不多说,直接上代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
permissions = new RxPermissions(this);
requestPermiss();
monitorConn = new MonitorConn();
if (Build.VERSION.SDK_INT >= 23) {
if (Settings.canDrawOverlays(MainActivity.this)) {
Intent intent = new Intent(MainActivity.this, MonitorService.class);
Toast.makeText(MainActivity.this,"已开启Toucher",Toast.LENGTH_SHORT).show();
startService(intent);
bindService(new Intent(this, MonitorService.class), monitorConn, BIND_AUTO_CREATE);
// finish();
} else {
//若没有权限,提示获取.
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,Uri.parse("package:" + getPackageName()));
Toast.makeText(MainActivity.this,"需要取得权限以使用悬浮窗",Toast.LENGTH_SHORT).show();
startActivityForResult(intent,BACK_CODE);
}
} else {
//SDK在23以下,不用管.
Intent intent = new Intent(MainActivity.this, MonitorService.class);
startService(intent);
bindService(new Intent(this, MonitorService.class), monitorConn, BIND_AUTO_CREATE);
finish();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BACK_CODE) {
if (Build.VERSION.SDK_INT >= 23) {
if (!Settings.canDrawOverlays(this)) {
// SYSTEM_ALERT_WINDOW permission not granted...
Toast.makeText(MainActivity.this,"not granted",Toast.LENGTH_SHORT);
}else {
Intent intent = new Intent(MainActivity.this, MonitorService.class);
startService(intent);
bindService(new Intent(this, MonitorService.class), monitorConn, BIND_AUTO_CREATE);
}
}
}
}