这是代码
此函数从MainActivity.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.set(Calendar.HOUR_OF_DAY, 0);
alarmStartTime.set(Calendar.MINUTE, 00);
alarmStartTime.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,alarmStartTime.getTimeInMillis(),pendingIntent);
Log.d("Alarm","Set for midnight");
}
以下是updateTables的代码
public class UpdateTables extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Service Start", CalculateDaysService.TAG);
Log.d("BroadCast Receiver","yes");
context.startService(new Intent(context,CalculateDaysService.class));
Log.i("Done","Yes");
}
}
的Manifest.xml
<receiver android:name=".UpdateTables" android:enabled="true"/>
无法调用updateTable类。
更新
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.set(Calendar.HOUR_OF_DAY, 10);
alarmStartTime.set(Calendar.MINUTE, 29);
alarmStartTime.set(Calendar.SECOND, 0);
if (alarmStartTime.get(Calendar.HOUR_OF_DAY) >= 10) {
alarmStartTime.add(Calendar.DATE, 1);
}
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,alarmStartTime.getTimeInMillis(),100*1000,pendingIntent);
Log.d("Alarm","Set for midnight");
}
<receiver android:name=".UpdateTables"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
答案 0 :(得分:0)
更改强>
alarmManager.set(AlarmManager.RTC_WAKEUP,alarmStartTime.getTimeInMillis(),pendingIntent);
要强>
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,alarmStartTime.getTimeInMillis(),pendingIntent);
或强>
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,alarmStartTime.getTimeInMillis(),pendingIntent);
对于广播接收器,您已配置 AndroidManifest.xml
设置强>
android:exported = true
<强>更新强>
<强>的AndroidManifest.xml 强>
在<manifest>
标记
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
您的<application>
代码 中的
<receiver android:name="com.yourpackage.UpdateTables">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>