在通知点击时停止前台服务

3

我正在学习Android服务。在我的主活动中有一个按钮,当点击它时,使用MediaPlayer开始播放音频文件,并显示通知。我想在点击通知时停止音乐服务并删除通知。我已经苦思冥想了几个小时,但是无法找出我的错误。这是我的服务类:

public class MusicService extends Service {
public MusicService() {
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    MediaPlayer player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
    player.setLooping(true);
    player.start();

    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("Hello")
            .setTicker("Hello 2")
            .setContentText("Hello 3")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build();

    startForeground(NOTIFICATION_ID.FOREGROUND_SERVICE, notification);


    return START_STICKY;
}

public interface NOTIFICATION_ID {
    public static int FOREGROUND_SERVICE = 101;
}

}


你到底在问什么?你尝试过什么? - David Wasser
1个回答

5

如何通过传递待处理意图到广播来停止前台服务并打开活动:

创建广播接收器

public class MusicNotificationBroadcastReceiver extends BroadcastReceiver {

   @Override
   public void onReceive(Context context, Intent intent) {
      // Start Activity
      Intent activityIntent = new Intent(context, MainActivity.class);
      activityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
      context.startActivity(activityIntent);
      // Start Services
      startService(new Intent(this, MusicService.class).setAction("STOP_ACTION"));
   }
}

创建通知:

Intent intent = new Intent(context, MusicNotificationBroadcastReceiver.class);
PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    
Notification notification = new NotificationCompat.Builder(this)
        .setContentTitle("Hello")
        .setTicker("Hello 2")
        .setContentText("Hello 3")
        .setSmallIcon(R.drawable.ic_launcher_foreground)
        .setContentIntent(contentIntent)
        .setOngoing(true)
        .build();

因此,在onStartCommand中处理如下:

if (intent.getAction() != null && intent.getAction().equals("STOP_ACTION")) {
     stopForeground(true);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接