我有一个应该始终运行的后台服务。 它应该等待传入的电子邮件,当电子邮件到达(到我的旧手机)时,它会触发一个 Action 。 (向我的新手机发送短信)。不是一个聪明的用户案例,只是学习 android。
但是,如果我将应用程序保留在“最近”应用程序中,则上述所有操作都可以正常工作。我把它刷掉的那一刻,它不起作用。
关于如何实现此目标的任何想法?
我在 Whatsapp、Facebook 等一些应用程序中看到,即使在我们滑动之后,后台服务仍在运行以收听新通知等。 我如何使用我的应用程序实现?
最佳答案
为此,您需要使服务粘性返回 START_STICKY onStartCommand 的服务。并且在文档中提到如果进程被终止系统将再次重新创建
if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.
public class MyService extends Service {
/*
* (non-Javadoc)
*
* @see android.app.Service#onBind(android.content.Intent)
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler.postDelayed(run, 1000);
return Service.START_STICKY;
}
private Runnable run = new Runnable() {
@Override
public void run() {
handler.removeCallbacks(run);
handler.sendEmptyMessage(0);
}
};
private Handler handler = new Handler() {
/*
* (non-Javadoc)
*
* @see android.os.Handler#handleMessage(android.os.Message)
*/
@Override
public void handleMessage(Message msg) {
Log.e("handleMessage", "" + System.currentTimeMillis());
handler.postAtTime(run, 1000);
}
};
}
关于android - 如何在最近的 Activity 刷出后在后台运行 Android 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28086490/