显示从状态栏通知开始的权限活动,可以通过以下步骤实现:
- 在AndroidManifest.xml文件中,添加以下权限:<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />private static final int REQUEST_CODE_NOTIFICATION_ACTIVITY = 1000;
private void requestNotificationActivityPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_CODE_NOTIFICATION_ACTIVITY);
}
}
}@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestNotificationActivityPermission();
}@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_NOTIFICATION_ACTIVITY) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
// 权限被拒绝
Toast.makeText(this, "权限被拒绝,无法显示通知", Toast.LENGTH_SHORT).show();
} else {
// 权限被授权
showNotification();
}
}
}
}private void showNotification() {
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
layoutParams.gravity = Gravity.TOP | Gravity.START;
layoutParams.x = 0;
layoutParams.y = 100;
TextView textView = new TextView(this);
textView.setText("这是一个通知");
textView.setTextColor(Color.WHITE);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
textView.setBackgroundColor(Color.BLACK);
textView.setPadding(10, 10, 10, 10);
windowManager.addView(textView, layoutParams);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
windowManager.removeView(textView);
}
}, 3000);
}现在,当用户授权了权限后,就可以在状态栏显示通知了。
- 在需要显示通知的Activity中,添加以下代码:
- 在Activity的onCreate方法中,调用requestNotificationActivityPermission方法:
- 在Activity的onActivityResult方法中,处理权限请求结果:
- 在Activity中,创建一个方法showNotification,用于显示通知: