如何像QQ一样进程不被系统杀死

如何像QQ一样进程不被系统杀死

2018-01-29 香沙小熊 代码集中营

点击上方“代码集中营”,选择“置顶公众号”

优秀文章,第一时间送达!

今天介绍一个android的Service,他是一个后台服务,专门用来处理常驻后台的工作组件。我们用的即时通讯,service来做常驻后台

进程优先级

进程的重要性优先级:

1. 前台进程:Foreground process

用户正在交互的Activity(onResume()

当某个Service绑定正在交互的Activity

被主动调用为前台的Service(startForeground())

组件正在执行生命周期的回调((onCreate() /onStart()/onDestory())

BroadcastReceiver 正在执行onReceive();

2.可见进程:Visible process

我们的Activity处在onPause() (没有进入onStop())

绑定到前台Activity的Service

3.服务进程:Service process

简单的startservice()启动

4.后台进程:Background process

对用户没有直接影响的进程-----Activity处于onStop()的时候

5.空进程    :Empty process

不含有任何的活动的组件。(android设计的,为了第二次启动更快,采取了一个权衡)

进程越往后越容易被系统杀死

如何不被系统杀死

我们要如何提升进程的优先级(尽量做到不轻易被系统杀死),提供以下七个方案

1. 模仿QQ采取在锁屏的时候启动1个像素的Activity。

背景:当手机锁屏的时候什么都干死了,为了省电。

监听锁屏广播,锁了---启动这个1像素Activity。

监听锁屏的,  开启---结束掉这个1像素Activity。

要监听锁屏的广播---动态注册。

关键代码:

publicclassKeepLiveActivityManager{

privatestaticKeepLiveActivityManager instance;

privateContext context;

privateWeakReference activityInstance;

publicstaticKeepLiveActivityManagergetInstance(Context context){

if(instance==null){

instance =newKeepLiveActivityManager(context.getApplicationContext());

}

returninstance;

}

privateKeepLiveActivityManager(Context context){

this.context = context;

}

publicvoidsetKeepLiveActivity(Activity activity){

activityInstance =newWeakReference(activity);

}

publicvoidstartKeepLiveActivity(){

Intent intent =newIntent(context, KeepLiveActivity.class);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(intent);

}

publicvoidfinishKeepLiveActivity(){

if(activityInstance!=null&&activityInstance.get()!=null){

Activity activity = activityInstance.get();

activity.finish();

}    }

}

源码地址:https://github.com/kpioneer123/KeepLiveProcess

2. 大型App运营商和手机厂商可能有合作关系---白名单

3. 双进程守护

一个进程被杀死,另外一个进程又被他启动,相互监听启动。

A<---->B

杀进程是一个一个杀的,本质是和杀进程时间赛跑。

关键代码:

publicclassLocalServiceextendsService{

publicstaticfinalString ACTION_LOCAL_SERVICE ="com.haocai.app.keepliveprocess.LocalService";

privatestaticfinalString TAG ="LocalService";

privateMyServiceConnection conn;

privateMyBinder binder;

privateIntent testIntent;

@Override

publicvoidonCreate(){

// TODO Auto-generated method stub

super.onCreate();

if(binder ==null){

binder =newMyBinder();

}

conn =newMyServiceConnection();

}

@Nullable

@Override

publicIBinderonBind(Intent intent){

returnbinder;

}

@Override

publicvoidonDestroy(){

super.onDestroy();

if(testIntent!=null){

stopService(testIntent);

}

//unbindService(conn);

}

//启动前台进程 增加重要性优先级

@Override

publicintonStartCommand(Intent intent,intflags,intstartId){

LocalService.this.bindService(newIntent(LocalService.this, RemoteService.class), conn, Context.BIND_IMPORTANT);

PendingIntent contentIntent = PendingIntent.getService(this,0, intent,0);

NotificationCompat.Builder builder =newNotificationCompat.Builder(this);

builder.setTicker("360")

.setContentIntent(contentIntent)

.setContentTitle("我是360,我怕谁!")

.setAutoCancel(true)

.setContentText("hehehe")

.setWhen( System.currentTimeMillis());

//把service设置为前台运行,避免手机系统自动杀掉改服务。

startForeground(startId, builder.build());

returnSTART_STICKY;

}

classMyBinderextendsRemoteConnection.Stub{

@Override

publicStringgetProcessName()throwsRemoteException{

// TODO Auto-generated method stub

return"LocalService";

}

}

classMyServiceConnectionimplementsServiceConnection{

@Override

publicvoidonServiceConnected(ComponentName name, IBinder service){

Log.i(TAG,"建立连接成功!");

}

@Override

publicvoidonServiceDisconnected(ComponentName name){

Log.i(TAG,"本地服务被干掉了~~~~~断开连接!");

Toast.makeText(LocalService.this,"断开连接", Toast.LENGTH_SHORT).show();

//启动被干掉的

testIntent =newIntent();

//自定义的Service的action

testIntent.setAction(RemoteService.ACTION_REMOTE_SERVICE);

//自定义Service的包名

testIntent.setPackage(getPackageName());

Log.i("999", getPackageName() +"");

startService(testIntent);

LocalService.this.bindService(newIntent(LocalService.this, RemoteService.class), conn, Context.BIND_IMPORTANT);

}

}

}

源码地址:https://github.com/kpioneer123/KeepLiveProcess2

4. JobScheduler

把任务加到系统调度队列中,当到达任务窗口期的时候就会执行,我们可以在这个任务里面启动我们的进程。这样可以做到将近杀不死的进程。

@SuppressLint("NewApi")

publicclassJobHandleServiceextendsJobService{

publicstaticfinalString ACTION_JOB_HANDLE_SERVICE ="com.haocai.app.keepliveprocess.JobHandleService";

privateintkJobId =0;

@Override

publicvoidonCreate(){

super.onCreate();

Log.i("INFO","jobService create");

}

@Override

publicintonStartCommand(Intent intent,intflags,intstartId){

Log.i("INFO","jobService start");

scheduleJob(getJobInfo());

returnSTART_NOT_STICKY;

}

@Override

publicvoidonDestroy(){

// TODO Auto-generated method stub

super.onDestroy();

}

@Override

publicbooleanonStartJob(JobParameters params){

// TODO Auto-generated method stub

Log.i("INFO","job start");

//      scheduleJob(getJobInfo());

booleanisLocalServiceWork = isServiceWork(this, LocalService.ACTION_LOCAL_SERVICE);

booleanisRemoteServiceWork = isServiceWork(this, RemoteService.ACTION_REMOTE_SERVICE);

//      Log.i("INFO", "localSericeWork:"+isLocalServiceWork);

//      Log.i("INFO", "remoteSericeWork:"+isRemoteServiceWork);

if(!isLocalServiceWork||

!isRemoteServiceWork){

//this.startService(new Intent(this,LocalService.class));

startLocalService();

startRemoteService();

//this.startService(new Intent(this,RemoteService.class));

Toast.makeText(this,"process start", Toast.LENGTH_SHORT).show();

}

returntrue;

}

privatevoidstartLocalService(){

Intent  testIntent =newIntent();

//自定义的Service的action

testIntent.setAction(LocalService.ACTION_LOCAL_SERVICE);

//自定义Service的包名

testIntent.setPackage(getPackageName());

Log.i("999",getPackageName()+"");

startService(testIntent);

}

privatevoidstartRemoteService(){

Intent testIntent =newIntent();

//自定义的Service的action

testIntent.setAction(RemoteService.ACTION_REMOTE_SERVICE);

//自定义Service的包名

testIntent.setPackage(getPackageName());

Log.i("999", getPackageName() +"");

startService(testIntent);

}

@Override

publicbooleanonStopJob(JobParameters params){

Log.i("INFO","job stop");

//      Toast.makeText(this, "process stop", Toast.LENGTH_SHORT).show();

scheduleJob(getJobInfo());

returntrue;

}

/** Send job to the JobScheduler. */

publicvoidscheduleJob(JobInfo t){

Log.i("INFO","Scheduling job");

JobScheduler tm =

(JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

tm.schedule(t);

}

publicJobInfogetJobInfo(){

JobInfo.Builder builder =newJobInfo.Builder(kJobId++,newComponentName(this, JobHandleService.class));

builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);

builder.setPersisted(true);

builder.setRequiresCharging(false);

builder.setRequiresDeviceIdle(false);

builder.setPeriodic(10);//间隔时间--周期

returnbuilder.build();

}

/**

* 判断某个服务是否正在运行的方法

*

*@parammContext

*@paramserviceName

*            是包名+服务的类名(例如:net.loonggg.testbackstage.TestService)

*@returntrue代表正在运行,false代表服务没有正在运行

*/

publicbooleanisServiceWork(Context mContext, String serviceName){

booleanisWork =false;

ActivityManager myAM = (ActivityManager) mContext

.getSystemService(Context.ACTIVITY_SERVICE);

List myList = myAM.getRunningServices(100);

if(myList.size() <=0) {

returnfalse;

}

for(inti =0; i < myList.size(); i++) {

String mName = myList.get(i).service.getClassName().toString();

if(mName.equals(serviceName)) {

isWork =true;

break;

}

}

returnisWork;

}

}

5. 监听QQ,微信,系统应用,友盟,小米推送等等的广播,然后把自己启动了。

6. 利用账号同步机制唤醒我们的进程AccountManager

7. NDK来解决,Native进程来实现双进程守护。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容

  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,327评论 0 17
  • 一、鸡汤 appwidget是android中小组件,我们经常说的widget其实是指的那些button、text...
    欢乐斗佛阅读 2,200评论 1 8
  • 豆豆《天幕红尘》开篇讲述了罗家明践行“见路不走“而自杀于莫斯科。 罗家明的莫斯科投资失败自杀,他对“见路不走”的理...
    小辈伐道_Hunter阅读 382评论 0 0
  • 古有男子汉大丈夫顶天立地,今有女汉纸敢做敢当。到底发生什么事儿了呢? 我加入秦王会商学院合伙人一个月,我一小白,不...
    5253b13c684e阅读 465评论 0 0
  • 昨夜我梦见你 过去的太阳啊 萤火的人们像是骄傲的海女 什么是我们的生命里 只是我生命之颜色如蔷薇般鲜艳 有太阳也不...
    天魁诗词书画阅读 243评论 0 2