廣播通知啓動服務

廣播代碼如下:

public class BootBroadcastReceiver extends BroadcastReceiver{

	private String action = "android.intent.action.BOOT_COMPLETED";
	private Context mContext;
	@Override
	public void onReceive(Context context, Intent intent) {
		mContext = context;
		if(intent.getAction().equals(action))
		{
			Log.d("BootBroadcastReceiver", "BroadcastReceiver onReceive  ");
			//在這裏啓動服務
			Intent service = new Intent(context,MyService.class);  
			mContext.startService(service);
			   
		}
		
	}

}

service測試代碼:

public class MyService extends Service {  
	  
    public static final String TAG = "MyService";  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        Log.d(TAG, "onCreate() executed");  
    }  
  
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
        Log.d(TAG, "onStartCommand() executed");  
        return super.onStartCommand(intent, flags, startId);  
    }  
      
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
        Log.d(TAG, "onDestroy() executed");  
    }  
  
    @Override  
    public IBinder onBind(Intent intent) {  
        return null;  
    }  
  
}  

進行簡單配置即完成操作:

<service android:name="MyService"></service>
        
        <receiver android:name="BootBroadcastReceiver">
            <intent-filter> 
                
				<action android:name="android.intent.action.BOOT_COMPLETED"></action>
				<category android:name="android.intent.category.LAUNCHER" />  
			</intent-filter> 
        </receiver>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章