Android: How can i show a toast from a thread running in a remote service?

前端 未结 4 866
囚心锁ツ
囚心锁ツ 2020-12-03 06:07

Android: How can i show a toast from a thread running in a remote service? Whenever i run from a different thread in a service, the app crashes...

public cl         


        
相关标签:
4条回答
  • 2020-12-03 06:12

    Another way to try would be to use an AsyncTask. This Android article is a good one about threading.

    0 讨论(0)
  • 2020-12-03 06:13

    if someone don't understand what context is in @Alex Gitelman answer. write your class name in place of context in which you are writing this handler code like this

    Handler h = new Handler(MyClassName.this.getMainLooper());
    
    h.post(new Runnable() {
        @Override
        public void run() {
             Toast.makeText(MyClassName.this,"show toast message",Toast.LENGTH_LONG).show();
        }
    });
    
    0 讨论(0)
  • 2020-12-03 06:15

    I am not sure but this looks again like trying to invoke GUI methods on non-GUI threads.

    0 讨论(0)
  • 2020-12-03 06:16

    This is how I did it. Of course, you need to pass appropriate context.

       Handler h = new Handler(context.getMainLooper());
    
        h.post(new Runnable() {
            @Override
            public void run() {
                 Toast.makeText(context,message,Toast.LENGTH_LONG).show();
            }
        });
    
    0 讨论(0)
提交回复
热议问题