Search code examples
javaandroidstatictoastandroid-looper

Launch a Toast in a static method of a non-activity class


I want to launch a toast message in a static method of a non-Activity class. I read a loto of threads about that, but my situation is a bit more complicated, in particular:

I have a service and in OnStartCommand I call with fixed interval a static method of another class, in this called method I want to show in some particular cases a toast message.

I try also to create a support class that extends Application in which I have the application context to get when I need, but nothing to do.

This is the method in the Service class that calls the static method AllInterfacesActived:

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

    //flag variable that indicates if service is scanning
    isScanning = true;

    final int result;

    turnGPSOn();


    /*GET WIFI DATA, we use a thread and with scheduleAtFixedRate we run it repeatedly with the wifi scan interval*/ 
    Wifitimer.scheduleAtFixedRate(new TimerTask() {


        @Override
        public void run() {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());

            //we are in wifi case, we set umts string result to "" because we don't perform a umts scansion
            String resultUMTS = "";

            //call the SCANWIFI METHOD to scan the networks and to obtain their data
            String resultScan = scanWifi();
            Intent mIntent = new Intent();
            mIntent.setAction(INTENT_ACTION);

            //put information on wifi and umts in the intent
            mIntent.putExtra(INTENT_EXTRA_WIFI, "Waiting for umts scansion...\nWIFI SCAN PERFOMED"+resultScan+"\nUMTS\n"+resultUMTS);

            //broadcast of data
            Bundle xtra = new Bundle();
            sendBroadcast(mIntent);

            /*
             * when all interfaces are actived we call AllInterfacesActived() of OracoloBrain.java
             */
            if(getUseOracolo())
                if(isAPNEnabled(getApplicationContext()) && isGpsEnable() && isWifiEnabled()){
                    OracoloBrain.AllInterfacesActived();     
                }


        }
    }, 0,MainActivity.getWifiInterval());

//other code of the onStartCommand method...

In the OracoloBrain class (non activity class) I have the static method AllInterfacesActived. I leave out the code about this method, but in a particular case I want to show a Toast. I try to create a another class called MyApplication.java:

public class MyApplication extends Application {

private static Context context;

public void onCreate(){
    super.onCreate();
    MyApplication.context = getApplicationContext();
}

public static Context getAppContext() {
    return MyApplication.context;
}
}

So I try to launch toast using this context but nothing to do.


Solution

  • You could create a handler object on the main thread and then you could use it later to show your toast. Below is a sample code that will help you out.

    class MyService extends Service{
    Handler handler ;
    onStartCommand(intent int , int flags,int startId){
    handler = new Handler(); // this will get instantiated on the main thread;
    new Thread(new Runnable() {
    
                        @Override
                        public void run() {
                            dispatchMessage("this is a toast");
    
                        }
                    }).start();
    
    
    }
    public void dispatchMessage(final String message) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    System.out.println(message);
                    Toast.makeText(MyService.this, message, Toast.LENGTH_SHORT).show();
                }
            });
    
        }
    
    }
    

    You can read more on Handlers to understand what I have done to show Toast on other threads apart from main thread.