AlarmManager在app destroy上被杀死

时间:2016-02-23 20:35:04

标签: android alarmmanager repeat

我遇到以下问题:我在onCreate注册我的闹钟管理器,现在每分钟执行一次。 但是如果我通过Android taskmanager杀死了该应用(因此应用状态为destoyedAlarmReceiver停止了。为什么呢?

我的代码:

AlarmReceiver

public class AlarmReceiver extends WakefulBroadcastReceiver {

private AlarmManager mAlarm;
private PendingIntent mAlarmIntent;

@Override
public void onReceive(Context context, Intent intent) {
    Intent service = new Intent(context, PortalPullService.class);

    startWakefulService(context, service);
}

public void setAlarm(Context context) {
    mAlarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    mAlarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    int interval = context.getResources().getInteger(R.integer.update_interval_in_mins) * 60 * 1000;

    mAlarm.setInexactRepeating(
            AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + interval,
            interval,
            mAlarmIntent);

    ComponentName reciever = new ComponentName(context, AlarmBootReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(reciever,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

public void cancelAlarm(Context context) {
    if(mAlarm != null) {
        mAlarm.cancel(mAlarmIntent);
    }

    ComponentName reciever = new ComponentName(context, AlarmBootReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(reciever,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
}
}

PullService

public class PortalPullService extends IntentService {

private static final String LOG_TAG = "PortalPullService";

public PortalPullService() {
    super(LOG_TAG);
}

@Override
protected void onHandleIntent(Intent intent) {


    //TODO make request to ** check if new Infos are available, then send notification

    Helper.sendNotification(this, "Test", "Testnotification"); //My test if this works

    AlarmReceiver.completeWakefulIntent(intent);
}

}

的AndroidManifest.xml

<receiver android:name=".PortalUpdate.AlarmReceiver" />

<service
        android:name=".PortalUpdate.PortalPullService"
        android:exported="false" />   

接收者通过new AlarmReceiver().setAlarm(this);

注册

我搜索了几个问题,但我无法找到答案......我不知道我的错在哪里......

提前致谢;)

2 个答案:

答案 0 :(得分:1)

在华为安装应用程序的调试版本是个问题。

由于您可以在华为中禁用后台服务,并且华为没有将您的应用的调试版本识别为正确的应用程序,因此可能会出于安全原因而破坏所有服务......

在Play商店中正确安装有帮助!

答案 1 :(得分:0)

由于计划的PendingIntent是与您的应用相关联的令牌,并且如果该应用被强制终止,停止或休眠,系统将删除该应用。当用户再次启动您的应用时,您可以在onResumeonCreate重新设置它。