在设备中启用/禁用GPS时,在应用程序中设置文本



我使用以下代码根据用户打开/关闭网络和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的布尔值更改,但不是最初注册的。只有在应用程序启动后手动更改"位置"设置后,文本才会更改,这与应用程序一启动就更改文本的网络检查不同。

我认为这个问题已经在这里得到了回答

但我认为,如果使用LocationManagerLocationListener是个好主意,我的意思是,LocationListener有那些被高估的方法:

@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}

我让你考虑

最新更新