基于Android M及以上版本写一个系统级的Windows
2017-09-26 本文已影响0人
xlq
由于Android M在安全机制上有了更进一步的加强,所以写一个系统级别的window就不仅仅只是在Android Manifests里面配置SYSTEM_ALERT_WINDOW权限这么简单,它需要用户手动去打开权限,由此代码会有些许改动。
package com.example.ubuntu.windowmanagerdemo;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
WindowManager mWindowManager;
Button mWindowButton;
WindowManager.LayoutParams layoutParams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mWindowButton = new Button(this);
mWindowButton.setText("Window Button");
layoutParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
0, 0, PixelFormat.TRANSPARENT);
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;//表明是系统级别的window
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
layoutParams.x = 100;
layoutParams.y = 300;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(getApplicationContext())) {
//启动Activity让用户授权
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 100);
}else {
//用户已经授权
mWindowManager.addView(mWindowButton, layoutParams);
}
} else {
//用户版本低于Android M
mWindowManager.addView(mWindowButton, layoutParams);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.canDrawOverlays(this)) {
mWindowManager.addView(mWindowButton, layoutParams);
}
}
}
}
}