BQuadra
BQuadra

Reputation: 819

Run only a background service when application start

I want to start only to start a service when my application start. Here is my code:

My Service class:

public class MyService extends Service {
 @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

     Log.i("LocalService", "Received start id " + startId + ": " + intent);

   // We want this service to continue running until it is explicitly
   // stopped, so return sticky.
   return START_STICKY;
  }

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

My BroadcastReceiver class:

public class MyServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Intent service = new Intent(context, MyService.class);
    context.startService(service);
}
}

And my AndroidManifest file:

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <service
      android:name=".MyService"
      android:label="@string/app_name"
      android:enabled="true"
      android:process=":my_process" >
    </service>

    <receiver 
        android:name=".MyServiceReceiver"
        android:enabled="true" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <category android:name="android.intent.category.HOME"/>
        </intent-filter>
    </receiver>

</application>

I want to start my service when the application start (is installed the first time) and when the device boot.

P.S. If the code is right, maybe I have to setup a particular configuration for the eclipse "run" button? If try to create a new configuration I can't select nothing in "Launch action" because my application haven't an activity, and I have to select "Do nothing".

Thanks

Upvotes: 2

Views: 11552

Answers (1)

IssacZH.
IssacZH.

Reputation: 1477

You're going to need a main activity to call this service within onCreate if you want the service to start as soon as you start your application. In your main activity, include this code in your onCreate:

startService(new Intent(Main_Activity.this,MyServiceReceiver.class));

This is just to call your service when you start up your application.

Upvotes: 1

Related Questions