我想在非 Activity 类的静态方法中启动 toast 消息。我读了很多关于这个的帖子,但我的情况有点复杂,特别是:
我有一个服务,在 OnStartCommand 中我以固定间隔调用另一个类的静态方法,在这个被调用的方法中,我想在某些特定情况下显示一个 toast 消息。
我还尝试创建一个扩展 Application 的支持类,在该类中,我需要在需要时获取应用程序上下文,但无事可做。
这是调用静态方法 AllInterfacesActived 的 Service 类中的方法:
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;
}
}
因此,我尝试使用此上下文启动 toast,但无事可做。