我正在尝试使用notificatoin和rington来发出警报。
我的工作:从我的活动中我通过使用alarmmanager调用BroadcastReceiver,而不是在BroadcastReceiver中使用NotificationCompat.Builder进行通知,之后我调用该服务。
{
private Intent notificationIntent;
@Override
public void onReceive(Context context, Intent intent) {
String title = intent.getStringExtra("myTitle");
notificationIntent = new Intent();
checkIntent(title, context);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.dumbbell)
.setContentTitle("Tracker")
.setContentText(title)
.setAutoCancel(true);
notificationManager.notify(1, builder.build());
Intent ringtoneIntent = new Intent(context, AlarmService.class);
context.startService(ringtoneIntent);
}
private void checkIntent(String title, Context context) {
switch (title){
case "Weight":
notificationIntent = new Intent(context, WeightActivity.class);
break;
case "Measure":
notificationIntent = new Intent(context, measurActivity.class);
break;
case "Pr":
notificationIntent = new Intent(context, PrsActivity.class);
break;
case "Macros":
notificationIntent = new Intent(context, DietActivity.class);
break;
}
}
公共类AlarmService扩展了服务{
private MediaPlayer alarmSong;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarmSong = MediaPlayer.create(this, R.raw.willy_william_voodoo);
alarmSong.start();
System.out.println("RING RING");
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
System.out.println("removed");
}
}
答案 0 :(得分:0)
据我了解,您想停止服务AKA停止铃声。 用户可以解除所有通知,或者如果您将通知设置为自动取消(您拥有),则在用户选择通知后也会将其删除。
您还可以在NotificationManager上为特定通知ID调用cancel()。 cancelAll()方法调用将删除您先前发出的所有通知。您还可以为服务实现新的PendingIntent以自行停止。
添加到OnStartCommand()
notificationManager.cancel(NOTIFCATION_ID);
stopSelf();
然后添加新的Intent
Intent stopSelf = new Intent(this, AlarmService.class);
stopSelf.setAction(this.ACTION_STOP_SERVICE);
PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,PendingIntent.FLAG_CANCEL_CURRENT);
notificationManager.notify(NOTIFCATION_ID, builder.build());
要停止实际的音乐播放,请在您的服务中调用alarmSong.stop()onDestroy()
!
希望它有所帮助!