简体   繁体   English

在android中动态注册/取消注册广播接收器

[英]Dynamically register/unregister a broadcast receiver in android

I want to dynamically register and unregister my receiver class with the broadcast: "android.net.wifi.STATE_CHANGE" This works very well if I do this in the manifest. 我想通过广播动态注册和取消注册我的接收器类:“android.net.wifi.STATE_CHANGE”如果我在清单中执行此操作,这非常有效。 But this makes it static. 但这使它变得静止。 I want to do it dynamically in the activity class. 我想在activity类中动态地完成它。 What is its correspondent command in the activity class? 它在活动类中的通讯命令是什么?

This is what my code is... and I am getting a problem because of registering and unregistering(multiple times) my receiver(which is starting a service). 这就是我的代码......而且由于注册和取消注册(多次)我的接收器(它正在启动服务),我遇到了问题。

public class startScreen extends Activity {
    /** Called when the activity is first created. */

    private BroadcastReceiver receiver = new BroadcastReceiver() {    

        @Override
        public void onReceive(Context context, Intent intent) {
            Intent serviceIntent = new Intent();
            serviceIntent.setAction("com.example.MyService");
            context.startService(serviceIntent);    
        }    
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.initial);

        final IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.wifi.STATE_CHANGE");   

        Button button = (Button) findViewById(R.id.button1);
        final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);

        try {
                ...some code...
            if (bool == true) {
                toggleButton.setChecked(true);
                this.registerReceiver(receiver, filter);
            } else
                toggleButton.setChecked(false);
        } catch (Exception e) {
            Log.e("Error", "Database", e);
        } finally {
                ...
        }

        toggleButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if ((toggleButton.isChecked())) {
                    getBaseContext().registerReceiver(receiver, filter);

                } else {
                    if (receiver != null) {
                        getBaseContext().unregisterReceiver(receiver);
                        receiver = null;
                    }

                }
            }
        });
    }    

    @Override
    protected void onResume() {
        super.onResume();
        if (bool == true) {
            if (receiver == null)
                this.registerReceiver(receiver, filter);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (receiver != null) {
            this.unregisterReceiver(receiver);
            receiver = null;
        }
    }
}

The LocalBroadcastManager class is used to register for and send broadcasts of Intents to local objects within your process. LocalBroadcastManager类用于注册并向流程中的本地对象发送Intents广播。 This is faster and more secure as your events don't leave your application. 由于您的活动不会离开您的应用程序,因此速度更快,更安全。

The following example shows an activity which registers for a customer event called my-event. 以下示例显示了一个为名为my-event的客户事件注册的活动。

@Override
public void onResume() {
super.onResume();

   // Register mMessageReceiver to receive messages.
   LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
     new IntentFilter("my-event"));
}

// handler for received Intents for the "my-event" event 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
   // Extract data included in the Intent
   String message = intent.getStringExtra("message");
   Log.d("receiver", "Got message: " + message);
 }
};

@Override
protected void onPause() {
   // Unregister since the activity is not visible
   LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
   super.onPause();
} 
// This method is assigned to button in the layout
// via the onClick property
public void onClick(View view) {
   sendMessage();
}

// Send an Intent with an action named "my-event". 
private void sendMessage() {
  Intent intent = new Intent("my-event");
  // add data
  intent.putExtra("message", "data");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
} 

use the below methods to register/unregister your receiver: 使用以下方法注册/取消注册您的接收者:

registerReceiver(BroadcastReceiver receiver, new IntentFilter("android.net.wifi.STATE_CHANGE"));
unregisterReceiver(BroadcastReceiver receiver);

For reference have a look at this 作为参考看看这个

Don't add dynamic broadcast receiver in onReceive on broadcast file. 不要在广播文件的onReceive中添加动态广播接收器。 Add it on first activity or main activity of your application. 将其添加到应用程序的第一个活动或主要活动。 If you needed it only when your application is open. 如果您只在应用程序打开时才需要它。 But if you need it always received response just added it on manifest file 但如果你需要它总是收到响应只是将它添加到清单文件

Register dynamic broadcast receiver on main activity 在主要活动上注册动态广播接收器

MyReceiver reciver;

@Override
protected void onResume() {
    super.onResume();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
    intentFilter.addAction("android.net.wifi.STATE_CHANGE");
    reciver = new MyReceiver();
    registerReceiver(reciver, intentFilter);
}

Unregister that broadcast receiver on activity stop or closed 在活动停止或关闭时取消注册广播接收器

@Override
protected void onStop() {
    super.onStop();
    unregisterReceiver(reciver);
}

Perhaps I'm a bit too late, but the problem lies on the fact that you are setting the receiver = null in your onPause method, and then never setting it again. 也许我有点太晚了,但问题在于你在onPause方法中设置receiver = null ,然后再也没有设置它。 You are also trying to register it in your onResume method but only if it is null , which makes no sense too. 您也尝试在onResume方法中注册它,但仅当它为null ,这也没有意义。

You should change the logic where you set/test the null value of the receiver, to instead just use a boolean variable to keep track of the receiver status (if it's registered or not). 您应该更改设置/测试接收器null值的逻辑,而只是使用boolean变量来跟踪接收器状态(如果已注册或未注册)。

public void registerBroadcastReceiver(View view) {

    this.registerReceiver(broadCastReceiver, new IntentFilter(
        "android.intent.action.TIME_TICK"));
}


public void unregisterBroadcastReceiver(View view) {

    this.unregisterReceiver(broadCastReceiver);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM