我的广播接收器运行良好,但当我重新启动手机时,所有通知都停止工作。
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a52780.nontifications"
android:installLocation="internalOnly">
<uses-permission android:name="android.permission.SET_ALARM"/>
<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".AlarmReceiver"
android:priority="999">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
</manifest>
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Get id & message from Intent
int notificationId = intent.getIntExtra("notificationId", 0);
String message = intent.getStringExtra("text");
// when notif. is tapped, call MainActivity
Intent mainIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
NotificationManager myNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// PREPARE NOTIF
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("Wake up!")
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent);
myNotificationManager.notify(notificationId, builder.build());
}
}
我也尝试在接收器中添加android:enabled="true"和android:exported="false",但并没有起作用。应用程序安装在手机内存而不是SD卡上。无论如何,广播接收器都应该能够正常工作,但重启后它就不起作用了。
onReceive()
中记录任何内容,以确保原因不是通知。