我試圖讓我的廣播接收器在啓動後立即運行。據我所知,廣播接收機無論重新啓動都會運行,而我剛剛瞭解到這一點,但我的問題是,我已將它設置爲每天晚上在午夜運行,而且我不想等到午夜才運行一次。這打破了目的。但是我需要它在重新啓動後立即運行。但它沒有運行。有人可以看到我是否做錯了什麼?我正在Galaxy S4和S6上嘗試此操作,並且未收到日誌消息,指出它已重新啓動。重新啓動後廣播接收器不能重新啓動
這是我的Manifest文件,你可以看到它是必要的權限。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".StartActivityAtBootReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
在我StartActivityAtBootReceiver我有跟的onReceive調用的主要活動將開始廣播接收機。
public void onReceive(Context context, Intent intent) {
Log.e("LOGS", "Start Activity after Rebooted ");
Intent rebootIntent = new Intent(context, MainActivity.class);
rebootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(rebootIntent);
}
在我的MainActivity我這就要求廣播接收器在擴展廣播接收器另一大類下面。
//run from boot or from button on screen
protected void runFromOutside() throws ParseException {
checkIfStartingNow();
startTheClock();
finish(); //close the app/view
}
//check if starting now pops up message to state that it is staring now
protected void checkIfStartingNow() throws ParseException {
//does some checks and displays a message popup
}
protected void startTheClock() {
// Set the alarm to run at midnight every night
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 00);
//calendar.set(Calendar.MINUTE, 01);
// Get the AlarmManager Service
mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// Create an Intent to broadcast to the Shhh
mNotificationReceiverIntent = new Intent(MainActivity.this, Shhh.class);
// Create an PendingIntent that holds the NotificationReceiverIntent
// mNotificationReceiverPendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, mNotificationReceiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationReceiverPendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, mNotificationReceiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Set repeating alarm that checks every minute.
mAlarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mNotificationReceiverPendingIntent);
// set true for alarm
settings.edit().putBoolean(NotificationOn, true).apply();
Log.e("LOGS", "Entered Start the midnight alarm");
}