在Android Service组件里面弹出Toast

方法一:常用方法

原理:其原理是通过Handler将一个自定义的线程运行于主线程之上

/**
     * 在Service里面弹出Toast
     * 
     * @param txt 需要显示的文字
     */
    public void showToast(final String txt) {
        if (txt == null) {
            Log.e(TAG, "call method showToast, text is null.");
            return;
        }

        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(DeviceServiceEngineImpl.this, txt, Toast.LENGTH_LONG)
                        .show();
            }
        });
    }

方法二:app中没有activity的时候的方法

  1. 启动一个透明的Activity,onCreate方法中显示tost,然后定时finish。
  2. 使用WindowManager来显示一个view,然后定时移除

先new一个TextView,给它设置背景与颜色、字号,使之符合你想要的toast,然后设置好LayoutParams,把textView add到windowmanager上,然后定时移除。

private void showToast(Context context){
        final WindowManager wManager=(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        final TextView textView=new TextView(context);
        textView.setBackgroundResource(R.drawable.shape_bg_ball);
        textView.setText(context.getString(R.string.toClipboard));
        textView.setPadding(dp2Px(10,context),dp2Px(5,context),dp2Px(10,context),dp2Px(5,context));
        int screenHeigth = wManager.getDefaultDisplay().getHeight();
 
        int mStatusBarHeight = dp2Px(25, context);
 
        WindowManager.LayoutParams mParamsToast = new WindowManager.LayoutParams();
 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT > 23) {
                    //在android7.1以上系统需要使用TYPE_PHONE类型 配合运行时权限
                mParamsToast.type = WindowManager.LayoutParams.TYPE_PHONE;
            } else {
                mParamsToast.type = WindowManager.LayoutParams.TYPE_TOAST;
            }
        } else {
            mParamsToast.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        
        mParamsToast.format = PixelFormat.RGBA_8888;
        mParamsToast.gravity = Gravity.LEFT | Gravity.TOP;
        mParamsToast.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        int defaultY =screenHeigth- ((screenHeigth - mStatusBarHeight) / 2) / 3;
        mParamsToast.x = wManager.getDefaultDisplay().getWidth()/2- Tools.getViewWidth(textView)/2;
 
        mParamsToast.y = defaultY;
        mParamsToast.alpha = 1;
        mParamsToast.width = WindowManager.LayoutParams.WRAP_CONTENT;
        mParamsToast.height = WindowManager.LayoutParams.WRAP_CONTENT;
 
        wManager.addView(textView, mParamsToast);
        new Handler().postDelayed(()->
                wManager.removeViewImmediate(textView),500);
    }

 

你可能感兴趣的:(Android高级进阶)