我有一个应用程序,在主要活动中用户选择一个蓝牙设备并且该应用程序连接到该应用程序。然后启动一个新的活动,用户可以选择不同的活动(有不同的方式与蓝牙设备进行交互)。最后,选定的活动启动并且用户很高兴。Android:在丢失的蓝牙连接上完成多项活动
我的问题是,当连接丢失,我应该完成的活动列表活动和互动活动莫名其妙......但如何?我听说Intents会在活动和广播之间传递消息,甚至是Helpers,但没有关于如何将正在运行的线程的信息传递给多个其他活动的示例。
不同的连接线程(我从BluetoothChat示例中借用的)位于Application类中,因此我可以从任何活动访问写入功能。这也是我检测丢失的连接的地方。
下面是从我的应用程序相关代码:
应用程序类:
public class BluetoothRemoteControlApp extends Application {
public final int BT_CONNECTION_LOST = 1;
// . . .
private class ConnectedThread extends Thread {
// . . .
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(0, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
// the lost connection is detected here
connectionLost();
break;
}
}
}
// . . .
}
private void connectionLost() {
Log.e("BT", "Connection lost");
// inform that connection was lost,
// finish all activities and (re)start device select activity again
}
}
,其中不同活动(称为 “动作”)提出的活动:
public class ActionListActivity extends ListActivity {
ArrayList<Action> activityList = new ArrayList<Action>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// list of available activities, arguments: title, description and class name
activityList.add(new Action("Accelerometer Control", "Control your robot by tilting the phone", "AccelerometerControl"));
// . . .
setListAdapter(new ActionListBaseAdapter(this, activityList));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String activity = activityList.get(position).getClassName();
try {
Class<?> activityClass = Class.forName("com.bluetooth.activities." + activity);
Intent intent = new Intent(ActionListActivity.this, activityClass);
startActivity(intent);
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
// add a method here to finish the activity when connection is lost
}
假设我启动我的AccelerometerControl活动,在connectionLost()
中发送什么信息给ActionListActivity()
和AccelerometerControl()
,以便他们完成?
我不认为我可以这样做,因为我想从Application类完成活动,'finishActivity()'在扩展'Application'时不可用。 – Solenoid 2012-08-15 09:29:57
检查编辑。 – nandeesh 2012-08-15 09:45:15
非常好,现在我更了解Handlers。 – Solenoid 2012-08-15 12:16:13