【发布时间】:2014-02-16 07:54:50
【问题描述】:
我的应用程序在后台,我使用了一个在满足特定条件时发送广播的服务:
if(send)
{
Intent intent = new Intent(Tags.MSG_BROADCAST_ID);
intent.putExtra(Tags.MESSAGE, msg);
Log.w(Tags.DEBUG,"Broadcast");
sendBroadcast(intent);
}
}
我的广播接收器收到广播,它应该显示一个警报对话框。我用这个:
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);
}
}
当我的主要活动在前台时,警报会正确显示。当它在后台时,什么都看不见。
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);
我尝试使用以对话框为主题的活动而不是对话框,但它使活动成为焦点(我只需要对话框)。由于我需要在锁定屏幕上显示,我在对话框中添加了一些标志,以及以下权限:
<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"/>
我在 Android 2.3.6 上测试过。
我应该设置什么让我的对话框可见?
【问题讨论】:
-
我不认为您可以从后台应用程序显示对话框,因为它无法访问主线程,因此不会影响 UI。有一些小部件允许在 iOS 等锁定屏幕上显示背景通知。您应该使用 google 并查看这些内容。