我有一个播放音乐的服务(媒体播放器),它工作正常 .
-
如何确认此服务是一项前台服务?
-
如何模拟系统负载并检查服务是否会被杀死?
这是我的代码 .
public int onStartCommand(Intent intent,int flags,int startId){initMediaSession(); initMediaPlayer(); buildNotification(PlaybackStatus.PLAYING);
return super.onStartCommand(intent,flags,startId); }
private void buildNotification(PlaybackStatus playbackStatus){
final int NOTIFY_ID = 1002;
String aMessage="";
String name = "my_package_channel";
String id = "my_package_channel_1"; // The user-visible name of the channel.
String description = "my_package_first_channel"; // The user-visible description of the channel.
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
if (notifManager == null) {
notifManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(this, id);
intent = new Intent(this, NotificationReturnSlot.class);
pendingIntent = PendingIntent.getActivity(this, 1, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(this.getString(R.string.app_name)) // required
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{0L})
;
} else {
builder = new NotificationCompat.Builder(this);
intent = new Intent(this, NotificationReturnSlot.class);
pendingIntent = PendingIntent.getActivity(this, 1, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(this.getString(R.string.app_name)) // required
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{0L})
.setPriority(Notification.PRIORITY_HIGH);
}
int mId = 1489;
startForeground(mId, builder.build());
}
1 回答
}
如果你想知道你的服务是否在前台运行,只需打开一些其他胖应用程序,然后检查服务是否仍在运行或只是检查标志service.foreground
资料来源:How to determine if an Android Service is running in the foreground?