So, I'm trying to get a handle on BroadcastReceivers and Intent filters. I have a custom Dialog that I create in MyActivity. In the Dialog, I have a Button. When the button gets clicked, I want to send a broadcast that MyActivity's receiver will pick up. Here's what I have right now:
//MyActivity.java
class myActivity extends Activity {
//MyDialog dialog initialized in onCreate
...
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//toast "Broadcast received"
}
}
}
//MyDialog.java
class MyDialog extends Dialog {
//m_context = incoming context from MyActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnCLickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("android.intent.action.RUN");
m_context.sendBroadcast(intent);
}
});
}
}
//AndroidManifest.xml
<activity android:name=".MyActivity" />
<receiver android:name="MyReceiver" android:enabled="true">
<intent-filter >
<action android:name="android.intent.action.RUN"/>
</intent-filter>
</receiver>
When I press button1, the app crashes. Can anyone lead me in the right direction?
getStringExtra("message"); And then you will use message as you need. If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="@android:style/Theme. Dialog" /> in your manifest for ReceiveText and then set the message to a textview in the activity.
There are two ways to make a broadcast receiver known to the system: One is declare it in the manifest file with this element. The other is to create the receiver dynamically in code and register it with the Context. registerReceiver() method.
Android BroadcastReceiver is a dormant component of android that listens to system-wide broadcast events or intents. When any of these events occur it brings the application into action by either creating a status bar notification or performing a task.
Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.
in MyActivity do something like this:
private BroadcastReceiver _refreshReceiver = new MyReceiver();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
IntentFilter filter = new IntentFilter("SOMEACTION");
this.registerReceiver(_refreshReceiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(this._refreshReceiver);
}
and to invoke broadcast
Intent in = new Intent("SOMEACTION");
sendBroadcast(in);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With