Android实现开机自启动Service
一,首先做一个易做图:
public class StartBroadcastReceiver extends BroadcastReceiver{
private static final String ACTION = "android.intent.action.BOOT_COMPLETED";
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION)){
Intent i= new Intent(Intent.ACTION_RUN);
i.setClass(context, TService.class);
context.startService(i);
}
}
}
二,然后再做一个service:
package com.testService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class TService extends Service {
/**
* 创建Handler对象,作为进程传递postDelayed之用
*/
private Handler objHandler = new Handler();
private int intCounter = 0;
private static final String TAG = "TService";
private NotificationManager notificationManager;
private Runnable mTasks = new Runnable() {
public void run() {
intCounter++;
Log.i("HIPPO", "Counter:" + Integer.toString(intCounter));
objHandler.postDelayed(mTasks, 1000);
}
};
public void onCreate() {
Log.d(TAG, "============> TService.onCreate");
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
super.onCreate();
}
public void onStart(Intent intent, int startId) {
Log.i(TAG, "============> TService.onStart");
objHandler.postDelayed(mTasks, 1000);
super.onStart(intent, startId);
}
public IBinder onBind(Intent intent) {
Log.i(TAG, "============> TService.onBind");
return null;
}
public class LocalBinder extends Binder {
public TService getService() {
return TService.this;
}
}
public boolean onUnbind(Intent intent) {
Log.i(TAG, "============> TService.onUnbind");
return false;
}
public void onRebind(Intent intent) {
Log.i(TAG, "============> TService.onRebind");
} www.zzzyk.com
public void onDestroy() {
Log.i(TAG, "============> TService.onDestroy");
notificationManager.cancel(R.string.service_start);
objHandler.removeCallbacks(mTasks);
super.onDestroy();
}
private void showNotification() {
Notification notification = new Notification(R.drawable.icon,
"SERVICE START", System.currentTimeMillis());
Intent intent = new Intent(this, testService.class);
intent.putExtra("FLG", 1);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, 0);
notification.setLatestEventInfo(this, &quo
补充:移动开发 , Android ,