获取位置仅获取UI线程上的位置(GPS位置)

时间:2019-11-17 04:07:54

标签: java android

您好,Android开发人员或Java开发人员,

今天我遇到了一个问题,这是获取位置的代码:

public class GpsTracker implements LocationListener{
    public Location getLocation() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isGPSEnabled) {

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            return location;
        }else {

        }
        return null;
    }
    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

第二个代码:

public void getLocation(final int childId){
    GpsTracker gpsTracker = new GpsTracker();
    Location location = gpsTracker.getLocation();
    if (location != null){
        final double longitude = location.getLongitude();
        final double latitude = location.getLatitude();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, WebConfig.INSERT_GPS_LOCATION, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("FKchild_id", Integer.toString(childId));
                params.put("longitude", Double.toString(longitude));
                params.put("latitude", Double.toString(latitude));

                return params;
            }
        };
        RequestHandler.getInstance(context).addToRequestQueue(stringRequest);
    }



}

上述《准则》非常有效。

现在是问题所在

 private void backgroundTasks() {


        final BackgroundTask backgroundTask = new BackgroundTask(this);

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(8);
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

                final int userId = SharedPrefManager.getInstance(getApplicationContext()).getUserId();
                String userType = SharedPrefManager.getInstance(getApplicationContext()).getUserType();
                boolean isLoggedIn = SharedPrefManager.getInstance(getApplicationContext()).isLoggedIn();

                if (userId != 0 && userType.equals("child") && isLoggedIn) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            backgroundTask.getLocation(userId);
                        }
                    });
                    backgroundTask.getSms(userId);
                    backgroundTask.getCallLogs(userId);
                    backgroundTask.getContacts(userId);


                }
            }
        }, 0, 1, TimeUnit.SECONDS);


}

如您所见,我将backgroundTask.getLocation(userId);在UI线程中,因为如果在后台线程中执行此操作。它不会工作。有什么解决办法吗?谢谢

1 个答案:

答案 0 :(得分:0)

最佳解决方案是:

处理程序

您可以在主要活动中构建处理程序,然后在其中找到位置并向其显示活动是否存在。

在后台运行应用程序时起作用。

还有第二种方法:

服务

后台服务将满足您的需求。

在评论中更新我