昨天面试问到了用服务保持唤醒这块内容,忘记了这方面的知识没能答得上来,翻开笔记本回顾一下,这篇博客就当作复习吧!
Service:是一个后台服务,专门用来处理常驻后台的工作组件(为核心服务专门开一个进程,跟其他的后台操作隔离)
一、进程的重要性优先级:(越往后的就越容易被系统杀死)
1.前台进程;Foreground process
1)用户正在交互的Activity(onResume())
2)当某个Service绑定正在交互的Activity。
3)被主动调用为前台Service(startForeground())
4)组件正在执行生命周期的回调(onCreate()/onStart()/onDestroy())
5)BroadcastReceiver 正在执行onReceive();
2.可见进程;Visible process
1)我们的Activity处在onPause()(没有进入onStop())
2)绑定到前台Activity的Service。
3.服务进程;Service process
简单的startService()启动。
4.后台进程;Background process
对用户没有直接影响的进程----Activity处于onstop()的时候
5.空进程; Empty process
不含有任何的活动的组件。(android设计的,为了第二次启动更快,采取的一个权衡)
二、如何提升进程的优先级(尽量做到不轻易被系统杀死)
1.QQ采取在锁屏的时候启动一个1个像素的Activity,当用户解锁以后将这个Activity结束掉(顺便同时把自己的核心服务再开启一次)。
当手机锁屏的时候什么都干死了,为了省电。因此,锁屏界面是盖在了手机应用界面的上面。
监听锁屏广播:
锁屏—启动这个Activity。
解锁—结束这个Activity。
代码实现如下:
MainActivty类:
package com.example.aaa;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
}
MyService类:
package com.example.aaa;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.example.aaa.ScreenListener.ScreenStateListener;
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
ScreenListener listener = new ScreenListener(this);
listener.begin(new ScreenStateListener() {
@Override
public void onScreenOn() {
// 开屏---finish这个一个像素的Activity
KeepLiveActivityManager.getInstance(MyService.this).finishKeepLiveActivity();
}
@Override
public void onScreenOff() {
// 锁屏---启动一个像素的Activity
KeepLiveActivityManager.getInstance(MyService.this).startKeepLiveActivity();
}
});
}
}
KeepLiveActivityManager类:
package com.example.aaa;
import java.lang.ref.WeakReference;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class KeepLiveActivityManager {
private static KeepLiveActivityManager instance;
private Context context;
private WeakReference<Activity> activityInstance;
public static KeepLiveActivityManager getInstance(Context context) {
if(instance==null){
instance = new KeepLiveActivityManager(context.getApplicationContext());
}
return instance;
}
private KeepLiveActivityManager(Context context) {
this.context = context;
}
public void setKeepLiveActivity(Activity activity){
activityInstance = new WeakReference<Activity>(activity);
}
public void startKeepLiveActivity() {
Intent intent = new Intent(context, KeepLiveActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Toast.makeText(context, "开启1像素Activity", 0).show();
}
public void finishKeepLiveActivity() {
if(activityInstance!=null&&activityInstance.get()!=null){
Activity activity = activityInstance.get();
activity.finish();
Toast.makeText(context, "结束1像素Activity", 0).show();
}
}
}
ScreenListener类:
package com.example.aaa;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.PowerManager;
public class ScreenListener {
private Context mContext;
private ScreenBroadcastReceiver mScreenReceiver;
private ScreenStateListener mScreenStateListener;
public ScreenListener(Context context) {
mContext = context;
mScreenReceiver = new ScreenBroadcastReceiver();
}
/**
* screen状态广播接收者
*/
private class ScreenBroadcastReceiver extends BroadcastReceiver {
private String action = null;
@Override
public void onReceive(Context context, Intent intent) {
action = intent.getAction();
if (Intent.ACTION_SCREEN_ON.equals(action)) { // 开屏
mScreenStateListener.onScreenOn();
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) { // 锁屏
mScreenStateListener.onScreenOff();
}
}
}
/**
* 开始监听screen状态
*
* @param listener
*/
public void begin(ScreenStateListener listener) {
mScreenStateListener = listener;
registerListener();
getScreenState();
}
/**
* 获取screen状态
*/
private void getScreenState() {
PowerManager manager = (PowerManager) mContext
.getSystemService(Context.POWER_SERVICE);
if (manager.isScreenOn()) {
if (mScreenStateListener != null) {
mScreenStateListener.onScreenOn();
}
} else {
if (mScreenStateListener != null) {
mScreenStateListener.onScreenOff();
}
}
}
/**
* 停止screen状态监听
*/
public void unregisterListener() {
mContext.unregisterReceiver(mScreenReceiver);
}
/**
* 启动screen状态广播接收器
*/
private void registerListener() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
mContext.registerReceiver(mScreenReceiver, filter);
}
public interface ScreenStateListener {// 返回给调用者屏幕状态信息
public void onScreenOn();
public void onScreenOff();
}
}
KeepLiveActivity类:
package com.example.aaa;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
public class KeepLiveActivity extends Activity {
private static final String TAG = "aaa";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "KeepLiveActivity----onCreate!!!");
Window window = getWindow();
window.setGravity(Gravity.LEFT|Gravity.TOP);
LayoutParams params = window.getAttributes();
params.height = 1;
params.width = 1;
params.x = 0;
params.y = 0;
window.setAttributes(params);
KeepLiveActivityManager.getInstance(this).setKeepLiveActivity(this);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i(TAG, "KeepLiveActivity----onDestroy!!!");
}
}
运行结果:
1.锁屏状态:
2.解锁状态:
2.双进程守护—可以防止单个进程杀死。听面试官说是最常用的方法
可以防止单个进程杀死,同时可以防止第三方的360清理掉。
一个进程被杀死,另外一个进程又被他启动。相互监听启动(即两个进程相互绑定)。用这种方法的时候,如果强行停止该应用,服务还是会被杀死的
代码实现如下:
MainActivity类:
package com.dn.keepliveprocess;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, LocalService.class));
startService(new Intent(this, RemoteService.class));
}
}
LocalService类:
package com.dn.keepliveprocess;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class LocalService extends Service {
public static final String TAG = "ricky";
private MyBinder binder;
private MyServiceConnection conn;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
if(binder ==null){
binder = new MyBinder();
}
conn = new MyServiceConnection();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
LocalService.this.bindService(new Intent(LocalService.this, RemoteService.class), conn, Context.BIND_IMPORTANT);
Toast.makeText(getApplicationContext(), "本地服务启动", 0).show();
return START_STICKY;
}
class MyBinder extends RemoteConnection.Stub{
@Override
public String getProcessName() throws RemoteException {
// TODO Auto-generated method stub
return "LocalService";
}
}
class MyServiceConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "建立连接成功!");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG, "RemoteService服务被干掉了~~~~断开连接!");
Toast.makeText(LocalService.this, "断开连接", 0).show();
//启动被干掉的
LocalService.this.startService(new Intent(LocalService.this, RemoteService.class));
LocalService.this.bindService(new Intent(LocalService.this, RemoteService.class), conn, Context.BIND_IMPORTANT);
}
}
}
RemoteService类:
package com.dn.keepliveprocess;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class RemoteService extends Service {
public static final String TAG = "ricky";
private MyBinder binder;
private MyServiceConnection conn;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
if(binder ==null){
binder = new MyBinder();
}
conn = new MyServiceConnection();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
RemoteService.this.bindService(new Intent(RemoteService.this, LocalService.class), conn, Context.BIND_IMPORTANT);
Toast.makeText(getApplicationContext(), "远程服务启动", 0).show();
return START_STICKY;//该标志位表示让系统尽量不杀死该服务
}
class MyBinder extends RemoteConnection.Stub{
@Override
public String getProcessName() throws RemoteException {
// TODO Auto-generated method stub
return "LocalService";
}
}
class MyServiceConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "建立连接成功!");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG, "LocalService服务被干掉了~~~~断开连接!");
Toast.makeText(RemoteService.this, "断开连接", 0).show();
//启动被干掉的
RemoteService.this.startService(new Intent(RemoteService.this, LocalService.class));
RemoteService.this.bindService(new Intent(RemoteService.this, LocalService.class), conn, Context.BIND_IMPORTANT);
}
}
}
运行结果:
3.JobScheduler
把任务加到系统调度队列中,当到达任务窗口期的时候就会执行,我们可以在这个任务里面启动我们的进程。
这样可以做到将近杀不死的进程(即使强行杀死进程也不会结束服务,个人觉得优于双进程守护)。
MainActivity:
package com.dn.keepliveprocess;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// startService(new Intent(this, LocalService.class));
// startService(new Intent(this, RemoteService.class));
startService(new Intent(this, JobHandleService.class));
}
}
JobHandleService:
package com.dn.keepliveprocess;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
@SuppressLint("NewApi")
public class JobHandleService extends JobService{
private int kJobId = 0;
@Override
public void onCreate() {
super.onCreate();
Log.i("INFO", "jobService create");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("INFO", "jobService start");
scheduleJob(getJobInfo());
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public boolean onStartJob(JobParameters params) {
// TODO Auto-generated method stub
Log.i("INFO", "job start");
boolean isLocalServiceWork = isServiceWork(this, "com.dn.keepliveprocess.LocalService");
boolean isRemoteServiceWork = isServiceWork(this,"com.dn.keepliveprocess.RemoteService");
if(!isLocalServiceWork||
!isRemoteServiceWork){
this.startService(new Intent(this,LocalService.class));
this.startService(new Intent(this,RemoteService.class));
Toast.makeText(this, "process start", Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.i("INFO", "job stop");
// Toast.makeText(this, "process stop", Toast.LENGTH_SHORT).show();
scheduleJob(getJobInfo());
return true;
}
/** Send job to the JobScheduler. */
public void scheduleJob(JobInfo t) {
Log.i("INFO", "Scheduling job");
JobScheduler tm =
(JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
tm.schedule(t);
}
public JobInfo getJobInfo(){
JobInfo.Builder builder = new JobInfo.Builder(kJobId++, new ComponentName(this, JobHandleService.class));
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
builder.setPersisted(true);
builder.setRequiresCharging(false);
builder.setRequiresDeviceIdle(false);
builder.setPeriodic(10);//间隔时间--周期
return builder.build();
}
/**
* 判断某个服务是否正在运行的方法
*
* @param mContext
* @param serviceName
* 是包名+服务的类名(例如:net.loonggg.testbackstage.TestService)
* @return true代表正在运行,false代表服务没有正在运行
*/
public boolean isServiceWork(Context mContext, String serviceName) {
boolean isWork = false;
ActivityManager myAM = (ActivityManager) mContext
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> myList = myAM.getRunningServices(100);
if (myList.size() <= 0) {
return false;
}
for (int i = 0; i < myList.size(); i++) {
String mName = myList.get(i).service.getClassName().toString();
if (mName.equals(serviceName)) {
isWork = true;
break;
}
}
return isWork;
}
}