简体   繁体   English

在Activity / App进入后台后60秒调用方法

[英]Calling a method 60 seconds after Activity/App goes background

I want to clear the clipboard after 60 seconds of putting a text onto the Android clipboard. 我想在将文本放到Android剪贴板上60秒后清除剪贴板。

I tried the handler postDelayed below. 我尝试了下面的处理程序postDelayed。 Problem is when the activity is killed or the app goes to background (home button clicked), this function does not execute. 问题是当活动被杀死或应用程序进入后台(单击主页按钮)时,此功能不会执行。 How can I make sure to call the function when app is in background? 如何在app处于后台时确保调用该函数?

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
           //Clear clipboard
        }
    }, 60000);

Since your Activity doesn't persist after the app is killed, you must go for a Service class. 由于您的活动在应用程序被杀后不会持续存在,因此您必须使用Service类。 There're some circumstances where it may also be killed, but in a normal basis it will persist in most cases (otherwise check foreground services). 在某些情况下,它也可能被杀死,但在正常情况下,它会在大多数情况下持续存在(否则检查前台服务)。

This approach should work: 这种方法应该有效:

Java Java的

public class TestClipboardServiceActivity extends Activity {
    @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startService(new Intent(this, MyClipboardService.class));

        // Forced the app to be destroyed intentionally.
        finish();
    }
}

/**
 * Clipboard Service. It will clear the clipboard after 60 seconds.
 */
public class MyClipboardService extends Service {

    public class LocalBinder extends Binder {
        MyClipboardService getService() {
            return MyClipboardService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyClipboardService", "Received start id " + startId + ": " + intent);

        // Remember, this is executed in the main thread.
        new Handler().postDelayed(new Runnable() {
            @Override public void run() {
                clearClipboard();
            }
        }, 6000);

        return START_STICKY;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * Clears the clipboard.
     */
    private void clearClipboard() {
        ClipboardManager myClipboard =
            (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (myClipboard != null) {
            myClipboard.setPrimaryClip(ClipData.newPlainText(null, "");
        }
    }
}

Kotlin 科特林

class TestClipboardServiceActivity : Activity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    startService(Intent(this, MyClipboardService::class.java))

    // Forced the app to be destroyed intentionally.
    finish()
  }
}

/**
 * Clipboard Service. It will clear the clipboard after 60 seconds.
 */
class MyClipboardService : Service() {

  private val mBinder = LocalBinder()

  inner class LocalBinder : Binder() {
    internal val service: MyClipboardService
      get() = this@MyClipboardService
  }

  override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    Log.i("MyClipboardService", "Received start id $startId: $intent")

    // Remember, this is executed in the main thread.
    Handler().postDelayed(this::clearClipboard, 60000)

    return START_STICKY
  }

  override fun onBind(intent: Intent) = mBinder

  /**
   * Clears the clipboard.
   */
  private fun clearClipboard() {
    val myClipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    myClipboard.primaryClip = ClipData.newPlainText(null, "")
  }
}

On the other hand, if you prefer to use a custom library to handle jobs, I'll strongly suggest android-job from Evernote. 另一方面,如果您更喜欢使用自定义库来处理作业,我强烈建议使用Evernote的android-job It internally even uses the recent WorkManager class and the library contains several scheduling variants, apart from compatibility for many Android API and the lack of Google Play Services library. 它内部甚至使用最近的WorkManager类,并且该库包含多个调度变体,除了许多Android API的兼容性和缺少Google Play服务库。 In your case you could take a look at the setExact(long exactInMs) method, providing an offset when the job should run from when the job was scheduled. 在您的情况下,您可以查看setExact(long exactInMs)方法,在作业从计划作业开始运行时提供偏移量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM