java– 通过位置服务警报打开后等待,直到位置打开

java– 通过位置服务警报打开后等待,直到位置打开,第1张

概述我有一个问题,如果我的手机的位置服务被关闭,我想设置一个警报打开位置服务设置并在那里打开它.这工作正常,但问题是我打开后导航回我的应用程序.看起来当我点击后,我的活动的onResume被调用,但是在onResume完成之前,该位置仍未正确设置.这是我的代码:Comments.java:@Overridepub

我有一个问题,如果我的手机的位置服务被关闭,我想设置一个警报打开位置服务设置并在那里打开它.这工作正常,但问题是我打开后导航回我的应用程序.看起来当我点击后,我的活动的onResume被调用,但是在onResume完成之前,该位置仍未正确设置.这是我的代码:

Comments.java:

@OverrIDepublic voID onResume() {    super.onResume();    locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);    Location location = LocationService.getLastLocation();    if(location == null) {        if(getLastKNownLocation() == null) {            if(checkLocationEnabled()); {                location = getLastKNownLocation();            }        }    }    if(location != null) {        progressOverlay = fragmentVIEw.findVIEwByID(R.ID.progress_overlay);        AndroIDUtils.animateVIEw(progressOverlay, VIEw.VISIBLE, 0.9f, 200);        //Within this function call, the progress overlay is set to VIEw.GONE.        databasequery.getPublicposts(location, progressOverlay, fragmentVIEw, getContext());    } else {        //We need to handle an error saying that location is not enabled for this device and exit them out of the app    }}private Location getLastKNownLocation() {    locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);    List<String> provIDers = locationManager.getProvIDers(true);    Location bestLocation = null;    for (String provIDer : provIDers) {        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {            return null;        } else {            Location l = locationManager.getLastKNownLocation(provIDer);            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {                // Found best last kNown location: %s", l);                bestLocation = l;            }        }    }    return bestLocation;}public boolean checkLocationEnabled() {    try {        gps_enabled = locationManager.isProvIDerEnabled(LocationManager.GPS_PROVIDER);    } catch(Exception ex) {    }    try {        network_enabled = locationManager.isProvIDerEnabled(LocationManager.NETWORK_PROVIDER);    } catch(Exception ex) {    }    if(!gps_enabled && !network_enabled) {        // notify user        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());        dialog.setMessage(getContext().getResources().getString(R.string.gpsNetworkNotEnabled));        dialog.setPositivebutton(getContext().getResources().getString(R.string.openLocationSettings), new DialogInterface.OnClickListener() {            @OverrIDe            public voID onClick(DialogInterface paramDialogInterface, int paramInt) {                Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);                getContext().startActivity(myIntent);                //get gps            }        });        dialog.setNegativebutton(getContext().getString(R.string.cancel), new DialogInterface.OnClickListener() {            @OverrIDe            public voID onClick(DialogInterface paramDialogInterface, int paramInt) {            }        });        dialog.show();    }    return gps_enabled || network_enabled;}

我所做的是当电话位置服务关闭时,我设置了一个警报,将您带到位置服务屏幕.当用户打开位置服务屏幕时,如果他或她点击他或她的电话上的“后退”,则应将他们带回到初始屏幕,该屏幕显示他们的位置服务处于警戒状态.但是,当导航回该屏幕时,我的progressOverlay变量仍然可见,因为在databasequery.getPublicposts调用通过时,progressOverlay设置为VIEw.GONE.这似乎不会发生,因为当我们导航回屏幕时,if(location!= null)语句可能是错误的,但在手机等待几秒钟并完全获得手机的位置后可能设置为true.这很有意思,因为如果我在该代码中的任何地方放置一个调试器,位置服务将被正确设置并且我的progressOverlay将消失,因为在我调试代码时该位置已设置.在调用databasequery.getPublicposts之前,有没有什么方法可以“等待”或继续显示加载屏幕,直到位置服务完全打开?任何帮助,将不胜感激.

解决方法:

嗨为什么尝试使用getLastKNownLocation.It返回您之前的纬度和经度,可能需要一些时间来更新上一个已知位置.
很可能它会在您的位置后退回null.

我只是指你谷歌融合API的位置任何类型的更新或当前.它非常准确.

你如何在你的项目中融合API.看,我会给你一个小例子.

步骤1.制作此类GoogleLocationService.java

public class GoogleLocationService {private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();LocationUpdateListener locationUpdateListener;Context activity;protected Googleapiclient mGoogleapiclient;protected LocationRequest mLocationRequest;public static final long UPDATE_INTERVAL_IN_MILliSECONDS = 30000;public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {    this.locationUpdateListener = locationUpdateListener;    this.activity = activity;    buildGoogleapiclient();}protected synchronized voID buildGoogleapiclient() {    //Log.i(TAG, "Building Googleapiclient");    mGoogleapiclient = new Googleapiclient.Builder(activity)            .addConnectionCallbacks(callbacks)            .addOnConnectionFailedListener(callbacks)            .addAPI(LocationServices.API)            .build();    createLocationRequest();    mGoogleapiclient.connect();}protected voID createLocationRequest() {    mLocationRequest = new LocationRequest();    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILliSECONDS);    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);}private class GoogleServicesCallbacks implements Googleapiclient.ConnectionCallbacks, Googleapiclient.OnConnectionFailedListener, LocationListener {    @OverrIDe    public voID onConnected(Bundle bundle) {        startLocationUpdates();    }    @OverrIDe    public voID onConnectionSuspended(int i) {        mGoogleapiclient.connect();    }    @OverrIDe    public voID onConnectionFailed(@NonNull ConnectionResult connectionResult) {        if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_required) {            Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();        }        locationUpdateListener.cannotReceiveLocationUpdates();    }    @OverrIDe    public voID onLocationChanged(Location location) {        if (location.hasAccuracy()) {            if (location.getAccuracy() < 30) {                locationUpdateListener.updateLocation(location);            }        }    }}private static boolean locationEnabled(Context context) {    boolean gps_enabled = false;    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);    try {        gps_enabled = lm.isProvIDerEnabled(LocationManager.GPS_PROVIDER);    } catch (Exception ex) {        ex.printstacktrace();    }    return gps_enabled;}private boolean servicesConnected(Context context) {    return isPackageInstalled(GooglePlayServicesUtil.Google_PLAY_STORE_PACKAGE, context);}private boolean isPackageInstalled(String packagename, Context context) {    PackageManager pm = context.getPackageManager();    try {        pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);        return true;    } catch (PackageManager.nameNotFoundException e) {        e.printstacktrace();        return false;    }}public voID startUpdates() {    /*     * Connect the clIEnt. Don't re-start any requests here; instead, wait     * for onResume()     */    if (servicesConnected(activity)) {        if (locationEnabled(activity)) {            locationUpdateListener.canReceiveLocationUpdates();            startLocationUpdates();        } else {            locationUpdateListener.cannotReceiveLocationUpdates();            Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();        }    } else {        locationUpdateListener.cannotReceiveLocationUpdates();        Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();    }}//stop location updatespublic voID stopUpdates() {    stopLocationUpdates();}//start location updatesprivate voID startLocationUpdates() {    if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {        return;    }    if (mGoogleapiclient.isConnected()) {        LocationServices.FusedLocationAPI.requestLocationUpdates(mGoogleapiclient, mLocationRequest, callbacks);    }}public voID stopLocationUpdates() {    if (mGoogleapiclient.isConnected()) {        LocationServices.FusedLocationAPI.removeLocationUpdates(mGoogleapiclient, callbacks);    }}public voID startGoogleAPI() {    mGoogleapiclient.connect();}public voID closeGoogleAPI() {    mGoogleapiclient.disconnect();} }

第2步.制作这个界面
LocationUpdateListener.java

 public interface LocationUpdateListener {/** * Called immediately the service starts if the service can obtain location */voID canReceiveLocationUpdates();/** * Called immediately the service trIEs to start if it cannot obtain location - eg the user has Disabled wireless and */voID cannotReceiveLocationUpdates();/** * Called whenever the location has changed (at least non-trivially) * @param location */voID updateLocation(Location location);/** * Called when GoogleLocationServices detects that the device has moved to a new location. * @param localityname The name of the locality (somewhere below street but above area). */voID updateLocationname(String localityname, Location location);}

第3步.在想要获取位置的地方使用这段代码

public class MainActivity extends ActionBaractivity {private GoogleLocationService GoogleLocationService;@OverrIDeprotected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_main);    GoogleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {    @OverrIDe    public voID canReceiveLocationUpdates() {    }    @OverrIDe    public voID cannotReceiveLocationUpdates() {    }    //update location to our servers for tracking purpose    @OverrIDe    public voID updateLocation(Location location) {        if (location != null ) {            Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());        }    }    @OverrIDe    public voID updateLocationname(String localityname, Location location) {        GoogleLocationService.stopLocationUpdates();    }});GoogleLocationService.startUpdates();}@OverrIDepublic voID onDestroy() {    super.onDestroy();if (GoogleLocationService != null) {    GoogleLocationService.stopLocationUpdates();}}}

更新的答案
如何通过广播发送和接收lat lng

称之为onlocationchanged

Intent sendbroadIntentPND = new Intent("COORD_broADCAST_FILTER");                    sendbroadIntentPND.putExtra("LOC_LAT", location.getLatitude());sendbroadIntentPND.putExtra("LOC_LON", location.getLongitude());getApplicationContext().sendbroadcast(sendbroadIntentPND);

然后你想以这种方式接收位置呼叫

// declear global variableprivate final String COORD_broADCAST_FILTER = "COORD_broADCAST_FILTER";private Location newLocation;private broadcastReceiver coordinateReceiver = new broadcastReceiver() {    @OverrIDe    public voID onReceive(Context context, Intent intent) {try {            newLocation.setLatitude(intent.getDoubleExtra("LOC_LAT", 0.0));            newLocation.setLongitude(intent.getDoubleExtra("LOC_LON", 0.0));        } catch (Exception e) {            e.printstacktrace();        }    } };

注册接收者oncreate,

 getActivity().registerReceiver(coordinateReceiver, new IntentFilter(COORD_broADCAST_FILTER));

注销你的接收器ondestroy

 getActivity().unregisterReceiver(coordinateReceiver);

谢谢希望这对你有所帮助.

总结

以上是内存溢出为你收集整理的java – 通过位置服务警报打开后等待,直到位置打开全部内容,希望文章能够帮你解决java – 通过位置服务警报打开后等待,直到位置打开所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1118359.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存