Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

android - Run Gps as background service and send coordinates to web server (PHP)

I know there are many questions that have been asked regarding this and i have been going through all that from couple of days but could'nt find a reasonable answer. i am newbie to android and php so i have no idea how things get done.

so basically first i want to know how to run gps as a service in background like when the application is installed it starts and periodically send the coordinates to web server?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just create a service that runs in the background all the time.

For Example:-

AndroidLocationServices

public class AndroidLocationServices extends Service {

WakeLock wakeLock;

private LocationManager locationManager;

public AndroidLocationServices() {
    // 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
@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() {

    @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() + "");

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

                jsonArray.put(jsonObject);

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

                new LocationWebService().execute(new String[] {
                        Constants.TRACK_URL, 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;
}

}

LocationWebService

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(arg0[0]);
    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;
}
}

You can find a sample project with Android App and corresponding WebFiles within this github project androidbackgroundgps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...