我知道回复有点晚了,但由于没有可接受的答案,您可以考虑一下。
您不必创建自定义视图并将其添加到窗口。如果您只想显示一个常规对话框,您可以执行以下操作。
创建一个 Service 类并通过将其写入 AndroidManifest.xml 让应用程序知道该服务。类似的东西;
<service android:name="your.package.name.PopupService"/>
然后实现服务;
public class PopupService extends Service {
private Intent myIntent;
MaterialDialog dialog;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.myIntent = intent;
showDialog(myIntent.getStringExtra("msg")); // you can send extra information to service via intent
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
private void showDialog(String message)
{
if (dialog != null) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
dialog = new MaterialDialog.Builder(getApplicationContext())
.content(message)
.positiveText("OK")
.negativeText("cancel")
.positiveColor(getResources().getColor(R.color.colorAccent))
.negativeColor(getResources().getColor(R.color.colorPrimary))
.cancelable(true)
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
stopSelf();
}
@Override
public void onNegative(MaterialDialog dialog) {
stopSelf();
}
})
.dismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
stopSelf();
}
})
.build();
dialog.getWindow().setType(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
dialog.show();
}
@Override
public void onDestroy() {
if (dialog != null) {
dialog.dismiss();
}
super.onDestroy();
}
}
当你想显示对话框时,只需调用服务,比如;
Intent intent = new Intent(MainActivity.this, PopupService.class);
intent.putExtra("msg","Test Message");
startService(intent);
还有一点,就是把这个权限加到AndroidManifest.xml中
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
希望这会有所帮助:)