android開機自啟動
原理,在收到系統開機廣播後,啟動一個透明的activity,在activity裡面啟動一個服務。
關鍵代碼如下:
1、開機廣播接受者
public class BootReceiver extends BroadcastReceiver {public void onReceive(Context context, Intent intent) {if (intent.getAction().equals(android.intent.action.BOOT_COMPLETED)) {Log.d(BootReceiver, system boot completed);// context, AutoRun.classIntent newIntent = new Intent(context, AutoRun.class);/* MyActivity action defined in AndroidManifest.xml */newIntent.setAction(android.intent.action.MAIN);/* MyActivity category defined in AndroidManifest.xml */newIntent.addCategory(android.intent.category.LAUNCHER);/* * If activity is not launched in Activity environment, this flag is * mandatory to set */newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);/* if you want to start a service, follow below method */context.startActivity(newIntent);}}}
2、開機啟動的activty透明
3、
public class AutoRun extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); //去除title requestWindowFeature(Window.FEATURE_NO_TITLE); //去掉Activity上面的狀態列 getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams.FLAG_FULLSCREEN);setContentView(R.layout.main);Log.i(開機啟動,開機啟動);startService(new Intent(this,EndClientService.class));finish();}}
3、開機啟動的服務
public class EndClientService extends Service {private Intent intent2=null;public EndClientService() {// TODO Auto-generated constructor stub}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Log.i(開機服務,服務開啟);IntentFilter filter=new IntentFilter();filter.addAction(android.provider.Telephony.SMS_RECEIVED);filter.setPriority(Integer.MAX_VALUE);registerReceiver(mReceiver, filter);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i(服務,服務運行中);return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();unregisterReceiver(mReceiver);mReceiver=null;}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}