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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16459860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:00:19  来源:igfitidea点击:

Android create new thread in service class

javaandroidmultithreadingclassservice

提问by user2295158

I created a service class and now I'am trying to run a new thread in this class. Service is started in my MainActivityand this works well. The first Toast.Messagein the onCreate()section shows up, but the message in my thread runa()doesn't come up. Thought that it should work with a new Runnable().

我创建了一个服务类,现在我试图在这个类中运行一个新线程。服务在 my 中启动,MainActivity并且效果很好。该部分Toast.Message中的onCreate()第一个出现了,但我的线程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

    }
}

Would be nice if anyone could help me:)

如果有人可以帮助我,那就太好了:)

回答by Ovidiu Latcu

The Threadthat you are creating, will not be executed on the MainThread, thus you can not show a Toastfrom it. To display a Toastfrom a background Threadyou will have to use a Handler, and use that Handlerto display the Toast.

Thread要创建的,会不会在执行MainThread,所以你不能表现出Toast如此。要从Toast背景中显示 a ,Thread您必须使用 a 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()
            }
        }
    }    
}

This would be the solution for your exact problem, although I don't consider it a good 'architecture' or practice as I don't know exactly what you want to achieve.

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

回答by Anup Cowkur

You cannot show Toasts from non-UI threads. Your Service is running on the main thread but you are running your runa()method in a background thread. You have to use a handler and ask it to display the toast on the UI thread. See this answerto find out how this is done.

您不能从非 UI 线程显示 Toast。您的服务在主线程上运行,但您runa()在后台线程中运行您的方法。您必须使用处理程序并要求它在 UI 线程上显示 Toast。请参阅此答案以了解这是如何完成的。

回答by Victor Ruiz.

The best way to update the UI from a Thread, is using a handler or UIThread

从线程更新 UI 的最佳方法是使用处理程序或 UIThread

Try this code:and not forget to put the service into the Manifestfile first.

试试这个代码:不要忘记先把服务放入Manifest文件中。

class CapturingSerivce extends Service {
 Handler mHandler=new Handler();

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

 public void runa() throws Exception{
        mHandler.post(new Runnable(){
            public void run(){

            }
        });
    }    


@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return super.onStartCommand(intent, flags, startId);
  }
}