我想通过BroadcastReceiver发送通知。 AlarmReceiver发送的通知,但是当我点击通知时再次发送通知。同样的事情再次发生,一次又一次地像无尽的循环
这是我的AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher);
// This intent is fired when notification is clicked
Intent i = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
// Notifcation notify sound
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);
// Large icon appears on the left of the notification
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Have a good weekend");
//Notification click after clear notification
builder.setAutoCancel(true);
//Set notification sound
builder.setSound(alarmSound);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
}
和MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAlarm();
}
private void setAlarm(){
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(MainActivity.this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.DAY_OF_WEEK,6);
calendar.set(Calendar.HOUR_OF_DAY,16);
calendar.set(Calendar.MINUTE,53);
calendar.set(Calendar.SECOND,0);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
}
答案 0 :(得分:0)
点击通知时,它会打开MainActivity
,并在此活动的onCreate
方法中调用setAlarm()
。因此,在单击通知onCreate
方法时,将调用setAlarm()
,然后再次设置警报和构建通知。
执行以下更改
调用按钮的setAlarm()
onClick
,以便不会自动调用onCreate
个活动。
如果您想自动发送通知
更改notification
Intent i = new Intent(context, MainActivity.class);
截至目前,您正在使用意图点击通知打开ManinActivity
。
将Intent
更改为
Intent i = new Intent(context, OtherActivity.class);
OtherActivity是setAlarm()
方法中没有notification
或构建onCreate
的活动。
替代方法
使用sharedPreferences
检查通知是否构建一次。
如果构建一次则不要调用setAlarm()