0

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

1 回答 1

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);
于 2015-10-23T06:25:15.983 回答