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

Posted

技术标签:

【中文标题】想要在设备离线时将数据存储在本地数据库中,并在在线时从数据库中获取并发送到服务器【英文标题】:want to store data in local db when device is offline and get from db when online and send to server 【发布时间】:2017-01-03 02:19:27 【问题描述】:

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

    我的应用在 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) 


【问题讨论】:

这是你的问题吗I want a alert when gps is disable.? 是的,这是我的问题 我想在没有启用网络提供商时显示警报,并希望在两者都禁用时停止应用程序崩溃 【参考方案1】:

你可以利用这个方法

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

    

【讨论】:

谢谢兄弟,但我想在没有启用网络提供商时显示警报,并希望在两者都禁用时停止应用程序崩溃 访问链接 for alert dialog in server 并使用isEnabled bool 来检查 GPS 或 NETWORK 提供商是否启用。 我使用警报,但是当两者都被禁用时,我怎样才能阻止应用程序崩溃。我想显示警报并停止崩溃,因为每次我同时禁用 gps 和网络时,我的应用程序都会停止工作 请再提出一个关于错误详情的问题。关于gps的这个问题,我回答了。

以上是关于想要在设备离线时将数据存储在本地数据库中,并在在线时从数据库中获取并发送到服务器的主要内容,如果未能解决你的问题,请参考以下文章

当手机离线时,GCM 会存储消息列表或仅存储最后一条消息,就像 APNS 一样?

离线时无法建立与本地主机的连接

当设备在 react-native 中离线时,在 webview 中显示本地图像

CloudKit 记录的本地缓存

离线时发布(React-Native)

在 Flutter 应用程序中使用 Firestore 中的离线持久性