最近在适配8.0程序,发现之前用的电源管理等等操作都无法使程序在点击home键后,息屏状态下存活。小米、华为均测试过,失败告终。
有人可能会说去电源设置里更改后台运行设置,那是人为操作,不是程序员该做的。而且装了酷狗之后发现人家也没进行后台设置啊,歌不是妥妥的播放吗?
所以考虑了半天,发现了新大陆,抱着试试看的心理去实现了,嘿,结果完美解决了。
大家也别老是盯着网上的那些解决办法,很多都是CTRL+C/CTRL+V来的,坑的一逼。
官网给的建议是显示调用一个前台service,然后就能保证不被杀,好吧,也许对于国外的手机可以,国内就呵呵了。
废话不多说,正确打开方式开启:
1.准备一个前台BackGroundService
我的例子是BackGroundService,名字土,别吐槽
public class BackGroundService extends Service {
Notification notification;
private Context mContext;
private static Thread uploadGpsThread;
private MediaPlayer bgmediaPlayer;
private boolean isrun = true;
public MyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = this;
Intent notificationIntent = new Intent(this, GPSPathActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//1.通知栏占用,不清楚的看官网或者音乐类APP的效果
notification = new Notification.Builder(mContext)
.setSmallIcon(R.drawable.audioflag)
.setWhen(System.currentTimeMillis())
.setTicker("GPS测试")
.setContentTitle("GPS测试标题")
.setContentText("GPS测试内容")
.setOngoing(true)
.setPriority(PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.build();
/*使用startForeground,如果id为0,那么notification将不会显示*/
startForeground(100, notification);
//2.开启线程(或者需要定时操作的事情)
if(uploadGpsThread == null){
uploadGpsThread = new Thread(new Runnable() {
@Override
public void run() {
//这里用死循环就是模拟一直执行的操作
while (isrun){
//你需要执行的任务
doSomething();
try {
Thread.sleep(10000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
//3.最关键的神来之笔,也是最投机的动作,没办法要骗过CPU
//这就是播放音乐类APP不被杀的做法,自己找个无声MP3放进来循环播放
if(bgmediaPlayer == null){
bgmediaPlayer = MediaPlayer.create(this,R.raw.wusheng);
bgmediaPlayer.setLooping(true);
bgmediaPlayer.start();
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onDestroy() {
isrun = false;
stopForeground(true);
bgmediaPlayer.release();
stopSelf();
super.onDestroy();
}
}
2. 在对应的activity里显示开启service
Intent forgroundService = new Intent(this,BackGroundService.class);
startService(forgroundService);
3. 在AndroidManifest.xml文件里申明service
<service android:name=".BackGroundService" android:enabled="true" android:exported="true" />
就这么简单,第一、二步是官方方法,第三步是我琢磨出来的,启发来自某音乐播放器,当然你可以加自己的自定义通知栏、广播等等,都可以扩展,这能保证你的service永不kill