You need to create a service
to keep the system overlay( alert) to show even when your application closed.
Create a simple service , I will call as FloatingService
, which will show the overlay(alert) when onStartCommand
is called . Return START_STICKY
to keep the service run in background.
public class FloatingService extends Service {
private WindowManager windowManager;
private View floatingView;
WindowManager.LayoutParams params;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flag, int startId){
// show the alert her
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
// use your custom view here
floatingView = View.inflate(getBaseContext(),R.layout.floating_layout,null); //floatingView.setOnTouchListener(mOnTouchListener);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER | Gravity.CENTER;
// add the view to window manger
windowManager.addView(floatingView, params);
return START_STICKY;
}
}
Add an listener to the view so that you can close the overlay(alert) when required
floatingView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
windowManager.removeView(floatingView);
floatingView = null;
}
});
Finally , register the service in manifest
<service android:name="com.example.app.services.FloatingService" />
And System Alert
permission
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>