1

我试图在每天的某个时间重新创建一项活动,例如每天早上 6 点。

目前,我的计划任务正在运行,但不是重新创建我的 Activity 一次,而是不断地重新创建它,就像它卡在一个循环中一样。

从我的主要活动中,我使用:

 scheduledRefresh.setAlarm(this);

然后在我预定的刷新中:

 public void onReceive(Context context, Intent intent) {   
    Intent service = new Intent(context, ScheduledRefreshService.class);       
    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, service);
}

//Alarm is set for a specific time each day
public void setAlarm(Context context) {
    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, ScheduledRefresh.class);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    // The alarm is set for 6 am daily
    calendar.set(Calendar.HOUR_OF_DAY, 06);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);


    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,  
            calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);

    ComponentName receiver = new ComponentName(context, ScheduledBootReceiver.class);
    PackageManager pm = context.getPackageManager();

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

public void cancelAlarm(Context context) {
    // If the alarm has been set, cancel it.
    if (alarmMgr!= null) {
        alarmMgr.cancel(alarmIntent);
    }

    ComponentName receiver = new ComponentName(context, ScheduledBootReceiver.class);
    PackageManager pm = context.getPackageManager();

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

这将调用我的计划刷新服务,该服务具有重新创建 Activity 的代码:

 protected void onHandleIntent(Intent intent) {
    //restart mainActivity
    Intent map = new Intent(MainActivity.getContext(),MainActivity.class);          
    map.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    MainActivity.getContext().startActivity(map);
    ScheduledRefresh.completeWakefulIntent(intent);
}

然而,正如我所提到的,它只是不断地重新启动 Activity,而不是仅仅一次——这就是它需要工作的方式。

多年来,我一直在努力解决这个问题!

4

0 回答 0