从广播接收器获取变量

时间:2014-10-27 18:19:03

标签: android broadcastreceiver

我想从main_activity访问Broadcast Receiver中的变量boolean is_connected;。我该如何实现这一目标?

public class MyStartServiceReceiver extends BroadcastReceiver {
boolean is_connected;
MediaPlayer media;

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
        Toast.makeText(context, "1", Toast.LENGTH_LONG).show();
    } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
        media=MediaPlayer.create(context,R.raw.battery);
        media.start();
        Toast.makeText(context, "2", Toast.LENGTH_LONG).show();
        is_connected=false;


    }
}

}

2 个答案:

答案 0 :(得分:1)

您有两种选择。一,您可以将MyServiceStartReceiver放在MyActivity中,并将该变量创建为MainActivity中的类变量。 (请参阅我如何实现将在下面接收您的自定义意图广播的接收器。)

或者你可以将你的MyServiceStartReceiver分开,允许你在你的应用程序中使用它,并在完成它的onReceive函数时发送一个广播,并需要发送它的布尔结果。

<强> STEPS

在MyServiceStartReceiver类中创建变量

public static final String CONNECTED_KEY = "connected";

然后在onReceive()结束时准备让你的Activity知道布尔是什么

Intent broadcast = new Intent();
broadcast.setAction(MainActivity.CONNECTION_BROADCAST_ACTION);
broadcast.putExtra(CONNECTED_KEY, is_connected);
sendBroadcast(broadcast);

在MainActivity中,您可以创建自定义广播接收器。接收器可以是这样的

public class MainActivity extends Activity{
    public static final String CONNECTION_BROADCAST_ACTION = "my.package.name.CONNECTION_BROADCAST";
    protected boolean isConnected = false;
    private ConnectionStatusReceiver statusReceiver;

    // Your MainActivity stuff you have now and add

    @Override
    public void onResume(){
        super.onResume(); 
        if(statusReceiver == null)
            statusReceiver = new ConnectionStatusReceiver();
        registerReceiver(statusReceiver, new IntentFilter(CONNECTION_BROADCAST_ACTION));
    }

    @Override
    public void onPause(){
        super.onPause();
        unregisterReceiver(statusReceiver);
    } 

    public class ConnectionStatusReceiver extends BroadcastReceiver{

        // override the onReceive method and in it
        isConnected = intent.getBooleanExtra(BroadcastingClass.CONNECTED_KEY, false);
        // do what you want with it
    }
}

Haven未经过测试,但如果您有任何问题请告诉我。

答案 1 :(得分:0)

根据我的理解,您只想对(在您的活动中)对电源状态的更改做出反应。我的建议是在您的活动中声明BroadcastReceiver的子类作为内部类:

public class MyActivity extends Activity {
  private MyReceiver mReceiver = new MyReceiver();
  private class MyReceiver extends BroadcastReceiver {
    public void onReceive (Context context, Intent intent)     {
      String action = intent.getAction();
      if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
        // do stuff
      } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
        // do other stuff
      }
    }
  }
}

另外,请记住分别在onResumeonPause注册和删除接收者。

由于Intent.ACTION_BATTERY_CHANGED粘性广播,您将在注册接收者时收到(通过注册调用的返回值)最近的意图。如果您想根据此值初始化您的活动(这将在您的onResume实施中),这将非常有用。

另外,请注意,您不应该使用当前的策略(即使用清单中注册的独立接收器)进行此类广播。请参阅广播操作here的文档。