android系统启动时自动运行自己的程序

  
android系统在Manifest.permission中有这样一条RECEIVE_BOOT_COMPLETED的定义,当你自己的程序加 入这个权限后,
就可以在系统启动完毕后收到一条系统的广播,这个广播的标志为ACTION_BOOT_COMPLETED,
因此我们只要定义一个 BroadcastReceiver用来接收这个广播,然后加入自定义的动作即可。代码如下:

public class LocationLoggerServiceManager extends BroadcastReceiver { public static final String TAG = "customTag"; @Override public void onReceive(Context context, Intent intent) { if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { ComponentName comp = new ComponentName(context.getPackageName(), MainActivity.class.getName()); context.startActivity(new Intent().setComponent(comp).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } else { Log.e(TAG, "Received unexpected intent " + intent.toString()); } } }

在AndroidManifest.xml中加入这个类的定义和权限说明
    <receiver  
                android:name=".LocationLoggerServiceManager"  
                android:enabled="true"  
                android:exported="false"  
                android:label="LocationLoggerServiceManager">  
                <intent-filter>  
                    <action  
                        android:name="android.intent.action.BOOT_COMPLETED" />  
                </intent-filter>  
     </receiver>  
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  

 



 

点赞