前一篇文章: https://blog.csdn.net/qq_40803752/article/details/86182480
前一篇讲解了,我应用的后台保活。这篇文章说下,前台,还有保活的关闭,
把无限音乐的放在工作服务,还有工作服务的保活效果测试。
1.工作服务 :无限播放音乐 ,并且设置变量,可以关闭播放,如果是在其他服务,就
不好控制关闭了。
public class DownloadService extends Service {
public Context mContext=this;
private MediaPlayer mMediaPlayer;
private Timer mRunTimer;
private int mTimeSec;
private int mTimeMin;
private int mTimeHour;
@Override
public void onCreate() {
super.onCreate();
mContext=this;
//后台播放无声 音乐
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.no_notice);
mMediaPlayer.setLooping(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("TAG","onStartCommand");
mContext=this;
new Thread(new Runnable() {
@Override
public void run() {
startPlayMusic();
}
}).start();
return START_STICKY;
}
private void startPlayMusic() {
if (mMediaPlayer != null) {
mMediaPlayer.start();
}
}
private void stopPlayMusic() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mDownloadBinder;
}
@Override
public boolean onUnbind(Intent intent) {
Log.e("TAG","onUnbind");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (mManager == null) {
return;
}
mManager.cancel(NOTICE_ID);
stopRunTimer();
stopPlayMusic();
// 重启自己
if (sign){
Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class);
startService(intent);
}
}
}
2.设置前台代码:
/**
* 启动前台通知
*/
private void showNotification() {
String string = mContext.getResources().getString(R.string.app_name_);
//创建通知详细信息
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo)
.setContentTitle(string)
.setContentText(“系统后台服务”);
// Intent intent = new Intent(this, MainProgramActivity.class);
//创建任务栈Builder
//获取通知服务
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//获取PendingIntent
Intent mainIn