gpt4 book ai didi

java - 自运行服务中的 Toast

转载 作者:行者123 更新时间:2023-12-02 00:37:43 25 4
gpt4 key购买 nike

我有一个运行远程服务然后退出的 Android Activity 。服务本身轮询设备节点并检查更改,我想用 toast 来提醒用户,但我没能让它工作。 Toast 没有显示,过了一会儿,Android 喊道我的应用程序没有响应。顺便说一句,我不想​​再次启动 Activity 并从那里显示 toast,我只是希望它弹出在向用户显示的当前屏幕上。

这是服务代码:

public class MainService extends Service {

// Native methods
public native static int GetWiegandCode();
public native static void openWiegand();
public native static void closeWiegand();

static int code = 0;

// Other
private static final String TAG = MainService.class.getSimpleName();
private Handler handler;

@Override
public IBinder onBind(Intent intent) {
return null;
}

public void run() {
Handler h;
while (true) {
code = GetWiegandCode();
if (code > 0) {
h = new Handler(this.getMainLooper());
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(),
"ID " + Integer.toString(code) +
"Just entered", Toast.LENGTH_LONG).show();
}
});
}
}
}

@Override
public void onCreate() {
super.onCreate();
openWiegand();
Log.i(TAG, "Service Starting");
this.run();
}

@Override
public void onDestroy() {
super.onDestroy();
closeWiegand();
Log.i(TAG, "Service destroying");
}

static {
System.loadLibrary("wiegand-toast");
}
}

最佳答案

您无法从服务调用 Toast 消息。除了 UI 线程之外,您无法对 UI 执行任何操作。您将需要研究从您的服务与 UI 线程进行通信的多种方法之一 - BroadcastReciever、Messenger、AIDL 等。

对于您想要做的事情,您可能不需要走那么远的 AIDL 路线。查看此 Messenger 实现示例,然后查看 sdk-samples 中的完整示例:

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html

关于java - 自运行服务中的 Toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7298083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com