应用程序销毁后,保持服务活动

时间:2016-09-06 20:43:06

标签: android service broadcastreceiver alarmmanager

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

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);
    }

    ...
}

接收者类

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");
}

}

服务类

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"/>

代码工作正常,服务中的任务将定期执行。问题是当强制关闭应用程序时服务被破坏。我需要保持服务,能够执行任务,即使用户已关闭应用程序,因此可以通过通知更新用户。谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

相关问题