保活(四)-1px Acticity

1.原理

当屏幕熄灭的时候呢,锁屏状态,调起一个一像素的Activity,为的还是能够提高进程的优先级,在上一篇文章中,有详细的进程优先级的情况

2.Activity



public class OnePxActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        WindowManager.LayoutParams params = window.getAttributes();
        params.x = 0;
        params.y = 0;
        params.height = 1;
        params.width = 1;
        window.setAttributes(params);
        Log.i("stf", "--onCreate--->OnePxActivity");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i("stf", "--onResume--->OnePxActivity");
        checkScreen();
    }

    
    /**
     * @author  stf
     * @time    2018-06-13 14:16
     * @remark  检查屏幕状态  isScreenOn为true  屏幕“亮”
     *
     */
    private void checkScreen() {
        PowerManager pm = (PowerManager) OnePxActivity.this.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();
        Log.i("stf", "-屏幕状态-isScreenOn--->" + isScreenOn);
        if (isScreenOn) {
         Log.i("stf", "--关闭该Act--->OnePxActivity");
           finish();
        }
    }
  }

3.广播

// 屏幕状态检测广播
public class OnePixelReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("stf", "--OnePixelReceiver-->" + intent.getAction());
        //屏幕关闭启动1像素Activity
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF) || intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
            Log.i("stf", "--OnePixelReceiver-->启动OnePxActivity");
             try {
                Intent it = new Intent(context, OnePxActivity.class);
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(it);
            } catch (Exception e) {
                e.fillInStackTrace();
            }
        }
    }
}

4.清单文件

     

5.透明主题



6.注册广播

分为静态注册和动态注册:
静态注册时 android.intent.action.SCREEN_OFF 不会被触发
动态注册 则没有问题,经实测发现,当App进度后台时收到广播后无法跳转到1PXAct。
这里还是采取静态注册。

首先需要在启动广播的位置注册一个监听手机屏幕状态的广播监听(比如MainActivity)

        
            
                
                
            
        

7.运行结果

关闭屏幕 再点亮屏幕
--OnePixelReceiver-->android.intent.action.USER_PRESENT
--OnePixelReceiver-->启动OnePxActivity
--onCreate--->OnePxActivity
--onResume--->OnePxActivity
-屏幕状态-isScreenOn--->true
--关闭该Act--->OnePxActivity

参考资料

1像素 Activity

你可能感兴趣的:(保活(四)-1px Acticity)