Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android開機自啟動

android開機自啟動

編輯:關於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.class
			Intent 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. */
	@Override
	public 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
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.i(開機服務,服務開啟);
		IntentFilter filter=new IntentFilter();
		filter.addAction(android.provider.Telephony.SMS_RECEIVED);
		filter.setPriority(Integer.MAX_VALUE);
		registerReceiver(mReceiver, filter);
		
		
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(服務,服務運行中);
		return super.onStartCommand(intent, flags, startId);
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mReceiver);
		mReceiver=null;
	}
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

 

 

 

 


            
                

                
            
        



 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved