Cam*_*pig 2 multithreading android handler android-bluetooth
好的,我是android的新手,我正在尝试创建一个通过蓝牙与arduino接口的应用程序。我已经看过示例BluetoothChat,并看过它如何使用Handler在“服务”,由它产生的线程和MainActivity之间进行通信。我的问题是我有多个活动需要使用蓝牙服务。对于每个活动,我都有一个像这样的处理程序:
mHandler = new Handler(){
@Override
public void handleMessage(Message message) {
switch (message.what){
case BtService.CHANGE_STATE:
if (message.arg1 == BtService.STATE_CONNECTING){
Intent i = new Intent (MainActivity.this,ConnectedActivity.class);
startActivity(i);
}
break;
}
}
};
Run Code Online (Sandbox Code Playgroud)
在服务构造函数中,我得到了以下信息:
private BtService(){
btm = BluetoothAdapter.getDefaultAdapter();
mHandler= new Handler(Looper.getMainLooper());
}
Run Code Online (Sandbox Code Playgroud)
当我需要发送消息时,请执行以下操作:
private synchronized void setState(int state){
mHandler.obtainMessage(CHANGE_STATE, state, -1).sendToTarget();
mState = state;
}
Run Code Online (Sandbox Code Playgroud)
但是其他各种处理程序中均未接收到消息。在此声明“特定线程的所有Handler对象都接收相同的消息”。所以我不明白这个问题。我是否需要在每次启动活动时将在该活动中声明的处理程序传递给服务以使其接收消息?这似乎可行,但对我而言似乎不是一个好习惯。
如果要在所有应用程序中发送消息,则应使用BroadcastReceiver,这是您的最佳方法。
Intent intent = new Intent(ApplicationConstants.MY_MESSAGE);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)
在任何活动中接收消息(您可以在一个活动中使用此消息)
BroadcastReceiver connectionUpdates = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
...//TODO here
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(
connectionUpdates ,
new IntentFilter(ApplicationConstants.MY_MESSAGE));
Run Code Online (Sandbox Code Playgroud)
希望这对您有所帮助
干杯,
| 归档时间: |
|
| 查看次数: |
3170 次 |
| 最近记录: |