想在设备离线时将数据存储在本地数据库中,在线时从数据库中获取数据并发送到服务器

want to store data in local db when device is offline and get from db when online and send to server

  1. 我每 15 分钟启动一次警报服务,每 15 分钟向服务器发送一次数据。但是当 wifi 不可用时,我无法将数据发送到服务器。我想在 15 分钟后将数据存储在本地数据库中,并在设备在线时发送到服务器。

  2. 我的应用程序在 gps 禁用时停止工作,我想要在 gps 禁用时收到警报。

这里是服务代码

public class LocationService extends Service implements LocationListener {

public static String LOG = "Log";
JSONParser jsonParser = new JSONParser();
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 0 meters
private static final long MIN_TIME_BW_UPDATES = 1000; // 1 second
protected LocationManager locationManager;
private SQLiteHandler db;

public LocationService(Context context) {
    this.mContext = context;
}

public LocationService() {
    super();
    mContext = LocationService.this;
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    db = new SQLiteHandler(getApplicationContext());
    HashMap<String, String> user = db.getUserDetails();
    String uid = user.get("uid");
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String IMEINo =sharedPreferences.getString("IMEI NO",null);

    SimpleDateFormat simpleDateFormat =
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
    Calendar calendar = Calendar.getInstance();
    Date now = calendar.getTime();
    String deviceTimeStamp = simpleDateFormat.format(now);
    Toast.makeText(this,( "latitude" + latitude +"longitude" + longitude +uid), Toast.LENGTH_LONG).show();
    Log.i(LOG, "Service started");
    Log.i("asd", "This is sparta");
    new MyAsyncTask().execute((Double.toString(Double.parseDouble(uid))),
            (Double.toString(getLocation().getLongitude())),
            (Double.toString(getLocation().getLatitude())),
            (Double.toString(Double.parseDouble(IMEINo))),
            (deviceTimeStamp));

    return START_STICKY;
}
@Override
public void onCreate() {
    super.onCreate();
    Log.i(LOG, "Service created");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i(LOG, "Service destroyed");
}

private class MyAsyncTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        postData(params[0],params[1],params[2],params[3],params[4]);

        return "call";
    }

    protected void onPostExecute(String result){

        Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
    }
    public void postData(String uid, String longitude, String latitude, String IMEI, String deviceTimeStamp) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://enftracker.com/app_script/connect1.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("uid", uid));
            nameValuePairs.add(new BasicNameValuePair("longitude", longitude));
            nameValuePairs.add(new BasicNameValuePair("latitude", latitude));
            nameValuePairs.add(new BasicNameValuePair("IMEI", IMEI));
            nameValuePairs.add(new BasicNameValuePair("deviceTimeStamp", deviceTimeStamp));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }

}
public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                //updates will be send according to these arguments
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();

                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return location;
}
@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) {
}
}

你可以利用这个方法

@Override
public void onProviderEnabled(String provider) {
    if (provider.equals(LocationManager.GPS_PROVIDER) {
        boolean isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    }
}