Android实现开机自启动Service

首先做一个监听器:

         public class StartBroadcastReceiver extends BroadcastReceiver{

  1. private static final String ACTION = "android.intent.action.BOOT_COMPLETED";
  2. public void onReceive(Context context, Intent intent) {
  3.                 if (intent.getAction().equals(ACTION)){
  4.                         Intent i= new Intent(Intent.ACTION_RUN);
  5.                         i.setClass(context, TService.class);
  6.                         context.startService(i);
  7.                 }
  8.         }
  9.        
  10. }
  11. 然后再做一个service:
    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.        
    33.         public void onStart(Intent intent, int startId) {
    34.                 Log.i(TAG, "============> TService.onStart");
    35.                 objHandler.postDelayed(mTasks, 1000);
    36.                 super.onStart(intent, startId);
    37.         }
    38.         public IBinder onBind(Intent intent) {
    39.                 Log.i(TAG, "============> TService.onBind");
    40.                 return null;
    41.         }
    42.         public class LocalBinder extends Binder {
    43.                 public TService getService() {
    44.                         return TService.this;
    45.                 }
    46.         }
    47.         public boolean onUnbind(Intent intent) {
    48.                 Log.i(TAG, "============> TService.onUnbind");
    49.                 return false;
    50.         }
    51.         public void onRebind(Intent intent) {
    52.                 Log.i(TAG, "============> TService.onRebind");
    53.         }
    54.         public void onDestroy() {
    55.                 Log.i(TAG, "============> TService.onDestroy");
    56.                 notificationManager.cancel(R.string.service_start);
    57.                 objHandler.removeCallbacks(mTasks);
    58.                 super.onDestroy();
    59.         }
    60.         private void showNotification() {
    61.                 Notification notification = new Notification(R.drawable.icon,
    62.                                 "SERVICE START", System.currentTimeMillis());
    63.                 Intent intent = new Intent(this, testService.class);
    64.                 intent.putExtra("FLG", 1);
    65.                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
    66.                                 intent, 0);
    67.                 notification.setLatestEventInfo(this, "SERVICE", "SERVICE START",
    68.                                 contentIntent);
    69.                 notificationManager.notify(R.string.service_start, notification);
    70.         }
    71. }

    做一个主程序:

    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.        
    12.         private Button button01;
    13.         private Button button02;
    14.         private int flg;
    15.         private Intent tsIntent;
    16.     /** Called when the activity is first created. */
    17.     @Override
    18.     public void onCreate(Bundle savedInstanceState) {
    19.         super.onCreate(savedInstanceState);
    20.         
    21.         
    22.         setContentView(R.layout.main);
    23.         button01 = (Button)findViewById(R.id.Button01);
    24.         button02 = (Button)findViewById(R.id.Button02);
    25.         
    26.         tsIntent = this.getIntent();
    27.         Bundle bundle = tsIntent.getExtras();
    28.         
    29.         if (bundle == null){
    30.             flg = 1;
    31.             DisplayToast(this,"Service Start",2);
    32.             startService();
    33.             finish();
    34.         }else{
    35.                 DisplayToast(this,"Service Stop",2);
    36.                 stopService();
    37.                 finish();
    38.         }
    39.         
    40.         button01.setOnClickListener(Listener01);
    41.         button02.setOnClickListener(Listener02);
    42.         
    43.     }
    44.    
    45.     Button.OnClickListener Listener01 = new OnClickListener(){
    46.                 @Override
    47.                 public void onClick(View v) {
    48.                         // TODO Auto-generated method stub
    49.                         startService();
    50.                 }
    51.            
    52.     };
    53.    
    54.     Button.OnClickListener Listener02 = new OnClickListener(){
    55.                 @Override
    56.                 public void onClick(View v) {
    57.                         // TODO Auto-generated method stub
    58.                         stopService();
    59.                 }
    60.            
    61.     };
    62.    
    63.         private void startService() {
    64.                 Intent i = new Intent(testService.this, TService.class);
    65.                 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    66.                 this.startService(i);
    67.         }
    68.    
    69.         private void stopService() {
    70.                 Intent i = new Intent(testService.this, TService.class);
    71.                 this.stopService(i);
    72.         }
    73.         public static void DisplayToast(Context context , String str , int time){
    74.                 if (time == 1){
    75.                         //短时间显示Toast
    76.                         Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    77.                 }else if (time == 2){
    78.                         //长时间显示Toast
    79.                         Toast.makeText(context, str, Toast.LENGTH_LONG).show();
    80.                 }
    81.         }
    82. }

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

    1.         <receiver android:name=".StartBroadcastReceiver">
    2.             <intent-filter>
    3.                 <action android:name="android.intent.action.BOOT_COMPLETED"/>
    4.             </intent-filter>
    5.         </receiver>

    服务:

    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>

     

    1. 注册权限:
      1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值