在非活动类的静态方法中启动Toast

时间:2014-08-27 15:05:19

标签: java android static toast android-looper

我想在非Activity类的静态方法中启动toast消息。 我读了很多关于这一点的帖子,但我的情况有点复杂,特别是:

我有一个服务,在OnStartCommand中我用固定间隔调用另一个类的静态方法,在这个被调用的方法中我想在某些特定情况下显示一个toast消息。

我还尝试创建一个扩展Application的支持类,其中我有应用程序上下文,以便在需要时获取,但无需执行任何操作。

这是Service类中调用静态方法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...

在OracoloBrain类(非活动类)中,我有静态方法AllInterfacesActived。 我省略了有关此方法的代码,但在特定情况下,我想显示Toast。 我尝试创建另一个名为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;
}
}

所以我尝试使用这个上下文启动吐司,但无所事事。

3 个答案:

答案 0 :(得分:1)

您可以在主线程上创建一个处理程序对象,然后您可以稍后使用它来显示您的祝酒词。以下是一个可以帮助您的示例代码。

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();
            }
        });

    }

}

您可以阅读有关处理程序的更多信息,以了解我在除主线程之外的其他线程上显示Toast所做的工作。

答案 1 :(得分:0)

您可以向您的班级发送申请上下文:

在您的非活动课程中:

private static Context c;

public static Context getAndSetMyContext(Context c) {
this.c = c;
}
之后你可以:

Toast.makeText (c, "YOUR TEXT", Toast.LENGTH_LONG).show();

在您的活动课程中:

YourClass.getAndSetMyContext(getBaseContext());

答案 2 :(得分:0)

您的超级服务是什么?如果它的IntentService没有显示Toast,因为你没有在主UI线程上发布它。你必须这样做:

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable { 
    @Override
    public void run() {
        Toast.makeText(context/*Use app context here from your Application subclass*/, "", Toast.SHORT);
});