trying to make an Android service

jacho981

I'm trying to make an Android service, which should be started on device boot. It should send position data to a mySQL database every 5 minutes, through a POST to a php web service.

it is supposed to send the following data:

regID = same regId it used to register to GCM
name = a user name
latitude = the current latitude
longitude = the current longitude

I've never done a service before, so I'm quite confused on the right way to do it.

I would appreciate if you could guide me towards the right direction.

this is what I've done so far:

package servicio;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Service;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

import com.google.android.gcm.GCMRegistrar;

public class GeoService extends Service {

    LocationManager manejador;
    String proveedor;
    Location localizacion;
    LocationListener locListener;
    String latitud, longitud;
    final String regId = GCMRegistrar
            .getRegistrationId(getApplicationContext());

    // double latitud, longitud;

    @Override
    public void onCreate() {
        manejador = (LocationManager) getSystemService(LOCATION_SERVICE);

    }

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

        Criteria req = new Criteria();
        req.setAccuracy(Criteria.ACCURACY_FINE);

        // Lista de proveedores por criterio
        proveedor = manejador.getBestProvider(req, false);
        localizacion = manejador.getLastKnownLocation(proveedor);

        // location listener
        locListener = new LocationListener() {

            @Override
            public void onLocationChanged(Location location) {
                latitud = String.valueOf(location.getLatitude());
                longitud = String.valueOf(location.getLongitude());

                Thread sendGpsPositionToDB = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        String server = "http://www.grupobcn.es/aquacleanmessenger/";
                        String serverUrl = server + "addposicion.php";
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("iddevice", regId));
                        params.add(new BasicNameValuePair("latitud", latitud));
                        params.add(new BasicNameValuePair("longitud", longitud));

                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost(serverUrl);

                        try {
                            httppost.setEntity(new UrlEncodedFormEntity(params));
                            HttpResponse response = httpclient
                                    .execute(httppost);
                        } catch (IOException e) {
                        }
                    }

                });

                sendGpsPositionToDB.start();
            }

            @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

            }

        };

        manejador.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000,
                0, locListener);

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

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

}
Nana Ghartey

You can achieve this by registering a broadcast receiver and defining the RECEIVE_BOOT_COMPLETED permission.

When users install the app, the OS will look at the manifest and register for auto startup. Anytime the device is booted, the OS will call your onReceive() so you can start your service there as follows:

In your manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<service android:name=".GeoService" />

<receiver android:name="servicio.AutoStartGeo">  
    <intent-filter>  
        <action android:name="android.intent.action.BOOT_COMPLETED" />  
    </intent-filter>  
</receiver>

Define the AutoStartGeo Class:

public class AutoStartGeo extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
      if (intent.getAction() != null){
    Intent startServiceIntent = new Intent(context, GeoService.class);
    context.startService(startServiceIntent);       
}
}

}

Not that this won't work if the app is installed on the SD card because the app won't be available after the android.intent.action.BOOT_COMPLETED event. You must inform users about this or force your app to be installed internally via: android:installLocation="internalOnly"

Also note that on Android 3.0 and later, users needs to have started the app at least once before the app can receive the android.intent.action.BOOT_COMPLETED event.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

trying to make an Android service

From Dev

InvocationTargetException trying to make new instance of service class

From Dev

Trying to start a service on android and get a null object

From Dev

OpenCV Android - trying to make sample application work

From Dev

Trying to make an android app call a number

From Dev

Trying to make an android app call a number

From Dev

Trying to make a custom listview adapter in android

From Dev

OpenCV Android - trying to make sample application work

From Dev

trying to make a textView change with image in android studio

From Dev

Trying to make a pause/resume music activity using service

From Dev

Trying to make a simple Lock Screen app work, struggling with Service & Reciever

From Dev

Trying to make a pause/resume music activity using service

From Dev

Where to make service requests for a fragment to be created in Android?

From Dev

Where to make service requests for a fragment to be created in Android?

From Dev

I want to make a service in android but my service not running?

From Dev

I want to make a service in android but my service not running?

From Dev

Issue trying to expose a Restlet service from Android activity

From Dev

Android TableLayout: Trying to make entried in 1 row larger than another

From Dev

Trying to make a basic webview android app - crash on startup

From Dev

Trying to make an extending class for a pre-existing class in Android

From Dev

Android TableLayout: Trying to make entried in 1 row larger than another

From Dev

Trying to make a android converting app but cant get the math coding right

From Dev

Trying to make a $resource call from a controller through a model to a service, can't get the response back to the controller

From Java

what approach should i follow to make Timer service in android

From Dev

Android Google Play Service: Best practices to make location request

From Dev

Android: how to make a method of getting something from a service with onActivityResult()?

From Dev

Can i make the profile in android to silent or normal in a service class

From Dev

Android Google Play Service: Best practices to make location request

From Dev

Trying to make an image gallery

Related Related

  1. 1

    trying to make an Android service

  2. 2

    InvocationTargetException trying to make new instance of service class

  3. 3

    Trying to start a service on android and get a null object

  4. 4

    OpenCV Android - trying to make sample application work

  5. 5

    Trying to make an android app call a number

  6. 6

    Trying to make an android app call a number

  7. 7

    Trying to make a custom listview adapter in android

  8. 8

    OpenCV Android - trying to make sample application work

  9. 9

    trying to make a textView change with image in android studio

  10. 10

    Trying to make a pause/resume music activity using service

  11. 11

    Trying to make a simple Lock Screen app work, struggling with Service & Reciever

  12. 12

    Trying to make a pause/resume music activity using service

  13. 13

    Where to make service requests for a fragment to be created in Android?

  14. 14

    Where to make service requests for a fragment to be created in Android?

  15. 15

    I want to make a service in android but my service not running?

  16. 16

    I want to make a service in android but my service not running?

  17. 17

    Issue trying to expose a Restlet service from Android activity

  18. 18

    Android TableLayout: Trying to make entried in 1 row larger than another

  19. 19

    Trying to make a basic webview android app - crash on startup

  20. 20

    Trying to make an extending class for a pre-existing class in Android

  21. 21

    Android TableLayout: Trying to make entried in 1 row larger than another

  22. 22

    Trying to make a android converting app but cant get the math coding right

  23. 23

    Trying to make a $resource call from a controller through a model to a service, can't get the response back to the controller

  24. 24

    what approach should i follow to make Timer service in android

  25. 25

    Android Google Play Service: Best practices to make location request

  26. 26

    Android: how to make a method of getting something from a service with onActivityResult()?

  27. 27

    Can i make the profile in android to silent or normal in a service class

  28. 28

    Android Google Play Service: Best practices to make location request

  29. 29

    Trying to make an image gallery

HotTag

Archive