My application is in the background and I use a service that sends a broadcast when a certain condition is met:
if(send)
{
Intent intent = new Intent(Tags.MSG_BROADCAST_ID);
intent.putExtra(Tags.MESSAGE, msg);
Log.w(Tags.DEBUG,"Broadcast");
sendBroadcast(intent);
}
}
My broadcast receiver gets the broadcast and it should show an alert dialog. I use this:
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
if (bundle != null && Globals.MainActivity != null)
{
msg = bundle.getString(Tags.MESSAGE);
Globals.MainActivity.ShowMessage(msg);
}
}
When my main activity is in the foreground, the alert is shown correctly. When it is in the background, nothing is visible.
Runnable runnable = new Runnable()
{
public void run()
{
KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km.newKeyguardLock("My_App");
kl.disableKeyguard();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "My_App");
wl.acquire();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
dialog.dismiss();
}
}
);
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.getWindow().setType(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
// show it
alertDialog.show();
wl.release();
}
};
runOnUiThread(runnable);
I tried to use a Dialog themed activity instead of the dialog, but it brings the activity to focus (I only need the dialog). As I need to be shown over locked screen, I added some flag to the dialog, and the following permissions:
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
I tested it on Android 2.3.6.
What should I set to make my dialog visible?