#使您的 BroadcastReceiver 独立于 Activity
创建一个BroadcastReceiver
内部类Activity
以便它可以从其onReceive()
方法访问 UI 元素只是没有意义。如果你这样做,你就不能在BroadcastReceiver
任何其他活动中重复使用。你最终会一次又一次地编写几乎相同的代码。
一个更好的方法是,做一个 CallbackBroadcastReceiver
并让你的 Activity 订阅这个 Callback。
我怎么做?
1)创建回调接口
public interface ReceiverCallback{
public void doSomething(Object object);
}
2) 在 BroadcastReceiver 中提供您的回调
public class MyBroadcastReceiver extends BroadcastReceiver {
private ReceiverCallback callback;
public MyBroadcastReceiver(ReceiverCallback callback){
this.callback = callback; //<--Initialize this
}
@Override
public void onReceive(Context context, Intent intent) {
// Your listening logic goes here (New WIFI Scan data available,
Headphone plugged in etc)
// Send any data or No data(null)
callback.doSomething(null); //<--Send callback event
}
}
3) 订阅您的活动以获取回调事件:
public YourActivity extends AppCompatActivity implements ReceiverCallback{
// Your Activity code
public void updateUI() { //<-- You want this to get Triggered
// Update UI code
}
@Override
public void doSomething(Object object){
updateUI(); //<-- Callback does that
}
}
##Relevant Link:在此处阅读更详细的讨论