我的应用程序中的问题是只有在启动后打开我的应用程序时才会调用OnBootResetAlarmReceiver。在我启动后打开我的应用程序之前,它不会被调用。 我在清单
中添加了BOOT_COMPLETED权限和意图过滤器我希望在启动后自动调用我的OnBootResetAlarmReceiver,而无需打开应用程序。
正如你所看到的,我已经添加了Log and Toast,但是在启动之后我无法看到任何一个,直到我打开我的应用程序。我错过了什么吗?
OnBootResetAlarmReceiver.java
public class OnBootResetAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SQLiteDatabase database = TodoOpenHelper.getOpenHelperInstance(context).getReadableDatabase();
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int count = 0;
Cursor cursor = database.query(TodoOpenHelper.TODO_TABLE, null, TodoOpenHelper.TODO_ALARM_STATUS+ " = 1", null, null, null, null);
while (cursor.moveToNext()) {
count++;
String title = cursor.getString(cursor.getColumnIndex(TodoOpenHelper.TODO_TASK));
long timeInEpoch = cursor.getLong(cursor.getColumnIndex(TodoOpenHelper.TODO_TIME));
int pendingIntentId = cursor.getInt(cursor.getColumnIndex(TodoOpenHelper.TODO_PENDING_INTENT_ID));
Intent showNotificationIntent = new Intent(context, ShowNotificationReceiver.class);
showNotificationIntent.putExtra(IntentConstants.TODO_TITLE, title);
showNotificationIntent.putExtra(IntentConstants.TODO_PENDING_ID, pendingIntentId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, pendingIntentId, showNotificationIntent, 0);
alarmManager.set(AlarmManager.RTC, timeInEpoch, pendingIntent);
}
Toast.makeText(context, "On boot receiver, count ="+count, Toast.LENGTH_SHORT).show();
Log.i("MyAppBootReceiver", "count = "+count);
cursor.close();
}
}
清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sahni.rahul.todo">
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/TodoTheme">
<activity
android:name=".activity.MainActivity"
android:theme="@style/TodoTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activity.AddTodoActivity" />
<receiver
android:name=".broadcastReceivers.ShowNotificationReceiver"
android:enabled="true"
android:exported="true" />
<receiver
android:name=".broadcastReceivers.OnBootResetAlarmReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver
android:name=".broadcastReceivers.NotificationActionReceiver"
android:enabled="true"
android:exported="true"/>
</application>