android - 如何在最近的 Activity 刷出后在后台运行 Android 服务?

标签 android background-service android-intentservice

我有一个应该始终运行的后台服务。 它应该等待传入的电子邮件,当电子邮件到达(到我的旧手机)时,它会触发一个 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/

相关文章:

android - Android R 中的后台服务在省电模式下停止

android - IntentService 已弃用,如何将其替换为 JobIntentService?

android - 当应用程序处于后台时,startActivity() 不起作用(在这种特殊情况下)

android - 我如何进行文本查询并在 Android 中获取位置?

java - 结合setText使用方法(android studio)

java - Android 的接口(interface)方法是在哪个线程中调用的?同步还是异步?

android - 来自支持库的 SwipeRefreshLayout。 v21 不适用于静态内容

Android 位置更新作为后台服务

android - 让服务在后台运行而不显示通知

java - 无法找到显式 Activity 类 {};你有没有在你的 AndroidManifest.xml 中声明这个 Activity