1 不可见的前台服务
方案的实施步骤可以参考https://blog.csdn.net/weixin_40876113/article/details/80830795
以下是代码实践:
public int onStartCommand(Intent intent, int flags, int startId) {
if(Build.VERSION.SDK_INT < 18)
{
startForeground(1,new Notification());
}else
{
startForeground(123,new Notification());
startForeground(123,new Notification());
stopForeground(true);
}
return super.onStartCommand(intent, flags, startId);
}
2 不可见的Activity
方案的实施步骤可以参考https://blog.csdn.net/weixin_40876113/article/details/80830795
以下是代码实践:
注册一个监控屏幕亮起,关闭,解锁的广播接受者
public class OnePixelReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("hh","收到广播" + intent.getAction());
// TODO: This method is called when the BroadcastReceiver is receiving
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
Intent it = new Intent(context, OnePiexlActivity.class);
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(it);
}else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
context.sendBroadcast(new Intent("finish"));
Intent main = new Intent(Intent.ACTION_MAIN);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
main.addCategory(Intent.CATEGORY_HOME);
context.startActivity(main);
}
}
}
注意这里的广播接受者只能通过代码注册
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(new OnePixelReceiver(),filter);
一个像素点的Activity
public class OnePiexlActivity extends Activity {
private BroadcastReceiver endReceiver;
@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);
//结束该页面的广播
endReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
registerReceiver(endReceiver, new IntentFilter("finish"));
//检查屏幕状态
checkScreen();
Log.i("hh","onePiexlActivity created");
}
@Override
protected void onResume() {
super.onResume();
checkScreen();
}
/**
* 检查屏幕状态 isScreenOn为true 屏幕“亮”结束该Activity
*/
private void checkScreen() {
PowerManager pm = (PowerManager) OnePiexlActivity.this.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
if (isScreenOn) {
finish();
}
}
}