即使应用未处于活动状态,我也会尝试在特定时间实施发送通知 但它只适用于应用程序处于活动状态(已打开)
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis() + (5 * 1000)), broadcast);
接收器类:
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent it = new Intent(context, StartActivity.class);
createNotification(context, it, "new mensage", "body!", "this is a mensage");
}
public void createNotification(Context context, Intent intent, CharSequence ticker, CharSequence title, CharSequence descricao) {
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent p = PendingIntent.getActivity(context, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setTicker(ticker);
builder.setContentTitle(title);
builder.setContentText(descricao);
builder.setSmallIcon(R.drawable.icon);
builder.setContentIntent(p);
Notification n = builder.build();
//create the notification
n.vibrate = new long[]{150, 300, 150, 400};
n.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(R.drawable.icon, n);
//create a vibration
try {
Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone toque = RingtoneManager.getRingtone(context, som);
toque.play();
} catch (Exception e) {
}
}
}
androidmanifest:
<receiver android:name="com.example.atefhares.study_organizer.notifications_related.AlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
任何人都知道如何解决这个问题,拜托?