Is it possible to call onReceive method from a dialog?

你。 提交于 2019-12-06 02:10:48

According to your question, the following steps will give you exactly what you want.

1.) In your AndroidManifest.xml replace your receiver

<receiver android:name="com.example.MyReceiver"></receiver>

by the following:

<receiver android:name=".MyReceiver" />

2.) Finally add this in your code for the button listener:

save.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // ...
        getApplicationContext().sendBroadcast(
                new Intent(getApplicationContext(), MyReceiver.class));
        // ...
    }
});

That's it, now run your app. Whenever you click your save button, you will notice that the onReceive() method in your class MyReceiver will get called properly. That means your logcat output will be

I/App: called receiver method

as expected and your Toast message Call Utils1 will also be displayed correctly.

It is possible but you need to make a custom Dialog. Custom like a new Class that extends DialogFragment. There you create a instance of you receiver and register for it like this:

@Override
protected void onResume() {
 super.onResume();
 getActivity.registerReceiver(mReceiver, mIntentFilter);
}

@Override
protected void onPause() {
 if(mReceiver != null) {
   getActivity.unregisterReceiver(mReceiver);
   mReceiver = null;
   }
 super.onPause();
}

Sending a class-based intent to a broadcast receiver doesn't work. Intents with a class in them are for launching activities, not broadcast messages.

To send a message to a broadcast receiver, you need to use an intent with an action string, and register the string with an intent filter in your manifest.

If you've already got the data.You can just use it like this:

MyReceiver receiver = new MyReceiver();
receiver.onReceive(context,intent);

Call onReceive() by your code instead of by system.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!