Holen Sie die neue Variable in den JSON-String, nachdem Sie den neuen Wert vom Server erhalten haben.

Ich beginne meinTrackingService Klasse aus demMainActivity welches nur diese onCreate () Methode enthält:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent i = new Intent(this, TrackingService.class);
    startService(i);

}

Ich sende einige Datenroute, long, lat, mac zum Server. Wenn die Route nicht @ i0 Ich erhalte die folgende Antwort vom Server{"status": 201}. Oft ist dasroutes ist0 dann wird der Server gebeten, die App mit dem @ zu versehroutes wenn es genügend Informationen gibt, um es zu berechnen. In diesem Fall erhalte ich diese Antwort

{
 "status":230,
 "routes":[9],
 "distance":296.7374922
}

Nachher dasroutes wird an das @ übergebonAsyncTaskFinished in demTrackingService Klasse. Dort wird die route_number dem neuen Wert @ zugewies9 anschließend dasroutes in der JSON-Zeichenfolge hat einen Wert von9und kann zum Einfügen in die Datenbanktabelle an den Server gesendet werden.

Aus dem TrackingService entwickle ich dasroute, long, lat, mac mitGson und sende es an dasPostData class dann werden die Daten mit Hilfe von AsyncTask an den Server übertragen.

Der Code funktioniert gut, wenn die App im Vordergrund ausgeführt wird, aber wenn sie im Hintergrund ausgeführt wird, wird er falsch verarbeitet. Die route_number wird dem neuen Wert nicht zugewiesen.

public class TrackingService extends Service implements AsyncTaskCallback  {

    Location location;
    LocationManager locationManager;

    int route_number = 0;
    int speed;
    double pLong;
    double pLat;

    @Override
    public void onCreate() {


    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        detectLocation();

        return START_STICKY;
    }

    private void detectLocation() {

        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener ll = new myLocationListener(this);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, 0,
                ll);

    }

    class myLocationListener implements LocationListener {
        final Context bContext;

        public myLocationListener(Context context) {
            bContext = context;
        }

        @Override
        public void onLocationChanged(Location location) {

            // TODO Auto-generated method stub
            if (location != null) {
                 pLong = location.getLongitude();
                 pLat = location.getLatitude();
                 speed = (int) ((location.getSpeed() * 3600) / 1000);

                String mac = get_mac_address();

                String jSONString = convertToJSON(mac, pLong, pLat, time);

                if (isNetworkAvailable()) {
                    System.out.println(jSONString);

                    PostData sender = new PostData(TrackingService.this);
                    sender.post_data(jSONString, bContext);

                } else {
                    Toast.makeText(TrackingService.this,
                            "The device is not connected to the internet ",
                            Toast.LENGTH_SHORT).show();

                }

            }
        }


    } 



    private String convertToJSON(String mac, double pLong, double pLat,
            String time) {
        Data d = new Data(mac, pLat, pLong, time, route_number);
        Gson gson = new GsonBuilder().registerTypeAdapter(Data.class,
                new DataSerializer()).create();
        String a = gson.toJson(d);
        return a;
    }


    @Override
    public void onAsyncTaskFinished(ArrayList<Integer> routeList, double distance) {
        if (distance <= 15 && speed <= 4) {
            stop_popup(routeList);

        } else {
            route_number = routeList.get(0);
            System.out.println("The route number is: " + route_number);
        }

    }

}

PostData-Klasse:

public class PostData {
    String jSONString;
    private AsyncTaskCallback callback;


    public PostData(AsyncTaskCallback callback) {
        this.callback = callback;
    }

    public String getjSONString() {
        return jSONString;

    }

    public void setjSONString(String jSONString) {
        this.jSONString = jSONString;
    }

    public void post_data(String jSONString, Context context) {
        this.jSONString = jSONString;

        new MyAsyncTask(context).execute(jSONString);

    }

    class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<Integer>> {
        final Context mContext;
        ArrayList<Integer> routes = new ArrayList<Integer>();
        double distance;

