gpt4 book ai didi

android - 为什么我的服务没有运行? (通过显示 Toast 消息来判断。)

转载 作者:搜寻专家 更新时间:2023-11-01 08:13:53 24 4
gpt4 key购买 nike

我正在尝试在后台提供服务,这样我就可以运行一个循环,每 x 分钟请求一个页面。这是我在 list 中的服务:

<service android:name=".webToSMS" android:enabled="true" />

这是我正在启动的服务(在主要 Activity 中):

Intent intent = new Intent(this, webToSMS.class);
startService(intent);

最后,这是我的服务类:

public class webToSMS extends IntentService {

public webToSMS() {
super("webToSMS");
}

@Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}

我在 Android 上遵循指南,这就是它告诉我要做的。我期待的是弹出一个 toast 说“你好 toast !”当此服务运行时。最终,当这可行时,我将放置一个循环,每 x 分钟请求一个页面。

最佳答案

您的服务正在运行,只是不显示 toast,因为您不在 UI 线程上。

如果你想看 toast ,试试这个

Handler HN = new Handler(); 


private class DisplayToast implements Runnable {

String TM = "";

public DisplayToast(String toast){
TM = toast;
}

public void run(){
Toast.makeText(getApplicationContext(), TM, Toast.LENGTH_SHORT).show();
}
}

@Override
protected void onHandleIntent(Intent intent) {

HN.post(new DisplayToast("New Toast on UI Thread"));
}

关于android - 为什么我的服务没有运行? (通过显示 Toast 消息来判断。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6824050/

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