I want to receive user location in background and do some math on it. then send notification to user. I dont know how to manage the locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener) because of ActivityCompat.requestPermissions(activity: this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); need activity and there is no activity in BroadcastReceiver.
here is my code:
public class AlarmReceiver extends BroadcastReceiver {
private static LocationManager locationManager;
private static LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {
//do some math on loacation
}
};
@Override
public void onReceive(Context context, Intent intent) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// ask for permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
// we have permission!
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
and MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onDestroy() {
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("NotificationText", "some text");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 3, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
super.onDestroy();
}
}