在应用程序被销毁后保持服务存活

Keep service alive after app has been destroyed

我正在开发一个应用程序,它需要每隔特定的时间在服务器上进行一些检查。检查包括验证是否有一些通知要显示。为了达到这个目标,我实现了服务、警报管理器和广播接收器。这是我目前使用的代码:

public class MainActivity  {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ...
        setRecurringAlarm(this);
    }

    /**
     *
     * @param context
     */
    private void setRecurringAlarm(Context context) {
        Calendar updateTime = Calendar.getInstance();

        Intent downloader = new Intent(context, MyStartServiceReceiver.class);
        downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), 60000, pendingIntent);
    }

    ...
}

接收者class

public class MyStartServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Intent dailyUpdater = new Intent(context, MyService.class);
    context.startService(dailyUpdater);
    Log.e("AlarmReceiver", "Called context.startService from AlarmReceiver.onReceive");
}

}

服务class

public class MyService extends IntentService {
    public MyService() {
        super("MyServiceName");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e("MyService", "Service running!");

        // TODO Do the hard work here

        this.sendNotification(this);
    }

    private void sendNotification(Context context) {
        // TODO Manage notifications here
    }
}

Manifest.xml

<!--SERVICE AND BROADCAST RECEIVER-->
    <service
        android:name=".MyService"
        android:exported="false"/>
    <receiver
        android:name=".MyStartServiceReceiver"
        android:process=":remote"/>

代码运行良好,服务中的任务将定期执行。问题是当应用程序被强制关闭时服务被破坏。我需要让服务保持活动状态,能够执行任务,即使用户关闭了应用程序,也可以通过通知更新用户。感谢您的宝贵时间!

你不能。如果应用程序被强制关闭,这意味着它崩溃了(在这种情况下,服务必须停止,因为它可能不再正常工作)或者用户强制关闭它,在这种情况下,用户希望应用程序停止——这意味着用户不希望服务 运行。允许服务自动重启,即使用户停止它基本上也是将恶意软件写入 OS.

事实上,Android 采取了完全相反(并且正确)的方式 - 如果用户强行停止应用程序,则应用程序的任何内容都无法 运行 直到用户 运行s再次手动。

您可以通过 this。我希望这会解决你的问题。如果你想保持清醒你的服务几乎不可能重新启动强制关闭的应用程序。因此,如果您禁用强制停止,您的问题可能会得到解决。