我在 list 中设置了一个广播来监视连接 Activity :
<application
...
<receiver
android:name="com.blah.appname.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
...
</application>
NetworkChangeReceiver 内部是 onHandle() 方法。这主要只是为了显示 Toast 消息,并进行一些日志记录,并在整个应用程序中工作。
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
// do stuff
}
}
但是,我还需要根据连接丢失在个人 Activity 中执行特殊操作。
如何从 Activity 中访问现有广播接收器的 onReceive() 方法?我不完全理解接收器如何从 list 绑定(bind)到应用程序的内部结构。
最佳答案
您在应用程序中创建一个广播接收器以在应用程序中访问它。 list 中的广播接收器必须在 10 秒内返回,因此广播接收器的 list 版本通常会以 Intent 启动某些内容,然后返回。
以下是向您的应用添加广播接收器的代码示例。
BroadcastReciver yourReceiver;
public void onStart() {
super.onStart();
setupGPS();
}
private void setupGPS() {
if (yourReceiver == null) {
// INTENT FILTER FOR GPS MONITORING
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION_GPS);
yourReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String s = intent.getAction();
if (s != null) {
if (s.equals(ACTION_GPS)) {
gpsCheck();
}
}
}
}
};
getActivity().registerReceiver(yourReceiver, theFilter);
}
gpsCheck();
}
private void gpsCheck() {
if (view != null) {
LinearLayout llTrackerEnableGPS = (LinearLayout) view
.findViewById(R.id.llTrackerEnableGPS);
if (llTrackerEnableGPS != null) {
LocationManager locationManager = (LocationManager) fragmentActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean isGPSAvailable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
llTrackerEnableGPS.setVisibility(isGPSAvailable ? View.GONE
: View.VISIBLE);
}
}
}
@Override
public void onPause() {
super.onPause();
if (yourReceiver != null) {
final FragmentActivity a = getActivity();
if (a != null) {
a.unregisterReceiver(yourReceiver);
}
}
yourReceiver = null;
}
关于java - 从 Activity 中访问应用程序广播接收器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26874152/