java - Android 应用关闭后正确重启服务

标签 java android service background-service long-running-processes

我目前正在开发一个依赖后台服务的电子邮件应用程序,以便能够自动获取新电子邮件。当应用程序打开(或在应用程序的运行列表中)时,这非常有效,但是一旦我关闭应用程序/将其从最近的应用程序列表中删除,服务也会停止。这可以通过进入设备上的“开发人员设置”并查看没有为我的应用程序运行的进程或服务来确认。

我在 StackOverflow 上阅读了无数线程,但似乎没有一个能解决问题。有时调用 onTaskRemoved() 并重新启动服务,但有时根本不调用或调用它,日志显示操作系统已安排重新启动 服务 但随后 service 被操作系统强制关闭 而我总是需要运行此服务来检索新电子邮件。

我当前的代码如下:

我的服务:

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        Log.i(TAG, "onStartCommand()");

        ...

        Log.d(TAG, "SERVICE IS RUNNING");

        if (host != null) {
            Log.d(TAG, "STARTING PUSH SERVICE");

            Handler handler = new Handler();
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "BR: " + ((BugReporting) getApplication()));
                    sharedRunnable = ((BugReporting) getApplication()).getSharedRunnable();

                    MailPush mailPush = new MailPush(getApplicationContext(), sharedRunnable);
                    Log.d(TAG, "sharedRunnable 1: " + sharedRunnable);
                    mailPush.checkInboxEmail(host, email, password);
                    //mailPush.checkSentEmail(host, email, password);
                }
            };
            handler.postDelayed(runnable, 5000);//0.5 seconds

        }

        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate()");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Log.i(TAG, "onTaskRemoved()");

        PendingIntent service = PendingIntent.getService(
                getApplicationContext(),
                1001,
                new Intent(getApplicationContext(), MyService.class),
                PendingIntent.FLAG_ONE_SHOT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy()");
        startService(new Intent(this, MyService.class));
    }

重启接收器:

 public class AutoStart extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, MyService.class));
    }
}

list :

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

...

        <receiver
                android:name="uk.co.tundracorestudios.securemail.notification.AutoStart"
                android:enabled="true"
                android:exported="true"
                android:process=":remote">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </receiver>

            <service
                android:name="uk.co.tundracorestudios.securemail.notification.MyService"
                android:enabled="true"
                android:exported="true"
                android:label="@string/mail_service"
                android:stopWithTask="false"/>

我确实尝试将 MyService 作为一个不同的 process 运行,但这限制了我获取我保存在应用程序中的 sharedRunnable可以通过其他方式访问的类:

 updateListRunnable = ((BugReporting) getApplication()).getSharedRunnable();

因此,我想问的是,如何确保我的服务持续运行/工作,即使在应用程序关闭或设备重新启动时仍然可以访问到位于 getApplication() 中的组件?

当我尝试将 MyService 作为单独的 进程 运行时,上面的 updateListRunnable 将始终返回 null,而当应用程序和 service 运行在同一个 process 中,它会返回正确的 runnable

最佳答案

不久前我遇到了类似的问题,并在我的服务的 onDestroy() 方法中使用了它:

public void onDestroy() {
    Intent restartService = new Intent(getApplicationContext(),this.getClass());
    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),1,restartService,PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME,5000,pendingIntent);
    super.onDestroy();
}

当服务被销毁时,我设置了 5 秒的警报,这将再次启动我的服务。这样,当用户从最近删除它时,您的服务将停止,但它会重新启动。

关于java - Android 应用关闭后正确重启服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41673278/

相关文章:

android - 如何将音频文件从android客户端发送到servlet服务器

java - 将 Groovy Grails 服务注入(inject) Java 类

java - 首次运行时 HttpURLConnection 由对等方重置...可立即重新运行

java - 如何在 Android studio 中一次运行多个案例

android - getview 方法未在 android 中的自定义 listview 方法中调用

java - 使用java代码以编程方式创建android应用程序

java - WinRun4J 服务示例不运行

c# - Windows 服务 (c#) 未启动

java - Android - Eclipse - docUri 是什么意思?

Java 数据包嗅探器