经常会有这样的需求,当手机开机后立刻启动一个服务或者一个活动。
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class AutoStartReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("AS", "开机自启动广播接收器[AutoStartReceiver]"); //启动活动 Intent bootIntent = new Intent(context, AutoStartActivity.class); bootIntent.setAction("android.intent.action.MAIN"); bootIntent.addCategory("android.intent.category.LAUNCHER"); bootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(bootIntent); //启动服务 context.startService(new Intent(context, AutoStartService.class)); } }
import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class AutoStartService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("AS", "开机自启动服务[AutoStartService]"); return 0; } @Override public IBinder onBind(Intent arg0) { return null; } }
import android.app.Activity; import android.os.Bundle; import android.util.Log; /** * 每次开机时都会显示此活动 * @author Davee */ public class AutoStartActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { Log.i("AS", "开机自启动活动[AutoStartActivity]"); super.onCreate(savedInstanceState); setContentView(R.layout.aotu_start); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="开机自启动的Activity" /> </LinearLayout>
添加权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
添加配置
<activity android:name=".AutoStartActivity" /> <service android:name=".AutoStartService" /> <receiver android:name=".AutoStartReceiver" > <intent-filter> <!-- 接受系统开机广播 --> <action android:name="android.intent.action.BOOT_COMPLETED"/> <category android:name="android.intent.category.HOME" /> </intent-filter> </receiver>