How do I sendBroadcast(intent) from myDialog and r

2019-06-15 14:33发布

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?

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-15 15:04

It would probably be much easier to register your receiver in code in your activity's onResume method (and unregiser in onPause).

BroadcastReceiver rec = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        //Do stuff
    }
};
IntentFilter filter = new IntentFilter("android.intent.action.RUN");

registerReceiver(rec, filter);
查看更多
The star\"
3楼-- · 2019-06-15 15:22

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);
查看更多
登录 后发表回答