java - 使用 PendingIntent 停止服务

标签 java android android-intent android-service android-pendingintent

我的广播应用程序上有一个持续通知,并且我已经设法从该通知开始主要 Activity ,但现在我正在尝试向通知添加一个按钮以停止流媒体服务。

这是我在服务中的通知方法:

@SuppressWarnings("deprecation")
private void createNotification() {
    int myIconId = R.drawable.ic_pause;
    Intent mIntent = new Intent(context, StreamingService.class);
    Notification notification;
    Bundle bundle = new Bundle();
    bundle.putInt("list", list);
    PendingIntent stopIntent = PendingIntent.getService(context, 0, mIntent, 0) ;
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
            0, new Intent(getApplicationContext(), MainActivity.class)
                    .putExtras(bundle), PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        notification = new Notification();
        notification.tickerText = station.getRadioName();
        notification.icon = R.mipmap.ic_launcher;
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        notification.setLatestEventInfo(getApplicationContext(),
                station.getRadioName(), null, pi);
    } else {
        notification = new NotificationCompat.Builder(context)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(station.getRadioName())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(
                        BitmapFactory.decodeResource(
                                context.getResources(),
                                R.mipmap.ic_launcher))
                .addAction(myIconId,"STOP", stopIntent)
                .setOngoing(true).setContentIntent(pi).build();
    }

    startForeground(NOTIFICATION_ID, notification);
}

这是我的 OnStartCommand:

public int onStartCommand(Intent intent, int flags, int startId) {
    task = new ProgressTask();
    task.execute();
    return START_NOT_STICKY;
}

我使用了 Intent 和 PendingIntent 来启动服务,但是如何使用 PendingIntent 将服务设置为 stopSelf() ? 我被困在这个问题上好几天了,提前感谢您的帮助。

最佳答案

在你的 OnStartCommand 中使用这个

if(intent.getAction().equals("STOP"))
stopSelf();

关于java - 使用 PendingIntent 停止服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34427215/

相关文章:

java - PrimaryStage 无法解析为变量 :, 在其他类中使用时:JavaFX

Android Retrofit 2.0.0-beta2 Post string body 动态 header

android - 我在 Android studio 3.0 Beta 5 中运行应用程序时遇到 Multidex 问题

android - 服务和计时器同步

java - 在长时间运行的线程完成之前显示 Android 布局?

java - 从 Activity 中打开 pdf

Java 套接字服务器帮助

java - 从带有完整异常消息的命令行执行 jar

java - 如何获取Firestore文档ID?

java - 要在 java 中设置按钮点击延迟?