gpt4 book ai didi

android - 在通知单击时停止前台服务

转载 作者:搜寻专家 更新时间:2023-11-01 09:27:27 48 4
gpt4 key购买 nike

我正在学习 Android 服务。我的主要 Activity 中有一个按钮,单击该按钮后,将使用媒体播放器开始播放声音文件,并显示一条通知。我希望在单击通知时停止音乐服务并删除通知。几个小时以来,我一直在用头撞墙,因为我无法弄清楚自己做错了什么。这是我的服务等级:

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;
}

最佳答案

通过将未决 Intent 传递给广播来停止前台服务并在点击通知上打开 Activity 有什么问题:

创建广播接收器

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);
}

关于android - 在通知单击时停止前台服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684806/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com