Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

16.5. 动态监听广播

		
	private void broadcast(final long Id) {
 
		// 注册广播监听系统的下载完成事件。
		IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
		broadcastReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
				if (ID == Id) {
					Toast.makeText(getApplicationContext(), "任务:" + Id + " 下载完成!", Toast.LENGTH_LONG).show();
				}
			}
		};
 
		registerReceiver(broadcastReceiver, intentFilter);
	}		
		
		

Kotlin 例子

		
	private val bluetoothBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Log.d(TAG, "bluetoothBroadcastReceiver Action: " + action)
            val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
            when (action) {

                BluetoothDevice.ACTION_ACL_CONNECTED -> {
                    device?.let {
                        Toast.makeText(context, "蓝牙已连接: ${it.name}", Toast.LENGTH_SHORT).show()
                    }
//                    if(会议开始){
                    startMeeting()
//                    }

                    Log.d(TAG, "bluetoothBroadcastReceiver startMeeting")
                }

                BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                    device?.let {
                        Toast.makeText(context, "蓝牙已断开: ${it.name}", Toast.LENGTH_SHORT).show()
                    }
                    closeMeeting()
                    Log.d(TAG, "bluetoothBroadcastReceiver closeMeeting")
                }


//                BluetoothAdapter.ACTION_STATE_CHANGED -> {
//                    val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
//                    when (state) {
//                        BluetoothAdapter.STATE_ON -> {
//                            Log.d(TAG, "蓝牙已开启")
//                            BlueManager.startScan()
//                        }
//
//                        BluetoothAdapter.STATE_OFF -> {
//                            Log.d(TAG, "蓝牙已关闭")
//                        }
//                    }
//                }
            }

        }
    }		
	private fun broadcast() {

 		val filter = IntentFilter()
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        filter.addAction(BluetoothDevice.ACTION_FOUND)
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)
        activity?.registerReceiver(bluetoothBroadcastReceiver, filter)
 
	}