myButton 是一个按钮,当单击它时应该从后台 IntentService 接收广播。但从未收到广播。但是,如果我将 broadcastReceiver 移到 myButton.setOnClickListener 函数之外,我就会开始从我的后台服务接收广播。
有没有办法让 broadcastReceiver 在 setOnClickListener 函数中接收广播?
public class MainActivity extends Activity {
private BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myButton = (Button)findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
Toast.makeText(MainActivity.this, "BROADCAST RECEIVED", Toast.LENGTH_SHORT).show();
stopService(msgIntent);
}
};
}
});
public void onResume()
{
super.onResume();
IntentFilter filter = new IntentFilter(SimpleIntentService.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(broadcastReceiver,filter);
}
public void onPause()
{
unregisterReceiver(broadcastReceiver);
super.onPause();
}
}
我不得不从 onClick 方法中取出广播接收器。这有效并收到广播:
public class MainActivity extends Activity {
private BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myButton = (Button)findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//do extra stuff
}
});
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
Toast.makeText(MainActivity.this, "BROADCAST RECEIVED", Toast.LENGTH_SHORT).show();
stopService(msgIntent);
}
};
}
}