2

I've created a geo-location app that collects location information of the device and compares it to a pre-defined lat/long coordinates to perform certain actions when they match.

Currently I have an activity page where the users can enter the coordinates as well as other parameters such as radius and interval for polling. Also, the app starts only when the user starts it.

I wish to convert it into a service that does the following

  • runs in the background
  • parameters are read from a configuration file (this part is already done) hence no need for any main activity (no UI)
  • starts up automatically (probably need an android.intent.action.BOOT_COMPLETED BroadcastReceiver)

How do I do this?

Thanks.

V_J
  • 1,081
  • 13
  • 33
user1118764
  • 9,255
  • 18
  • 61
  • 113

1 Answers1

2

You have to create a service for your application, like this:

ExampleService.java:

public class ExampleService extends Service {

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



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

    Log.d(TAG, "onStart()===>In");
   // Write your application logical code here

}

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

}

BootCompleteReceiver.java

public class BootCompleteReceiver extends BroadcastReceiver {

private static final String TAG = "[BootCompleteReceiver]";

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Toast.makeText(context, "Boot complete", Toast.LENGTH_LONG).show();
    Log.d(TAG, "Boot complete");
    // Start the ExampleService
    Intent service = new Intent(context, ExampleService.class);
    context.startService(service);
}

}

In Android Manifest:

<!-- Server as a service -->
<service
android:name="com.example.ExampleService"
android:enabled="true" >
</service>

<!-- Boot complete receiver -->
<receiver
android:name="com.example.BootCompleteReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

You also have to create a activity to start the service manually and awake the service from the activity.

V_J
  • 1,081
  • 13
  • 33