【发布时间】:2018-04-06 03:23:05
【问题描述】:
我正在学习 Android 服务。我的主要活动中有一个按钮,单击该按钮时,会使用媒体播放器开始播放声音文件,并显示通知。我希望在单击通知时停止音乐服务并删除通知。我已经把头撞在墙上几个小时了,因为我无法弄清楚我做错了什么。这是我的服务类:
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;
}
}
【问题讨论】:
-
你到底在问什么?你试过什么?
标签: android android-service android-notifications android-pendingintent