这是代码
此函数从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");
}
}
清单文件
<receiver android:name=".UpdateTables" android:enabled="true"/>
无法调用updateTable类。
更新:
私人无效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>
最佳答案
更改
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
see this link
更新
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>
关于java - 在午夜运行服务而不启动应用程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40325913/