2012年12月8日 星期六

Service


Hello,
Now we are going to learn how to start a service at boot time, i.e. to start our service when device starts up.
First we have to create a BroadcastReceiver which will be started when boot completes as
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyStartupIntentReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
}
}
onRecieve will be first called when the BroadcastReceiver MyStartupIntentReceiver starts.
Next make an entry of this receiver in AndroidManifest.xml as
<receiver android:name="MyStartupIntentReceiver">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
Here in intent filter we have declared the action as android.intent.action.BOOT_COMPLETED , so that this receiver and intent with action android.intent.action.BOOT_COMPLETED
Now this receiver will be intimated when boot completes
Next if we want to start a service then the procedure is as follows
Create a Service as
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

@Override
public IBinder onBind(Intent intent) {

return null;

}

@Override
public void onCreate() {
super.onCreate();

Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();

}

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

Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

}

@Override
public void onStart(Intent intent, int startId) {

super.onStart(intent, startId);

Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

}
}
Make an entry of this service in AndroidManifest.xml as
<service android:name="MyService">
<intent-filter>
<action
android:name="com.wissen.startatboot.MyService" />
</intent-filter>
</service>
Now start this service in the BroadcastReceiver MyStartupIntentReceiver’s onReceive method as
 public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.wissen.startatboot.MyService");
context.startService(serviceIntent);

}
Next you can write the code that you want to execute when device boots up in the BroadcastReceiver or in the Service

沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...