所以,我正试图处理BroadcastReceivers和Intent过滤器。我有一个我在MyActivity中创建的自定义Dialog。在对话框中,我有一个按钮。单击按钮后,我想发送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>
当我按下button1时,应用程序崩溃了。任何人都可以带领我朝着正确的方向前进吗?
答案 0 :(得分:16)
执行以下操作:
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);
答案 1 :(得分:0)
在您的活动的onResume方法中注册接收器可能要容易得多(并且在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);