如果没有正在运行的活动,如何从线程发出Toast消息?
我启动了应用程序,为后台套接字侦听创建了一个新线程,然后退出了应用程序。但是,该线程然后仍监听传入的套接字请求。
我从这个例子开始:BluetoothChat 在这个地方的某个地方(BluetoothChatService.java行:来自类&#34的243;私有类AcceptThread扩展Thread")我开始吐司:
public void run() {
if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
setName("AcceptThread");
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "accept() failed", e);
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothChatService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
答案 0 :(得分:1)
如果在初始化课程时可以将引用传递给Activity
,则可以使用runOnUiThread()
。例如,
全球指针......
Activity mActivity;
你的构造函数......
public MyClass(Activity activity) {
mActivity = activity;
}
MyClass
内显示祝酒词的方法......
public void showToast(String message, int duration) {
mActivity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mActivity, message, duration);
}
}
}
然后随时调用该方法。