我有啓動一個IntentService
的活性:如何將活動中的消息發送到服務並在服務運行時執行它們?
intent = new Intent(MyApplication.getAppContext(), MyService.class);
intent.putExtra("EXTRA_DEVICE_ADDRESS", value);
MyApplication.getAppContext().startService(intent);
的服務啓動與I發送的MAC地址的藍牙連接。
device = mBluetoothAdapter.getRemoteDevice(macAddress);
public ConnectThread(BluetoothDevice device) {
this.mmDevice = device;
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(SPP_UUID));
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
}
我聽:
while (true) {
try {
if (mmInStream.available() != 0) {
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
sendMessageToActivity("incoming", readMessage);
} else {
SystemClock.sleep(100);
}
和發送接收到的消息回活動:
public void sendMessageToActivity(String type, String message) {
intent = new Intent(BROADCAST_ACTION);
intent.putExtra(type, message);
sendBroadcast(intent);
}
我用BroadcastReceiver
從服務接收消息:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
我從活動調用(問題的部分):
private void writeOut(final String message) {
msg = message;
byte[] send = msg.getBytes();
MyService.write(send);
}
這是該服務的靜態write()
方法:
public static void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (obj) {
if (mState != STATE_CONNECTED)
return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);`
}
我的問題:以上所有作品作爲意圖除了MyService.write(send)
。 UI卡住了。我試圖使用AsyncTask
,但沒有奏效。我想我需要停止使用該靜態方法並將消息發送到服務並讓他完成這項工作。我相信我需要在活動中初始化一個Handler
,並通過startService()
將其發送給服務。
我想跟蹤進出服務的消息。它與傳入的消息正常工作。我需要找出一種方法來正確接收來自活動的消息,執行它們,然後將信息發送回活動。
是我的問題複雜嗎? – wervdon 2013-03-12 11:23:04
你需要A /不要因爲你的第一個問題在20小時後沒有回答而提出第二個問題。 B /閱讀關於http://developer.android.com/guide/components/bound-services.html C/define「在AsyncTask的上下文中不起作用」,並詳細說明你如何嘗試。 D /考慮廣播和接收器。 – njzk2 2013-03-13 09:11:16