问题描述
我想在后台接收用户位置并对其进行一些数学计算。然后向用户发送通知。我不知道如何管理locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,locationListener)
,因为ActivityCompat.requestPermissions(activity: this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
需要活动,而broadcastReceiver
中没有活动。
这是我的代码:
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,1);
} else {
// we have permission!
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,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,locationListener);
}
}
}
和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,pendingIntent);
super.onDestroy();
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)