十4、Android性能優化之Service

Service:是一個後臺服務,專門用來處理常駐後臺的工做組件。android

即時通信:service來作常駐後臺git

###1.核心服務儘量地輕! 不少人喜歡把全部的後臺操做都集中在一個service裏面。 爲核心服務專門作一個進程,跟其餘的全部後臺操做隔離。 樹大招風,核心服務千萬要輕。github

####進程的重要性優先級:bash

  • 前臺進程:Foreground process

    1.用戶正在交互的Activity(onResume()) 2.當某個Service綁定正在交互的Activity 3.被主動調用爲前臺的Service(startForeground()) 4.組件正在執行生命週期的回調((onCreate() /onStart()/onDestory()) 5.BroadcastReceiver 正在執行onReceive();微信

  • 可見進程:Visible process

    1.咱們的Activity處在onPause() (沒有進入onStop()) 2.綁定到前臺Activity的Serviceapp

  • #####服務進程:Service process 簡單的startservice()啓動ide

  • 後臺進程:Background process

    對用戶沒有直接影響的進程-----Activity處於onStop()的時候ui

  • #####空進程 :Empty process 不含有任何的活動的組件。(android設計的,爲了第二次啓動更快,採起了一個權衡)this

進程越日後越容易被系統殺死

###2、如何提高進程的優先級(儘可能作到不輕易被系統殺死)spa

1.模仿QQ採起在鎖屏的時候啓動1個像素的Activity。

背景:當手機鎖屏的時候什麼都乾死了,爲了省電。
  監聽鎖屏廣播,鎖了---啓動這個1像素Activity。
  監聽鎖屏的,  開啓---結束掉這個1像素Activity。
  要監聽鎖屏的廣播---動態註冊。
複製代碼

關鍵代碼:

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);
	}
	public void finishKeepLiveActivity() {
		if(activityInstance!=null&&activityInstance.get()!=null){
			Activity activity = activityInstance.get();
			activity.finish();
		}
	}

}
複製代碼
public class KeepLiveActivity extends Activity {
    private static final String TAG ="KeepLive" ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       moveTaskToBack(true); //按home鍵不退出程序

        Log.i(TAG,"KeepLiveActivity----onCreate");
        Window window = getWindow();
        window.setGravity(Gravity.LEFT|Gravity.TOP);
        WindowManager.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() {
        super.onDestroy();
        Log.i(TAG, "KeepLiveActivity----onDestroy!!!");
    }
}
複製代碼
public class MyService extends Service {


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        ScreenListener listener = new ScreenListener(this);
        listener.begin(new ScreenListener.ScreenStateListener() {
            @Override
            public void onScreenOn() {
                //開屏---finish這個一像素的Activity
                KeepLiveActivityManager.getInstance(MyService.this).finishKeepLiveActivity();
            }

            @Override
            public void onScreenOff() {
                //鎖屏---啓動一像素的Activity
                KeepLiveActivityManager.getInstance(MyService.this).startKeepLiveActivity();
            }

            @Override
            public void onUserPresent() {

            }
        });

    }
}

複製代碼

#####源碼地址: #####KeepLiveProcess

2.大型App運營商和手機廠商可能有合做關係---白名單

3.雙進程守護

一個進程被殺死,另一個進程又被他啓動,相互監聽啓動。
複製代碼

A<---->B 殺進程是一個一個殺的,本質是和殺進程時間賽跑。 關鍵代碼:

public class LocalService extends Service {

    public static final String ACTION_LOCAL_SERVICE = "com.haocai.app.keepliveprocess.LocalService";
    private static final String TAG = "LocalService";

    private MyServiceConnection conn;
    private MyBinder binder;
    private Intent testIntent;
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        if(binder ==null){
            binder = new MyBinder();
        }
        conn = new MyServiceConnection();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(testIntent!=null){
            stopService(testIntent);
        }

        //unbindService(conn);

    }

    //啓動前臺進程 增長重要性優先級
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LocalService.this.bindService(new Intent(LocalService.this, RemoteService.class), conn, Context.BIND_IMPORTANT);

        PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setTicker("360")
                .setContentIntent(contentIntent)
                .setContentTitle("我是360,我怕誰!")
                .setAutoCancel(true)
                .setContentText("hehehe")
                .setWhen( System.currentTimeMillis());

        //把service設置爲前臺運行,避免手機系統自動殺掉改服務。
        startForeground(startId, builder.build());
        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, "本地服務被幹掉了~~~~~斷開鏈接!");
            Toast.makeText(LocalService.this, "斷開鏈接", Toast.LENGTH_SHORT).show();
            //啓動被幹掉的
            testIntent = new Intent();
            //自定義的Service的action
            testIntent.setAction(RemoteService.ACTION_REMOTE_SERVICE);
            //自定義Service的包名
            testIntent.setPackage(getPackageName());
            Log.i("999", getPackageName() + "");
            startService(testIntent);

            LocalService.this.bindService(new Intent(LocalService.this, RemoteService.class), conn, Context.BIND_IMPORTANT);
        }

    }
    }


