如何在android中将每2分钟位置更新到服务器

时间:2018-04-04 06:27:23

标签: android service

我想每2分钟更新一次到服务器的位置,我在onResume中启动了计时器,在计时器类中我启动了API Rest Calls但是当应用程序被销毁时意味着我无法调用Rest Call。

我怀疑是否必须将计时器放在服务类中,在哪里放置计时器。

Mainactivity.java

public class UserHomePage extends AppCompatActivity i {
  SharedPreferences gs_sharepref_latlong;
      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, getString(R.string.access_token));
        setContentView(R.layout.user_activity_home);
        ctx=this;
        Intent intent = new Intent(ctx,
                MyLocationService.class);
          startService(intent);
 }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        }
 @Override
    protected void onPause() {
        super.onPause();
          }
    @Override
    protected void onStop() {
        super.onStop();
       }

    @Override
    protected void onResume() {
        super.onResume();
      myTask = new MyTimerTask();
        timer = new Timer();
        timer.schedule(myTask, 0, 120000);

    }
   // timer task to sending lat and long for each 2 minutes
    class MyTimerTask extends TimerTask {

        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
  ctx.startService(new Intent(ctx,MyLocationService.class));
 gs_sharepref_latlong = ctx.getSharedPreferences("myprefer", Context.MODE_PRIVATE);
 String gs_str_Latitude1 = gs_sharepref_latlong.getString("Lat", null);
                   String gs_str_Longitude1 = gs_sharepref_latlong.getString("Long", null);
           GS_UserUpdateLocation(ctx,gs_str_Latitude1,gs_str_Longitude1);
                 // Toast.makeText(ctx, "LATLONG-**-" + gs_str_Latitude1 + "***********" + gs_str_Longitude1, Toast.LENGTH_LONG).show();


                }
            });
        }
    }
 public void GS_UserUpdateLocation(Context context, final String gs_var_latitude, final String gs_var_longitude) {
 StringRequest stringRequest = new StringRequest(Request.Method.POST, ServerUtils.GS_UserLocationupdate,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new Hashtable<String, String>();
                params.put("gs_userId",  gs_var_userid);
                params.put("gs_lattitude",  gs_var_latitude);
                params.put("gs_longitude",  gs_var_longitude);
                return params;
            }

        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

        }

服务类

public class MyLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
 LocationManager locationManager ;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    Timer timer;
    MyTimerTask myTask;
    String gs_var_userid,gs_var_roleid;

    private GoogleApiClient mGoogleApiClient = null;
    private LatLng gs_var_mLatLng;

    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(12000)
            .setFastestInterval(16)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    public static boolean isGPSEnabled = false;
    public static boolean isNetworkEnabled = false;
  //to check gps is enabled or not
    @Override
    public void onCreate() {
        super.onCreate();
        locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        buildGoogleApiClient();

    }
  @Override
    public void onLowMemory() {
        super.onLowMemory();

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
     //   Log.i("RR","----destroy--");

        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }
    private synchronized void buildGoogleApiClient() {
        try {
            mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  @Override
    public void onConnected(@Nullable Bundle bundle) {
        try {
            if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
             return;
            }
            if (mGoogleApiClient != null) {
                mGoogleApiClient.connect();
            }
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient,
                    REQUEST,
                    this);  // LocationListener
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    // to get current latitude and longitude
    // storing the updated latitde and longitude when user moving and reach destination
    @Override
    public void onLocationChanged(Location location) {
        try {
            gs_var_mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            Log.i("WW","service class"+gs_var_mLatLng);

            sharedPreferences = getSharedPreferences("myprefer", MODE_PRIVATE);
            editor = sharedPreferences.edit();
            gs_var_userid=Prefs.getuserid(getApplicationContext());


            editor.putString("Lat", String.valueOf(location.getLatitude()));
            editor.putString("Long", String.valueOf(location.getLongitude()));

            editor.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
  return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;


}

注意:如果我在执行onLocationchanged之前将启动命令中的计时器显示为空对象纬度和经度,则启动onstart命令。请帮助我。即使应用程序被销毁状态我想更新位置

1 个答案:

答案 0 :(得分:0)

使用此:

.setInterval(120000)
.setFastestInterval(120000)

每2分钟获取一次位置。