1 toast在子线程中无法直接显示
2 在service中进行显示的时候会报已经存在looper的错误
所以对toast进行了下面的封装
public class ToastUtil {
private static final String TAG = "ToastUtil";
public static void customerToastShort(String msg){
if(!isMainThread()){
Looper.prepare();
showShortToast(msg);
Looper.loop();
}else {
showShortToast(msg);
}
}
private static void showShortToast(String msg) {
Toast toast = Toast.makeText(ThinkDriveApplication.getContext(),
msg, Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.CENTER, 50, 50);
toast.getView().setPadding(15, 15, 15, 15);
toast.getView().setBackgroundColor(Color.DKGRAY);
TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
text.setTextColor(Color.WHITE);
// text.setTextSize(14);
toast.show();
}
public static void customerToastLong(String msg){
if(!isMainThread()){
Looper.prepare();
showToastLong(msg);
Looper.loop();
}else {
showShortToast(msg);
}
}
private static void showToastLong(String msg) {
Toast toast = Toast.makeText(ThinkDriveApplication.getContext(),
msg, Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 50, 50);
toast.getView().setPadding(15, 15, 15, 15);
toast.getView().setBackgroundColor(Color.DKGRAY);
TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
text.setTextColor(Color.WHITE);
// text.setTextSize(14);
toast.show();
}
public static boolean isMainThread() {
return Looper.getMainLooper() == Looper.myLooper();
}
}
在service中显示toast,放入子线程中,或者写作这个方法里面
private void test(String msg){
Handler handler = new Handler(getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
ToastUtil.customerToastShort(msg);
}
});
}