实现原理
Android系统启动时会发送一个ACTION_BOOT_COMPLETED的广播,android.intent.action.BOOT_COMPLETED
代码
新建一个空项目
package com.example.autorun; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hello Android"); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
新建一个类,从BroadcastReceiver继承
package com.example.autorun; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class AutoRun extends BroadcastReceiver { private final String ACTION = "android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION)) ; { Intent in = new Intent(context, MainActivity.class); in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //或者用in.setFlags,暂时不知道有什么区别 context.startActivity(in); } } }
配置文件:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 向系统注册receiver --> <receiver android:name="com.example.autorun.AutoRun" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application>