        public MyAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected ArrayList<Integer> doInBackground(String... params) {
            // TODO Auto-generated method stub
            BufferedReader reader = null;

            try {
                System.out.println("The output of : doInBackground "
                        + params[0]);

                URL myUrl = new URL(
                        "https://bustrackerserver-test.rhcloud.com/webapi/test");

                HttpURLConnection conn = (HttpURLConnection) myUrl
                        .openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.connect();

                DataOutputStream wr = new DataOutputStream(
                        conn.getOutputStream());
                wr.writeBytes(params[0]);

                wr.close();

                StringBuilder sb = new StringBuilder();
                reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String line;

                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");

                }

                Gson gson = new Gson();
                StopsJSON data = gson.fromJson(sb.toString(), StopsJSON.class);

                routes = data.getRoutes();
                distance = data.getDistance();

            } catch (IOException e) {

                e.printStackTrace();
                return null;
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                        return null;
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            return null;

        }

        protected void onPostExecute(ArrayList<Integer> result) {

             if (routes != null && !routes.isEmpty()) {
            callback.onAsyncTaskFinished(routes, distance);
             }else{
                 Log.e("123", "Avoiding null pointer, the routes are null!!!");
             }
        }

    }

}

Ein Teil der Ausgabe, wenn die App im Vordergrund läuft:

05-28 00:04:02.825: I/System.out(1951): The output of : doInBackground {"mac":"10:A5:D0:06:C6:E9","latitude":53.8689686,"longitude":10.6655828,"route":0}
05-28 00:04:02.856: I/System.out(1951): (HTTPLog)-Static: isSBSettingEnabled false
05-28 00:04:03.026: I/System.out(1951): The output of the StringBulder: {"status":230,"routes":[9],"distance":296.0401842426428}
05-28 00:04:03.026: I/System.out(1951): The route number is: 9
05-28 00:04:12.795: I/System.out(1951): {"mac":"10:A5:D0:06:C6:E9","latitude":53.86892455,"longitude":10.66564527,"route":9}
05-28 00:04:12.835: I/System.out(1951): The output of : doInBackground {"mac":"10:A5:D0:06:C6:E9","latitude":53.86892455,"longitude":10.66564527,"route":9}
05-28 00:04:12.835: I/System.out(1951): (HTTPLog)-Static: isSBSettingEnabled false
05-28 00:04:13.096: I/System.out(1951): The output of the StringBulder: {"status":201}
05-28 00:04:13.096: E/123(1951): Avoiding null pointer, the routes are null!!!
05-28 00:04:23.796: I/System.out(1951): {"mac":"10:A5:D0:06:C6:E9","latitude":53.86882877,"longitude":10.66568087,"route":9}
05-28 00:04:23.806: I/System.out(1951): The output of : doInBackground {"mac":"10:A5:D0:06:C6:E9","latitude":53.86882877,"longitude":10.66568087,"route":9}
05-28 00:04:23.826: I/System.out(1951): (HTTPLog)-Static: isSBSettingEnabled false
05-28 00:04:23.896: I/System.out(1951): KnoxVpnUidStorageknoxVpnSupported API value returned is false
05-28 00:04:24.617: I/System.out(1951): The output of the StringBulder: {"status":201}
05-28 00:04:24.627: E/123(1951): Avoiding null pointer, the routes are null!!!
05-28 00:04:34.767: I/System.out(1951): {"mac":"10:A5:D0:06:C6:E9","latitude":53.86887302,"longitude":10.66568765,"route":9}
05-28 00:04:34.797: I/System.out(1951): The output of : doInBackground {"mac":"10:A5:D0:06:C6:E9","latitude":53.86887302,"longitude":10.66568765,"route":9}
05-28 00:04:34.797: I/System.out(1951): (HTTPLog)-Static: isSBSettingEnabled false
05-28 00:04:35.017: I/System.out(1951): The output of the StringBulder: {"status":201}

Antworten auf die Frage(0)

Ihre Antwort auf die Frage