java - 位置监听器没有运行我的 onLocationChanged
问题描述
我在 onLocationChanged 中的 buildLocationEvent(location) 永远不会运行?这有什么特别的原因吗?我看不出任何原因,也许我遗漏了一些明显的东西,请告诉我这里出了什么问题以及我如何对其进行排序,以便我可以开始正确地获取位置数据。
我复制了下面的代码:
public class LService extends Service {
public static final String TAG = "Lervice";
private LocationListener listener;
private LocationManager manager;
private static LocationEvent locationEvent = new LocationEvent();
@RequiresApi(api = Build.VERSION_CODES.O)
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
super.onCreate();
startMyOwnForeground();
listener = new LocationListener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onLocationChanged(Location location) {
buildLocationEvent(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
manager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, listener);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground() {
String NOTIFICATION_CHANNEL_ID = "com.app.myapp";
String channelName = "LService";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.GREEN);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(3, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
if(manager != null){
manager.removeUpdates(listener);
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void buildLocationEvent(Location location){
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
double[] coordinate = {latLng.latitude, latLng.longitude};
locationEvent.setCoordinate(coordinate);
locationEvent.setAltitude(location.getAltitude());
locationEvent.setHorizontalAccuracy(location.getAccuracy());
locationEvent.setVerticalAccuracy(location.getVerticalAccuracyMeters());
locationEvent.setTimestamp(location.getTime());
sendLocationToManager(locationEvent);
}
private void sendLocationToManager(LocationEvent locationEvent){
Intent intent = new Intent("locationCreated");
sendLocalBroadcastEvent(intent, locationEvent);
}
private void sendLocalBroadcastEvent(Intent intent, LocationEvent locationEvent){
intent.putExtra("locationevent", locationEvent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
感谢您对此的帮助。如果您需要任何澄清,请告诉我。
运行时在 Main 中调用权限:
String[] appPermissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
};
private static final int PERMISSIONS_REQUEST_CODE = 1240;
//get permissions for location
Log.d(TAG, "permissions: "+ checkAndRequestPermissions()); //false
if(true) {
//I RUN MY CODE HERE
}
}
private boolean checkAndRequestPermissions() {
List<String> listPermissionsNeeded = new ArrayList<>();
for (String perm : appPermissions) {
if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(perm);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
PERMISSIONS_REQUEST_CODE
);
return false;
}
//All Permissions granted
return true;
}
希望有帮助。
这就是我启动服务的方式:
public void startUpdatingLocation(){
//Start sensor service
Intent locationIntent = new Intent(MyApplication.getAppContext(), LService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MyApplication.getAppContext().startForegroundService(locationIntent);
} else {
MyApplication.getAppContext().startService(locationIntent);
}
}
解决方案
推荐阅读
- azure - 在 Sendgrid 中创建资源时 ResourcePurchaseValidationFailed
- java - 聚合以组合集合尝试
- eclipse - 为什么main方法加载不出来
- vim - Vim 按段落扩展选择
- python - 未来的最小熊猫数据框
- ios - iOS 本机框架作为本机组件包装到反应本机项目中不会执行 segues
- jenkins - Jenkins Kubernetes 插件 - sshagent 到 git clone terraform 模块
- sql - 检查十个字段中的任何两个是否不同(不为 NULL 或等于)
- r - 在多面 ggplot 上注释不同的方程
- c - realloc 是否改变了它的论点