Android檢測手機鎖屏開屏事件

現在手機用戶鎖屏後應用很快會被手機管家殺掉進程,爲了保證項目中的service一直存活,所以在用戶進行鎖屏時需要創建一個透明的Activity保證程序一直運行不被手機管家回收掉

 

1、自定義廣播接收者接收手機開關機這個廣播事件

package com.liveon;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ScreenReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {    //屏幕關閉
            Log.i("song","鎖屏");

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {   //屏幕打開
            Log.i("song","開屏");
        }

    }
}

2、在需要的MainActivity中動態註冊廣播

 private void registerService() {
        ScreenReceiver screenBroadcastReceiver = new ScreenReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        getApplicationContext().registerReceiver(screenBroadcastReceiver, filter);
    }

3、運行項目,在監測到用戶鎖屏時啓動一個1像素的透明的Activity就可以,用戶解鎖時,把這個透明的activity給finish就可以了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章