我知道这是一个重复的问题,但我已尝试在互联网上提供的所有解决方案,但无法找到解决方案。
清单文件
<receiver android:name=".UpdateTables"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
在 mainActivity .java的onCreate()
中调用此方法,我也尝试从应用程序类调用该方法。
private void setTheTimeToUpdateTables(Context context) {
Log.i("Update table function","Yes");
AlarmManager alarmManager=(AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent=new Intent(context,UpdateTables.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(context,0,alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//alarmManager.cancel(pendingIntent);
Calendar alarmStartTime = Calendar.getInstance();
alarmStartTime.setTimeInMillis(System.currentTimeMillis());
//midnight
alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
alarmStartTime.set(Calendar.MINUTE, 1);
alarmStartTime.set(Calendar.SECOND, 0);
if(Calendar.getInstance().getTimeInMillis()>alarmStartTime.getTimeInMillis())
{
alarmStartTime.add(Calendar.DATE,1);
}
Log.i("TIME IS ",Long.toString(alarmStartTime.getTimeInMillis()));
System.out.println("Updating table time "+alarmStartTime);
System.out.println("Time in millseconds "+alarmStartTime.getTimeInMillis());
alarmManager.setInexactRepeating(AlarmManager.RTC,alarmStartTime.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
Log.d("Alarm","Set for midnight");
}
public class UpdateTables extends BroadcastReceiver {
//midnight saga
DbHelper dbHelper;
ArrayList<ListMedicine> reminderInfo;
private SharedPreferences sharedPreferences;
private static AlarmManager alarmManager;
private static void init(Context ctx){
if (alarmManager==null)
alarmManager=(AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Update tables","yes");
}
当app关闭时,updatetables广播接收器将不会调用。
在应用程序关闭之前,输出./adb shell dumpsys警报。
RTC #5: Alarm{28e47fec type 1 when 1487010660087 user.com.hlthee}
tag=*alarm*:user.com.hlthee/.UpdateTables
type=1 whenElapsed=+23h48m35s946ms when=2017-02-14 00:01:00
window=-1 repeatInterval=86400000 count=0
operation=PendingIntent{24cc8fb5: PendingIntentRecord{19e0864a user.com.hlthee broadcastIntent}}
但是当应用程序从最近的活动关闭时,此条目也会被删除。为什么? 这就是应用程序关闭时没有响铃的原因。 任何帮助,将不胜感激。
答案 0 :(得分:0)
定义自定义操作名称,例如:
public static final String MY_ACTION = "com.sample.myaction"
创建一个BroadcastReceiver:
public class MyAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(MY_ACTION)) {
// Do something here
}
}
}
在AndroidManifest.xml上注册接收器:
<receiver android:name="com.sample.MyAlarmReceiver">
<intent-filter>
<action android:name="com.sample.myaction"/>
</intent-filter>
设置闹钟,使用以下PendingIntent:
Intent i = new Intent(MY_ACTION);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);