AlarmManager没有及时执行课程?

时间:2017-07-10 09:09:41

标签: android broadcastreceiver alarmmanager

在我的项目中,我想在每天的特定时间更改SharedPreference中的标志值,我已经实现了AlarmManager但它没有执行任务。 我调用接收器类的功能:

public void changeAttendaceFlag(){
        Log.d(TAG,"changeAttendaceFlag !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,14);
        calendar.set(Calendar.MINUTE,23);
        calendar.set(Calendar.SECOND,10);
        Intent activateLogin = new Intent(getApplicationContext(),Attendance.class);
        PendingIntent pendingIntent =
                PendingIntent.getBroadcast(getApplicationContext(),101,activateLogin,PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
    }

我的接收器类:

public class Attendance extends BroadcastReceiver {
    FcmSession fcmSession;
    private static final String TAG = "Attendance";
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, " Attendance Called !!!!!!!!!!!!!!!!!!!!", Toast.LENGTH_SHORT).show();
        fcmSession = new FcmSession(context);
        fcmSession.store_dialog_value(true);
        UtilsMethods utilsMethods = new UtilsMethods();
        String time = utilsMethods.getCurrentDateAndTime();
        Log.d(TAG,"change attendance flag  :"+time);
    }
}

2 个答案:

答案 0 :(得分:1)

尝试对大于19 API的targetSdk使用不精确而不是简单的重复。 检查此LINK

上的注意
  

注意:从API 19开始,所有重复警报都不准确。如果您的应用程序需要精确的交付时间,那么它必须使用一次性精确警报,每次重新安排如上所述。 targetSdkVersion早于API 19的旧应用程序将继续将所有警报(包括重复警报)视为完全警报。

所以,改变并尝试以下行: -

alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

<强>更新

此外,在某些手机设备(如小米联想)中,应用需要输入自动启动列表。如需参考答案,请查看此link.

答案 1 :(得分:1)

这只是答案的一部分。以下是您实施服务onStartCommand

的方式
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // this is where you run your changeAttendaceFlag() method
    return START_STICKY; // this will make your service recreate when your app is closed
}

一旦您的课程延伸Service

,我们就会提供以下返回类型
  

START_STICKY :使用此返回值可在关闭应用时重新创建服务。当你强制关闭你的应用程序时,服务将重新创建,但意图不会重新发送,因此服务将始终运行而不做任何事情。

     

START_NOT_STICKY :使用此返回值将使您的服务在关闭时无法重新创建。

     

START_REDELIVER_INTENT :使用此返回值会使您的服务功能类似于START_STICKY,但这次有意图时,它会重新发送它。

注意:一旦应用关闭,数据将重新实施,因为将重新创建服务。将数据保存在 SharedPreferences SQLite DB 中。

对于自动启动,您可以在设置中执行此操作,但是当您重新启动手机时,它将禁用自动启动,您需要启用它,这是一种非常糟糕的用户体验(我认为这适用于某些手机)。您也可以通过为 BOOT_COMPLETED 实施BroadcastReceiver来对您的服务进行自动启动。这是一个很好的例子https://stackoverflow.com/a/4562747/5870896