Android Toast Create showToast(final String toast, final Context context)

Here you can find the source of showToast(final String toast, final Context context)

Description

show Toast

Declaration

public static void showToast(final String toast, final Context context) 

Method Source Code

//package com.java2s;
import java.util.List;

import android.app.ActivityManager;

import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;

import android.os.Looper;

import android.widget.Toast;

public class Main {
    public static void showToast(final String toast, final Context context) {
        if (!isAppOnForeground(context))
            return;
        new Thread(new Runnable() {

            @Override/*from ww  w .ja  v  a 2 s. com*/
            public void run() {
                Looper.prepare();
                Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }).start();
    }

    public static boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        // Returns a list of application processes that are running on the device 
        List<RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (RunningAppProcessInfo appProcess : appProcesses) {
            // importance: 
            // The relative importance level that the system places  
            // on this process. 
            // May be one of IMPORTANCE_FOREGROUND, IMPORTANCE_VISIBLE,  
            // IMPORTANCE_SERVICE, IMPORTANCE_BACKGROUND, or IMPORTANCE_EMPTY. 
            // These constants are numbered so that "more important" values are 
            // always smaller than "less important" values. 
            // processName: 
            // The name of the process that this object is associated with. 
            if (appProcess.processName.equals(context.getPackageName())
                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }
}

Related

  1. showToast(final Context context, final String message)
  2. showToast(final Context context, final String string)
  3. showToast(final Context context, final int resId)
  4. showToast(final Context ctx, final Handler handler, final String text, final int duration)
  5. showToast(final Context ctx, final Handler handler, final int id, final int duration)
  6. showToast(final String toast, final Context context)
  7. showToastInThread(final Context context, final String msg)
  8. toast(String message, Context context)
  9. toast(final Context context, final CharSequence msg)