最近有个需求需要建一个service永远在后台运行来接收推送消息和一些定时器工作,首先想到的就是双进程守护原则,然后再利用aidl相互唤醒连个service1和service2,但是这样有个问题如果app一直运行在后台的话 这两个service 是不会关闭的,但是一旦利用home键关闭这个app那么伴随着这个连个service都会被杀死,这是因为app未获取自启动权限,以往我们通过检测Android的开机广播就能获取启动 但是对小米和华为系统来说他们已经屏蔽了这种方式,所以我选择了一种让用户自己开启自启动全县的方式,跟他们弹出受理界面,这样service就能一直在后台运行了
service1:
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;
import com.plant.org.testserver.MainActivity;
import com.plant.org.testserver.R;
import com.plant.org.testserver.utils.Utils;
public class Service1 extends Service {
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
startService2();
break;
default:
break;
}
};
};
/**
* 使用aidl 启动Service2
*/
private StrongService startS2 = new StrongService.Stub() {
@Override
public void stopService() throws RemoteException {
Intent i = new Intent(getBaseContext(), Service2.class);
getBaseContext().stopService(i);
}
@Override
public void startService() throws RemoteException {
Intent i = new Intent(getBaseContext(), Service2.class);
getBaseContext().startService(i);
}
};
/**
* 在内存紧张的时候,系统回收内存时,会回调OnTrimMemory, 重写onTrimMemory当系统清理内存时从新启动Service2
*/
@Override
public void onTrimMemory(int level) {
/*
* 启动service2
*/
startService2();
}
@Override
public void onCreate() {
Toast.makeText(Service1.this, "Service1 正在启动...", Toast.LENGTH_SHORT)
.show();
startService2();
/*
* 此线程用监听Service2的状态
*/
new Thread() {
public void run() {
while (true) {
boolean isRun = Utils.isServiceWork(Service1.this,
"com.plant.org.testserver.service.Service2");
if (!isRun) {
Message msg = Message.obtain();
msg.what = 1;
handler.sendMessage(msg);
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}.start();
}
/**
* 判断Service2是否还在运行,如果不是则启动Service2
*/
private void startService2() {
boolean isRun = Utils.isServiceWork(Service1.this,
"com.plant.org.testserver.service.Service2");
if (isRun == false) {
try {
startS2.startService();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new Notification(R.mipmap.ic_launcher,getString(R.string.app_name), System.currentTimeMillis());
PendingIntent pendingintent = PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class), 0);
// notification.setLatestEventInfo(this, "uploadservice", "请保持程序在后台运行", pendingintent);
startForeground(0x111, notification);
return START_STICKY_COMPATIBILITY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return (IBinder) startS2;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.d("lib093","Service1清除");
}
}
----------------------------------------------------------------------------------------------------------------------
package com.plant.org.testserver.service;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.widget.Toast;
import com.plant.org.testserver.utils.Utils;
/**
* 934042435@qq.com
*
* @author lib093
*
*/
public class Service2 extends Service {
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
startService1();
break;
default:
break;
}
};
};
/**
* 使用aidl 启动Service1
*/
private StrongService startS1 = new StrongService.Stub() {
@Override
public void stopService() throws RemoteException {
Intent i = new Intent(getBaseContext(), Service1.class);
getBaseContext().stopService(i);
}
@Override
public void startService() throws RemoteException {
Intent i = new Intent(getBaseContext(), Service1.class);
getBaseContext().startService(i);
}
};
/**
* 在内存紧张的时候,系统回收内存时,会回调OnTrimMemory, 重写onTrimMemory当系统清理内存时从新启动Service1
*/
@Override
public void onTrimMemory(int level) {
startService1();
}
@SuppressLint("NewApi")
public void onCreate() {
Toast.makeText(Service2.this, "Service2 启动中...", Toast.LENGTH_SHORT)
.show();
startService1();
/*
* 此线程用监听Service2的状态
*/
new Thread() {
public void run() {
while (true) {
boolean isRun = Utils.isServiceWork(Service2.this,
"com.plant.org.testserver.service.Service1");
if (!isRun) {
Message msg = Message.obtain();
msg.what = 1;
handler.sendMessage(msg);
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}.start();
}
/**
* 判断Service1是否还在运行,如果不是则启动Service1
*/
private void startService1() {
boolean isRun = Utils.isServiceWork(Service2.this,
"com.plant.org.testserver.service.Service1");
if (isRun == false) {
try {
startS1.startService();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return (IBinder) startS1;
}
}
----------------------------------------------------------------------------------------------------------------------------
interface StrongService{
voidstartService();
voidstopService();
}
-------------------------------------------------------------------------------------------------------------------
/*打开自启动管理页*/
public voidopenStart(Context context){
if(Build.VERSION.SDK_INT<23){
return;
}
String system =getSystem();
Intent intent =newIntent();
if(system.equals(SYS_EMUI)){//华为
ComponentName componentName =newComponentName("com.huawei.systemmanager","com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");
intent.setComponent(componentName);
}else if(system.equals(SYS_MIUI)){//小米
ComponentName componentName =newComponentName("com.miui.securitycenter","com.miui.permcenter.autostart.AutoStartManagementActivity");
intent.setComponent(componentName);
}
try{
context.startActivity(intent);
}catch(Exception e){//抛出异常就直接打开设置页面
intent=newIntent(Settings.ACTION_SETTINGS);
context.startActivity(intent);
}
}
@Override
public voidonRequestPermissionsResult(intrequestCode, String permissions[],int[] grantResults) {
switch(requestCode) {
case11001:
if((grantResults.length>0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
//TODO
}
break;
default:
break;
}
}
@Override
protected voidonDestroy() {
super.onDestroy();
Log.d("lib093","MainActivity销毁");
Intent i1 =newIntent(MainActivity.this, Service1.class);
startService(i1);
}
public voidonClick(View v) {
switch(v.getId()) {
caseR.id.button1:
Intent i1 =newIntent(MainActivity.this, Service1.class);
startService(i1);
Intent i2 =newIntent(MainActivity.this, Service2.class);
startService(i2);
break;
}
}
public staticString getSystem(){
String SYS="";
try{
Properties prop=newProperties();
prop.load(newFileInputStream(newFile(Environment.getRootDirectory(),"build.prop")));
if(prop.getProperty(KEY_MIUI_VERSION_CODE,null) !=null
|| prop.getProperty(KEY_MIUI_VERSION_NAME,null) !=null
|| prop.getProperty(KEY_MIUI_INTERNAL_STORAGE,null) !=null){
SYS =SYS_MIUI;//小米
}else if(prop.getProperty(KEY_EMUI_API_LEVEL,null) !=null
||prop.getProperty(KEY_EMUI_VERSION,null) !=null
||prop.getProperty(KEY_EMUI_CONFIG_HW_SYS_VERSION,null) !=null){
SYS =SYS_EMUI;//华为
}else if(getMeizuFlymeOSFlag().toLowerCase().contains("flyme")){
SYS =SYS_FLYME;//魅族
};
}catch(IOException e){
e.printStackTrace();
returnSYS;
}
returnSYS;
}
public staticString getMeizuFlymeOSFlag() {
returngetSystemProperty("ro.build.display.id","");
}
private staticString getSystemProperty(String key, String defaultValue) {
try{
Class clz = Class.forName("android.os.SystemProperties");
Method get = clz.getMethod("get", String.class, String.class);
return(String)get.invoke(clz, key, defaultValue);
}catch(Exception e) {
}
returndefaultValue;
}