android实现开机自启动服务

时间:2022-07-11 15:40:29

 

1.首先继承一个broadcastreceiver

[java] view plaincopy
  1. public class ConnectBroadCastReceiver extends BroadcastReceiver {  
  2.     @Override  
  3.     public void onReceive(Context context, Intent intent) {  
  4.          if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){  
  5.                 Intent bootActivityIntent=new Intent(context,MainActivity.class);  
  6.                 bootActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  7.                 context.startActivity(MainActivity);//要启动应用程序的首界面  
  8.             }  
  9.     }  
  10.   
  11. }  
2. 在AndroidMenifest.xml中配置Receiver
[html] view plaincopy
  1. <receiver android:name=".BootBroadcastReceiver">  
  2.     <intent-filter>  
  3.         <action android:name="android.intent.action.BOOT_COMPLETED"></action>  
  4.     </intent-filter>  
  5. </receiver>  
3. 添加权限

[html] view plaincopy
  1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>