java–Android在服务类中创建新线程

java–Android在服务类中创建新线程,第1张

概述我创建了一个服务类,现在我试图在这个类中运行一个新线程.服务在我的MainActivity中启动,这很有效.onCreate()部分中的第一个Toast.Message显示,但我的线程runa()中的消息没有出现.认为它应该与新的Runnable()一起使用.publicclassMyServiceextendsService{privates

我创建了一个服务类,现在我试图在这个类中运行一个新线程.服务在我的MainActivity中启动,这很有效. onCreate()部分中的第一个Toast.Message显示,但我的线程runa()中的消息没有出现.认为它应该与新的Runnable()一起使用.

public class My Service extends Service {    private static final String TAG = "MyService";    Thread readthread;    @OverrIDe    public IBinder onBind(Intent intent) {        return null;    }    @OverrIDe    public voID onCreate() {        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); //is shown        readthread = new Thread(new Runnable() { public voID run() { try {            runa();        } catch (Exception e) {             //Todo auto-generated catch block            e.printstacktrace();        } } });        readthread.start();         Log.d(TAG, "onCreate");    }    @OverrIDe    public voID onDestroy() {        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();        Log.d(TAG, "onDestroy");    }    @OverrIDe    public voID onStart(Intent intent, int startID) {        //Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();        //Log.d(TAG, "onStart");    }    public voID runa() throws Exception{        Toast.makeText(this, "test", Toast.LENGTH_LONG).show(); //doesn't show up    }}

如果有人能帮助我会很好:)

@R_404_6120@:

您正在创建的线程将不会在MainThread上执行,因此您无法从中显示Toast.要从后台线程显示Toast,您必须使用Handler,并使用该Handler显示Toast.

private MyService extends Service {    Handler mHandler=new Handler();    //...    public voID runa() throws Exception{        mHandler.post(new Runnable(){            public voID run(){                Toast.makeText(MyService.this, "test", Toast.LENGTH_LONG).show()            }        }    }    }

这将是您确切问题的解决方案,虽然我认为它不是一个好的“架构”或实践,因为我不知道您想要实现什么.

总结

以上是内存溢出为你收集整理的java – Android在服务类中创建新线程全部内容,希望文章能够帮你解决java – Android在服务类中创建新线程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1106603.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存