gpt4 book ai didi

android - 如何从 myDialog 发送广播( Intent )并在 myActivity 中接收?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:59:04 25 4
gpt4 key购买 nike

因此,我正在尝试了解 BroadcastReceivers 和 Intent 过滤器。我有一个在 MyActivity 中创建的自定义对话框。在对话框中,我有一个按钮。当按钮被点击时,我想发送一个 MyActivity 的接收器将接收到的广播。这是我现在拥有的:

//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>

当我按下按钮 1 时,应用程序崩溃了。谁能引导我朝着正确的方向前进?

最佳答案

在 MyActivity 中做这样的事情:

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

关于android - 如何从 myDialog 发送广播( Intent )并在 myActivity 中接收?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8022999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com