问题描述
我使用以下代码根据用户打开/关闭网络和 GPS 的时间更改两个文本视图。我能够让网络文本视图工作,但不能让位置文本视图工作。我想我使用了错误的过滤器,但我不知道该使用哪个过滤器。有什么建议/答案吗?
public class MainActivity extends AppCompatActivity {
TextView networkTextView;
TextView locationTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
networkTextView = findViewById(R.id.networkTextView);
locationTextView = findViewById(R.id.locationTextView);
IntentFilter filter1 = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver1,filter1);
IntentFilter filter2 = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
registerReceiver(broadcastReceiver2,filter2);
}
broadcastReceiver broadcastReceiver1 = new broadcastReceiver() {
@Override
public void onReceive(Context context,Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noNetworkConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);
if (noNetworkConnectivity) {
networkTextView.setText("disconnected");
} else {
networkTextView.setText("Connected");
}
}
}
};
broadcastReceiver broadcastReceiver2 = new broadcastReceiver() {
@Override
public void onReceive(Context context,Intent intent) {
if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {
boolean noLocationConnectivity = intent.getBooleanExtra(LocationManager.PROVIDERS_CHANGED_ACTION,false);
if (noLocationConnectivity) {
locationTextView.setText("disconnected");
} else {
locationTextView.setText("Connected");
}
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver1);
unregisterReceiver(broadcastReceiver2);
}
}
更新:
在我替换的位置的广播接收器中
boolean noLocationConnectivity = intent.getBooleanExtra(LocationManager.PROVIDERS_CHANGED_ACTION,false);
与
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean locationConnectivity = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
但这没有用。可能需要向用户请求位置数据权限?
更新 2:
意识到它正在注册 LocationManager.GPS_provider 的布尔值更改,但不是最初。只有在应用启动后手动更改位置设置后,文本才会更改,这与网络检查不同,应用一启动就更改文本。
~已解决:
不得不调用以下代码两次。一旦在接收器外部,然后在接收器内部。仍然不确定为什么它最初无法识别位置服务是打开还是关闭。
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean locationConnectivity = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (locationConnectivity) {
locationTextView.setText("Connected");
} else {
locationTextView.setText("disconnected");
}
解决方法
我认为这个问题已经有人回答了here
但我在考虑使用 LocationManager
和 LocationListener
是否是一个好主意,我的意思是,LocationListener
有那些被覆盖的方法:
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
我把它留给你考虑