我有一個應用程序,在主要活動中用戶選擇一個藍牙設備並且該應用程序連接到該應用程序。然後啓動一個新的活動,用戶可以選擇不同的活動(有不同的方式與藍牙設備進行交互)。最後,選定的活動啓動並且用戶很高興。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