Android在onClickListener中使用broadcastreceiver接收

时间:2015-10-23 05:54:05

标签: android broadcastreceiver android-broadcastreceiver

myButton是一个按钮,单击时应该从后台IntentService接收广播。但广播从未收到过。但是,如果我在myButton.setOnClickListener函数之外移动broadcastReceiver,那么我开始从我的后台服务接收广播。

有没有办法让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方法中取出broadcastReceiver。收到了这个作品和广播:

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

1 个答案:

答案 0 :(得分:0)

你忘了registerReceiver吗?

注册接收器时,您可能还需要指定一个IntentFilter。

以下是我项目中的一些示例代码:

private class LocationInfoReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // do something
    }
}

locationInfoReceiver = new LocationInfoReceiver();
// the key you use setAction() method in your Intent Service
IntentFilter locationInfoReceiverFilter = new IntentFilter("your key");
locationInfoReceiverFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(locationInfoReceiver, locationInfoReceiverFilter);