1. 程式人生 > >在service程式碼裡實現廣播接收者

在service程式碼裡實現廣播接收者

service裡:

// 初始化廣播接收器
private MyBroadcastReceiver receviver = null;

private void initBroadcastReceiver() {
	// 建立一個IntentFilter物件,將其action指定為BluetoothDevice.ACTION_FOUND
	IntentFilter intentFilter = new IntentFilter();
	intentFilter.addAction(Constant.RELOAD_DATA);
	intentFilter.addAction(Constant.RELOAD_OPEN_DOORS_DISTANCE);
	receviver = new MyBroadcastReceiver();
	// 註冊廣播接收器
	registerReceiver(receviver, intentFilter);
}

private class MyBroadcastReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action.equals(Constant.RELOAD_DATA)) {
			// 重新載入資料庫
			System.out.println("get RELOAD_DATA");
			getDoorInfFromDB();
			return;
		} else if (action.equals(Constant.RELOAD_OPEN_DOORS_DISTANCE)) {
			// 這裡得到實際距離,要將實際距離進行轉化
			/**
			* 0========-5
			* 10=======-85
			*/
			openDistance = getSharedPreferences(Constant.NAME_CONFIG, Context.MODE_PRIVATE).getInt(Constant.KEY_DOOR_DISTANCE, -85);
			if (openDistance > -50) {
				openDistance = -50;
			}
			return;
		} else if (action.equals(Constant.RELOAD_OPEN_DOORS_DISTANCE_DEF)) {
			SharedPreferences preferences = getSharedPreferences(Constant.NAME_CONFIG, Context.MODE_PRIVATE);
			openDistance = preferences.getInt(Constant.KEY_DOOR_DISTANCE_DEFAULT, -75);
			return;
		}
	}
}

在activity裡:
// 傳送廣播去重新載入資料
broadcastUpdate(Constant.RELOAD_DATA);

private void broadcastUpdate(final String action) {
	final Intent intent = new Intent(action);
	sendBroadcast(intent);
}

在onDestroy方法裡要解除註冊:

if (receviver != null) {
	unregisterReceiver(receviver);
}