Android中使用廣播接收者來彈出對話方塊的坑
阿新 • • 發佈:2019-01-01
琢磨了老半天,試了一下網上說的一種方法,我發現不行,這種方法是這樣的:
1.首先註冊靜態廣播
2.在清單中新增許可權
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
3.然後在show()之前設定Dialog型別為TYPE_SYSTEM_ALERT
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
然後發現還是不行。這就鬱悶啦!網上有人說用動態註冊方式可以實現在廣播接收者中彈出對話方塊,於是便試了一下,果然可以
首先開始註冊廣播,並給廣播訊息
private BroadcastReceiver broadcastReceiver;
broadcastReceiver=new tipsBroadReciver(); IntentFilter intentFilter=new IntentFilter(); intentFilter.addAction(ACTION); context.registerReceiver(broadcastReceiver,intentFilter); Intent intent=new Intent(); intent.setAction(ACTION); intent.putExtra("state","1"); context.sendBroadcast(intent);
在廣播接收者中開啟對話方塊
String state=intent.getExtras().getString("state"); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); dialogBuilder.setTitle("提示"); if(state.equals("1")){ text="沒有查詢到該好友"; } dialogBuilder.setMessage(text); dialogBuilder.setCancelable(false); dialogBuilder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { context.unregisterReceiver(tipsBroadReciver.this); } }); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.show();