0
[OK]を起動している理由のAndroid Broadcastreceiver、そこに記載されているID documentationは:
ポップアップが
あなたは の実装onReceive()でポップアップダイアログを起動することはできません。
それにもかかわらず、このコードはbeatufilly働いている:なぜそれが働いている
public class MainActivity extends AppCompatActivity {
final String ACTION = "myActionForBroadcast";
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("MyTag", "onReceive: context" + context.getPackageCodePath());
showDialog();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION);
registerReceiver(broadcastReceiver, filter);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("MyTag", "Handler run: before send broadcast");
sendBroadcast(new Intent(ACTION));
}
}, 5_000);
}
private void showDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Title");
builder.setMessage("Message");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Dialog: onClick()", Toast.LENGTH_SHORT).show();
}
});
Log.d("MyTag", "showDialog: before showing dialog");
builder.show();
Log.d("MyTag", "showDialog: before showing toast");
Toast.makeText(MainActivity.this, "showDialog: showing toast", Toast.LENGTH_SHORT).show();
}
}
?私はドキュメンテーションで何が欠けていますか? ありがとうございました。
ええ、それはあまりうまく書かれていません。彼らが言っていることは、 'onReceive()'に渡された 'Context'を使って' Dialog'を作成して表示できないということです。 'Dialog'は' Activity''Context'を必要とします。 'Context'は' onReceive() 'に渡されます。あなたのケースでは、 'BroadcastReceiver'は' MainActivity'の内部クラスであり、 'MainActivity'の' Context'を使って 'Dialog'を作成しています。 –
ああ、大丈夫です。私は来るコンテキストがBroadcastRestrictedContextなのを見ました。しかしトーストはこの文脈で見ることができますよね? –
はい、その 'Context'で' Toast'を表示することができます。 –