Android开机自启动服务的编写

来源:互联网 发布:java new int 编辑:程序博客网 时间:2024/05/21 18:45
启动式服务的操作步骤
    step1.创建一个子类,继承Service
    step2.启动  startService()

    step3.注册


一、创建一个子类,继承Service

<span style="font-size:14px;">public class TestService extends Service{@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubLog.d("**********banlei_bind***********", null);Toast.makeText(getApplicationContext(), "service_binder", Toast.LENGTH_LONG).show();return null;}public void onCreate(){super.onCreate();Log.d("**********banlei***********", null);Toast.makeText(getApplicationContext(), "service", Toast.LENGTH_LONG).show();}}</span>
二、创建一个广播接收者,重构其抽象方法 onReceive(Context context, Intent intent),在其中启动你想要启动的Service或app。

<span style="font-size:14px;">public class BootReceiver extends BroadcastReceiver{public void onReceive(Context arg0,Intent arg1){Log.d("**********banlei_Boot***********", null);Intent mBootIntent = new Intent(arg0, TestService.class);arg0.startService(mBootIntent);}}</span>

三、在receiver接收这种添加intent-filter配置 ,增加权限

<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.mvserver"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="19"        android:targetSdkVersion="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <service android:name=".TestService"></service>   <receiver android:name=".BootReceiver">       <intent-filter >           <action android:name="android.init.action.BOOT_COMPLETED" />       </intent-filter>   </receiver>    </application></manifest></span>



1 0