使用json将纬度和经度数据发送到服务器

时间:2014-11-13 15:16:11

标签: android json

我正在开发应用程序,它将使用json将经度和纬度数据发送到服务器。 我已经在名为LocationServices的android中创建了Service。 当onLocationChanged我将json值传递给LocationWebService类。 但是当位置发生变化时,它不会将数据插入表中。

以下是我的LocationServices

public class LocationServices extends Service {

WakeLock wakeLock;

private LocationManager locationManager;

public LocationServices() {
    // TODO Auto-generated constructor stub
}

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

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

    PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);

    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");

    // Toast.makeText(getApplicationContext(), "Service Created",
    // Toast.LENGTH_SHORT).show();

    Log.e("Google", "Service Created");

}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
   // Let it continue running until it is stopped.
   Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
   return START_STICKY;
}


@Override
@Deprecated
public void onStart(Intent intent, int startId) {
    // TODO Auto-generated method stub
    super.onStart(intent, startId);

    Log.e("Google", "Service Started");

    locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            5000, 5, listener);

}

private LocationListener listener = new LocationListener() {
      String MNO="";
    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

        Log.e("Google", "Location Changed");

        if (location == null)
            return;

        if (isConnectingToInternet(getApplicationContext())) {
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();

            try {
                Log.e("latitude", location.getLatitude() + "");
                Log.e("longitude", location.getLongitude() + "");

                SharedPreferences settings0 = getSharedPreferences("MNO",Context.MODE_PRIVATE);
                MNO = settings0.getString("MNO", "");



                jsonObject.put("MNO", MNO);
                jsonObject.put("latitude", location.getLatitude());
                jsonObject.put("longitude", location.getLongitude());

                jsonArray.put(jsonObject);

                Log.e("request", jsonArray.toString());

                new LocationWebService().execute(new String[] {
                         jsonArray.toString() });
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
};

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

    wakeLock.release();

}

public static boolean isConnectingToInternet(Context _context) {
    ConnectivityManager connectivity = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

    }
    return false;
}


public class LocationWebService extends AsyncTask<String, String, Boolean> {

public LocationWebService() {
    // TODO Auto-generated constructor stub
}

@Override
protected Boolean doInBackground(String... arg0) {



    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("location", arg0[1]));
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("insertLocation.php");
    HttpParams httpParameters = new BasicHttpParams();
    httpclient = new DefaultHttpClient(httpParameters);

    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response;
        response = httpclient.execute(httppost);

        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {

            Log.e("Google", "Server Responded OK");

        } else {

            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }

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

    return null;
}
}

}

以下是我的insertLocation.php

<?php
    $mno = $_POST['MNO'];
    $latitude = $_POST['Latitude'];
    $longitude = $_POST['Longitude'];

    //Include db connect class
    $hostname_localhost ="localhost";
    $database_localhost ="geolocation";
    $username_localhost ="geolocation";
    $password_localhost ="geolocation123";
    $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);    
    mysql_select_db($database_localhost, $localhost);

    $flag['code']=0;
    //Mysql inserting a new 

    $result = mysql_query("INSERT INTO location(mno,latitude,longitude) VALUES('$mno','$latitude','$longitude')");  
    if($result)
    {
        $flag['code']=200;
    } 
    echo json_encode($flag);
    mysql_close($con);
    ?>

我已检查服务已启动,但数据未发送到服务器或正常返回。

Plz帮助...

提前致谢

0 个答案:

没有答案