複製代碼
public class RemoteService  extends Service {

    private static final String TAG = "RemoteService";
    private MyBinder binder;
    private MyServiceConnection conn;
    public static final String ACTION_REMOTE_SERVICE = "com.haocai.app.keepliveprocess.RemoteService";
    private Intent  testIntent;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if(binder == null){
            binder = new MyBinder();
        }
         conn = new MyServiceConnection();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        if(testIntent!=null){
//            stopService(testIntent);
//        }
        //unbindService(conn);

    }

    //啓動前臺進程 增長重要性優先級
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        RemoteService.this.bindService(new Intent(RemoteService.this, LocalService.class), conn, Context.BIND_IMPORTANT);

        PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setTicker("360")
                .setContentIntent(contentIntent)
                .setContentTitle("我是360,我怕誰!")
                .setAutoCancel(true)
                .setContentText("hehehe")
                .setWhen( System.currentTimeMillis());

        //把service設置爲前臺運行,避免手機系統自動殺掉改服務。
        startForeground(startId, builder.build());
        return START_STICKY;
    }


    class  MyBinder extends  RemoteConnection.Stub{

        @Override
        public String getProcessName() throws RemoteException {
            return "RemoteService";
        }
    }

    class MyServiceConnection implements ServiceConnection{
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG,"RemoteService 創建鏈接成功!");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG,"遠程服務被幹掉了~~~~~斷開鏈接!");
            Toast.makeText(RemoteService.this,"斷開鏈接",Toast.LENGTH_SHORT).show();


            //啓動被幹掉的
            testIntent = new Intent();
            //自定義的Service的action
            testIntent.setAction(LocalService.ACTION_LOCAL_SERVICE);
            //自定義Service的包名
            testIntent.setPackage(getPackageName());
            Log.i("999",getPackageName()+"");
            startService(testIntent);

            RemoteService.this.bindService(new Intent(RemoteService.this, LocalService.class), conn, Context.BIND_IMPORTANT);
        }
        }

    }

複製代碼

#####源碼地址: #####KeepLiveProcess2

4.JobScheduler

把任務加到系統調度隊列中,當到達任務窗口期的時候就會執行,咱們能夠在這個任務裏面啓動咱們的進程。 這樣能夠作到將近殺不死的進程。

@SuppressLint("NewApi")
public class JobHandleService extends JobService{
	public static final String ACTION_JOB_HANDLE_SERVICE = "com.haocai.app.keepliveprocess.JobHandleService";
	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");
//		scheduleJob(getJobInfo());
		boolean isLocalServiceWork = isServiceWork(this, LocalService.ACTION_LOCAL_SERVICE);
		boolean isRemoteServiceWork = 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();
		}
		return true;
	}


	private void startLocalService(){
		Intent  testIntent = new Intent();

		//自定義的Service的action
		testIntent.setAction(LocalService.ACTION_LOCAL_SERVICE);
		//自定義Service的包名
		testIntent.setPackage(getPackageName());
		Log.i("999",getPackageName()+"");
		startService(testIntent);
	}
	private void  startRemoteService(){
		Intent testIntent = new Intent();

		//自定義的Service的action
		testIntent.setAction(RemoteService.ACTION_REMOTE_SERVICE);
		//自定義Service的包名
		testIntent.setPackage(getPackageName());
		Log.i("999", getPackageName() + "");
		startService(testIntent);

	}

	@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;
	}
}


複製代碼
<service
            android:name=".JobHandleService"
            android:permission="android.permission.BIND_JOB_SERVICE">
        </service>
複製代碼

5.監聽QQ,微信,系統應用,友盟,小米推送等等的廣播,而後把本身啓動了。

6.利用帳號同步機制喚醒咱們的進程

AccountManager

7.NDK來解決,Native進程來實現雙進程守護。

特別感謝: 動腦學院Ricky

相關文章
相關標籤/搜索