Я пытаюсь обновить местоположение на заднем плане и на переднем плане, поэтому сначала я определил две кнопки, такие как кнопка обновления и удаления. поэтому, когда я нажимаю обновить, он обновляет местоположение в фоновом режиме и удаляет для удаления слушателя местоположения.
, но через некоторое время я хочу удалить эти кнопки, и когда я открываю это действие, он должен обновлять местоположение автоматически без нажатие кнопки.
, поэтому я решил удалить код с кнопки обновления (Начать обновление местоположения) и скопировать и вставить в метод oncreate
. так что он будет обновляться при каждом открытии активности без нажатия на кнопку. теперь я получаю исключение нулевого указателя, пожалуйста, кто-то помогает мне
Я прилагаю свой полный код.
public class UserLocation extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
DatabaseReference publiclocation;
private static final int MY_PERMISSION_REQUEST_CODE = 7171;
private static final int PLAY_SERVICES_RES_REQUEST = 7172;
private LocationRequest mlocationRequest;
String uid;
SharedPreferences settings;
Button requestLocation, removeLocation;
MyBackgroundService mService = null;
boolean mBound = false;
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
MyBackgroundService.LocalBinder binder = (MyBackgroundService.LocalBinder) iBinder;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
mBound = false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_location);
publiclocation = FirebaseDatabase.getInstance().getReference(Common.PUBLIC_LOCATION);
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
settings = getSharedPreferences(PREFS_NAME, 0);
String user_uid = settings.getString("uid", "Null");
uid = firebaseUser.getUid();
//Run time permission
Dexter.withActivity(this)
.withPermissions(Arrays.asList(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
))
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
requestLocation = (Button) findViewById(R.id.request_location_updates_button);
removeLocation = (Button) findViewById(R.id.remove_location_updates_button);
//Update location when i click on button
requestLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mService.requestLocationUpdates();
}
});
//Remove location when i click remove button
removeLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mService.removeLocationUpdates();
}
});
setButtonState(Common.requestingLocationUpdates(UserLocation.this));
bindService(new Intent(UserLocation.this,
MyBackgroundService.class),
mServiceConnection,
Context.BIND_AUTO_CREATE
);
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
})
.check();
}
@Override
protected void onStart() {
super.onStart();
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
if (mBound) {
unbindService(mServiceConnection);
mBound = false;
}
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this);
EventBus.getDefault().unregister(this);
super.onStop();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
if (s.equals(Common.KEY_REQUESTING_LOCATION_UPDATES)) {
setButtonState(sharedPreferences.getBoolean(Common.KEY_REQUESTING_LOCATION_UPDATES, false));
}
}
private void setButtonState(boolean isRequestEnable) {
if (isRequestEnable) {
requestLocation.setEnabled(false);
removeLocation.setEnabled(true);
} else {
requestLocation.setEnabled(true);
removeLocation.setEnabled(false);
}
}
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onListenLocation(SendLocationToActivity event) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
settings = getSharedPreferences(PREFS_NAME, 0);
String user_uid = settings.getString("uid", "Null");
uid = firebaseUser.getUid();
if (event != null) {
String data = new StringBuilder()
.append(event.getLocation().getLatitude())
.append("/")
.append(event.getLocation().getLongitude())
.toString();
Toast.makeText(mService, data, Toast.LENGTH_SHORT).show();
// Location location = event.getLastLocation();
Locations location = new Locations();
location.setLat(event.getLocation().getLatitude());
location.setLon(event.getLocation().getLongitude());
if (Common.currentUser != null) {
publiclocation.child(firebaseUser.getUid()).setValue(location);
} else {
publiclocation.child(user_uid).setValue(location);
}
}
}
}
, поэтому ниже MyLocationService. java
public void requestLocationUpdates() {
Toast.makeText(getApplicationContext(),"Came",Toast.LENGTH_SHORT).show();
Common.setRequestingLocationUpdates(this, true);
startService(new Intent(getApplicationContext(), MyBackgroundService.class));
try {
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
} catch (SecurityException e) {
Log.e("FunDrive", "Lost location permissions.could not request it" + e);
}
}
Общее java
public static final String KEY_REQUESTING_LOCATION_UPDATES = "LocationUpdatedEnable";
SharedPreferences settings;
public static final int TIME_DISPLAY_SLOT_TOTAL = 20;
//Current User
public static User currentUser;
public static String PUBLIC_LOCATION="PublicLocation";
public static boolean isTimeSelected = false;
public static void setRequestingLocationUpdates(Context context,boolean value) {
PreferenceManager.
getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_REQUESTING_LOCATION_UPDATES,value)
.apply();
}
public static boolean requestingLocationUpdates(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_REQUESTING_LOCATION_UPDATES,false);
}
public static CharSequence getLocationTitle(com.example.fundrive.MyBackgroundService myBackgroundService) {
return String.format("Location Updated :%1$s", DateFormat.getDateInstance().format(new Date()));
}
Ниже приведено то, что я попробовал в oncreate
метод
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mService.requestLocationUpdates();
}