Android实现开机自启动Service

来源:互联网 发布:爱淘宝退款红包会退吗 编辑:程序博客网 时间:2024/05/19 02:25

    首先做一个监听器:

Java代码:
  1. public class StartBroadcastReceiver extends BroadcastReceiver{

  2. private static final String ACTION = "android.intent.action.BOOT_COMPLETED";

  3. public void onReceive(Context context, Intent intent) {

  4. if (intent.getAction().equals(ACTION)){

  5. Intent i= new Intent(Intent.ACTION_RUN);

  6. i.setClass(context, TService.class);

  7. context.startService(i);

  8. }

  9. }

  10. }


复制代码

然后再做一个service:

Java代码:

  1. package com.testService;

  2. import android.app.Notification;
  3. import android.app.NotificationManager;
  4. import android.app.PendingIntent;
  5. import android.app.Service;
  6. import android.content.Intent;
  7. import android.os.Binder;
  8. import android.os.Handler;
  9. import android.os.IBinder;
  10. import android.util.Log;

  11. public class TService extends Service {

  12.   /**

  13.   * 创建Handler对象,作为进程传递postDelayed之用

  14.   */

  15. private Handler objHandler = new Handler();

  16. private int intCounter = 0;

  17. private static final String TAG = "TService";

  18. private NotificationManager notificationManager;

  19. private Runnable mTasks = new Runnable() {

  20. public void run() {

  21. intCounter++;

  22. Log.i("HIPPO", "Counter:" + Integer.toString(intCounter));

  23. objHandler.postDelayed(mTasks, 1000);

  24. }

  25. };

  26. public void onCreate() {

  27. Log.d(TAG, "============> TService.onCreate");

  28. notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

  29. showNotification();

  30. super.onCreate();

  31. }

  32. public void onStart(Intent intent, int startId) {

  33. Log.i(TAG, "============> TService.onStart");

  34. objHandler.postDelayed(mTasks, 1000);

  35. super.onStart(intent, startId);

  36. }

  37. public IBinder onBind(Intent intent) {

  38. Log.i(TAG, "============> TService.onBind");

  39. return null;

  40. }

  41. public class LocalBinder extends Binder {

  42. public TService getService() {

  43. return TService.this;


  44. }

  45. }

  46. public boolean onUnbind(Intent intent) {

  47. Log.i(TAG, "============> TService.onUnbind");

  48. return false;

  49. }

  50. public void onRebind(Intent intent) {

  51. Log.i(TAG, "============> TService.onRebind");

  52. }

  53. public void onDestroy() {

  54. Log.i(TAG, "============> TService.onDestroy");

  55. notificationManager.cancel(R.string.service_start);

  56. objHandler.removeCallbacks(mTasks);

  57. super.onDestroy();

  58. }

  59. private void showNotification() {

  60. Notification notification = new Notification(R.drawable.icon,

  61. "SERVICE START", System.currentTimeMillis());


  62. Intent intent = new Intent(this, testService.class);

  63. intent.putExtra("FLG", 1);

  64. PendingIntent contentIntent = PendingIntent.getActivity(this, 0,intent, 0);

  65. notification.setLatestEventInfo(this, "SERVICE", "SERVICE START",contentIntent);

  66. notificationManager.notify(R.string.service_start, notification);

  67. }

  68. }


复制代码

做一个主程序:

Java代码:

  1.        package com.testService;

  2.   import android.app.Activity;
  3.        import android.content.Context;
  4.        import android.content.Intent;
  5.        import android.os.Bundle;
  6.        import android.view.View;
  7.        import android.view.View.OnClickListener;
  8.        import android.widget.Button;
  9.        import android.widget.Toast;

  10.   public class testService extends Activity {

  11.   private Button button01;

  12.   private Button button02;

  13.        private int flg;

  14.   private Intent tsIntent;

  15.   /** Called when the activity is first created. */

  16.   @Override
  17.        public void onCreate(Bundle savedInstanceState) {

  18.   super.onCreate(savedInstanceState);

  19.   setContentView(R.layout.main);

  20.   button01 = (Button)findViewById(R.id.Button01);

  21.   button02 = (Button)findViewById(R.id.Button02);

  22.   tsIntent = this.getIntent();

  23.   Bundle bundle = tsIntent.getExtras();

  24.   if (bundle == null){

  25.   flg = 1;

  26.   DisplayToast(this,"Service Start",2);

  27.   startService();

  28.   finish();

  29.   }

  30.        else{

  31.   DisplayToast(this,"Service Stop",2);

  32.   stopService();

  33.   finish();

  34.   }

  35.   button01.setOnClickListener(Listener01);

  36.   button02.setOnClickListener(Listener02);

  37.   }

  38.   Button.OnClickListener Listener01 = new OnClickListener(){

  39.   @Override
  40.         public void onClick(View v) {

  41.   // TODO Auto-generated method stub

  42.   startService();

  43.   }

  44.   };

  45.   Button.OnClickListener Listener02 = new OnClickListener(){

  46.   @Override
  47.        public void onClick(View v) {

  48.   // TODO Auto-generated method stub

  49.   stopService();

  50.   }

  51.   };

  52.   private void startService() {

  53.   Intent i = new Intent(testService.this, TService.class);

  54.   i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

  55.   this.startService(i);

  56.   }

  57.   private void stopService() {

  58.   Intent i = new Intent(testService.this, TService.class);

  59.   this.stopService(i);

  60.   }

  61.   public static void DisplayToast(Context context , String str , int time){

  62.   if (time == 1){

  63.   //短时间显示Toast

  64.   Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

  65.   }

  66.        else if (time == 2){

  67.        //长时间显示Toast

  68.   Toast.makeText(context, str, Toast.LENGTH_LONG).show();

  69.   }

  70.   }

  71.   }


复制代码

 不要忘了在androidmenfest.xml中注册一下接受广播器和服务以及开通权限:

接收广播器

Java代码:
  1.        < receiver android:name=".StartBroadcastReceiver">

  2.   < intent-filter>

  3.   < action android:name="android.intent.action.BOOT_COMPLETED"/>

  4.   < /intent-filter>

  5.   < /receiver>


复制代码

服务:

Java代码:
  1.        < service android:name=".TService"

  2.   android:label="TService"

  3.   android:icon="@drawable/icon"

  4.   android:enabled="true"

  5.   android:exported="true"

  6.   android:process=":remote">

  7.   < /service>


复制代码

注册权限:

Java代码:

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


复制代码
原创粉丝点击