android - calling ui thread from worker thread

后端 未结 7 2089
再見小時候
再見小時候 2020-12-11 00:12

Hi I want to make Toast available to me no-matter-what and available from any thread whenever I like within my application. So to do this I extended the A

相关标签:
7条回答
  • 2020-12-11 00:53

    If it's within your own activity, why can't you just call doToast()?

    0 讨论(0)
  • 2020-12-11 01:00

    use below code. create activity object which contains your activity instance..

    activity.runOnUiThread(new Runnable() {
      public void run() {
        Toast.makeText(activity.getApplicationContext(),"Toast text",Toast.LENGTH_SHORT).show();
      }
    );
    
    0 讨论(0)
  • 2020-12-11 01:01

    if you have the context with you, you can call the ui thread like this from non activity class.

    ((Activity)context).runOnUiThread(new Runnable() {
        public void run() {
            // things need to work on ui thread
        }
    });
    
    0 讨论(0)
  • 2020-12-11 01:11

    Why don't you send an intent that is captured by a BroadCastReceiver, then the broadcast receiver can create a notification in the notification tray. It's not a toast, but its a way to inform the user that his post has been successful.

    0 讨论(0)
  • 2020-12-11 01:13

    You can't just cast the result of getThread() to an instance of your MyActivity base class. getThread() returns a Thread which has nothing to do with Activity.

    There's no great -- read: clean -- way of doing what you want to do. At some point, your "worker thread" abstraction will have to have a reference to something that can create a Toast for you. Saving off some static variable containing a reference to your Activity subclass simply to be able to shortcut Toast creation is a recipe for memory leaks and pain.

    0 讨论(0)
  • 2020-12-11 01:14

    This will allow you to display the message without needing to rely on the context to launch the toast, only to reference when displaying the message itself.

    runOnUiThread was not working from an OpenGL View thread and this was the solution. Hope it helps.

    private Handler handler = new Handler();
    handler.post(new Runnable() {
        public void run() {
            Toast.makeText(activity, "Hello, world!", Toast.LENGTH_SHORT).show();
        }
    });
    
    0 讨论(0)
提交回复
热议问题