我试图让用户能够设置通知的自定义日期和时间。我创建了一个NofiticationPublisher
类,扩展BroadcastReciver
来处理它的设置。每当我尝试调用它时,它都不起作用。我的代码出了什么问题?
NotificationPublisher的:
public class NotificationPublisher extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
String name = intent.getStringExtra("Name");
String description = intent.getStringExtra("Description");
int id = intent.getIntExtra("Id", 0); // 0 is default
NotificationCompat.Builder b = new NotificationCompat.Builder(context);
b.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_stat_check)
.setContentTitle(name)
.setContentText(description)
.setTicker("Ticker test");
notificationManager.notify(id , b.build());
}
}
清单:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xxx.xxx.xxx">
<uses-permission android:name="xxx.xxx.xxx.alarm.permission.SET_ALARM" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
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>
<activity android:name=".example1" />
<activity android:name=".example2" />
<receiver android:name="xxx.xxx.xxx.NotificationPublisher" android:enabled="true" />
</application>
创建通知的部分活动:
if(notifications == true) {
Intent intentAlarm = new Intent(this, NotificationPublisher.class);
intentAlarm.putExtra("Name", name);
intentAlarm.putExtra("Description", description);
intentAlarm.putExtra("Id", id);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, (System.currentTimeMillis() + 5 * 1000), pendingIntent); // The time is an example
}