Ok, there is stated id documentation:
You cannot launch a popup dialog in your implementation of onReceive().
Nevertheless, this code is beatufilly working:
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();
}
}
Why is it working? What am I missing in documentation?? Thanks.