Thursday, June 4, 2015

Android: Update GUI field vlaue/display or show a message (toast) from Thread

Util Class


package com.pkm.android.utils.thread;

import android.app.Activity;
import android.content.Context;
import android.widget.Toast;

public class ThreadUtils {
    public static Object context = null;
    private static Activity activity;
 
    /**
     * setCurrentActivity(this) in onStart()  on each activity 
     * setCurrentActivity(this) in onResume()  on each activity
     * setCurrentActivity(null) in onPause()  on each activity 
     */
    public static void setCurrentActivity(Activity currentActivity) {
        activity = currentActivity;
    }

    public static Activity currentActivity() {
        return activity;
    }
 
    public static void message(final String message) {
        activity.runOnUiThread(new Runnable() {
            public void run() {
             Toast.makeText((Context) context, message, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Example Usage


@Override
protected void onStart() {
    super.onStart();
    ThreadUtils.setCurrentActivity(this);
    ThreadUtils.context = getBaseContext();
}

ThreadUtils.message("A message from thread, will normally fail!!!");

No comments:

Post a Comment