Android Overlay
Screen Overlay is an advanced feature introduced in Android Marshmallow version that enables any app to appear on the top of other applications. Allowing permissions to apps to draw or run over other apps. These features enable us to run some applications such as Mini Mirror or Speedometer.
AndroidManifest.xml
<!-- Overlay -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.TYPE_APPLICATION_OVERLAY"/>
<!-- Overlay Android 9 (API Level 28) - Allows a regular application to use Service.startForeground. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
MainActivity.java
Activity mActivity = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
startOverlayWithPermission();
}
public void startOverlayWithPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_SYSTEM_ALERT_WINDOW);
} else {
startMyService();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SYSTEM_ALERT_WINDOW) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(this)) {
// You have permission
showToast(getResources().getString(R.string.msg_overlay_authorized));
startMyService();
}
}
}
/**
* Start my Service
*/
private void startMyService() {
Intent svc = new Intent(mActivity, MyOverlayViewService.class);
if(!stopService(svc)) {
startService(svc);
}
finish(); // stop current program if you need
}
/**
* Shows a {@link Toast} on the UI thread.
*
* @param text The message to show
*/
private void showToast(final String text) {
final Activity activity = mActivity;
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
}
});
}
}
Leave a comment