I write a ToastUtils
to avoid duplicate toast:
public class ToastUtils {
private ToastUtils() {
//no instance
}
private static Toast toast = null;
public static void showToast(String message) {
if (toast == null) {
toast = Toast.makeText(Utils.getApp(), message, Toast.LENGTH_SHORT);
}
toast.setText(message);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
public static void showToast(@StringRes int messageId) {
if (toast == null) {
toast = Toast.makeText(Utils.getApp(), messageId, Toast.LENGTH_SHORT);
}
toast.setText(messageId);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
}
Utils.java
is the following:
public class Utils {
private Utils() {
//no instance
}
/**
* 提供统一的 Context 接口给其他工具类
*
* @return Context 对象
*/
public static Context getApp() {
return App.getApplication();
}
}
App.java
is my custom Application
:
public class App extends Application {
private static App application;
@Override
public void onCreate() {
super.onCreate();
application = this;
String curProcessName = getCurProcessName();
if (!TextUtils.equals(curProcessName, getPackageName())) {
return;
}
// omit my business code...
}
public static App getApplication() {
return application;
}
private String getCurProcessName() {
int pid = android.os.Process.myPid();
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
if (am == null || am.getRunningAppProcesses() == null || am.getRunningAppProcesses().isEmpty()) {
return null;
}
for (ActivityManager.RunningAppProcessInfo appProcess : am.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
}
What makes me frustrated is ToastUtils
doesn't work sometimes, ie, I cannot see toast message show on the screen.