本文介绍了如何从myDialog发送广播(意图)并在myActivity中接收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试获取BroadcastReceivers和Intent过滤器的句柄.我有一个在MyActivity中创建的自定义对话框.在对话框中,我有一个按钮.单击按钮后,我要发送一个广播,MyActivity的接收器将接收该广播.这是我现在所拥有的:

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>

当我按下button1时,应用程序崩溃.谁能引导我朝正确的方向前进?

When I press button1, the app crashes. Can anyone lead me in the right direction?

推荐答案

在MyActivity中执行以下操作:

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);
}

并调用广播

Intent in = new Intent("SOMEACTION");
sendBroadcast(in);

这篇关于如何从myDialog发送广播(意图)并在myActivity中接收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 18:59