UiAutomator踩坑区域

获取Context:

InstrumentationRegistry.getTargetContext()

弹出Toast:

static Handler mWorkerHandler;

static {
    Thread workerThread = new Thread() {
        @Override
        public void run() {
            super.run();
            //这里是关键,要在线程中弹出Toast,必须加入Looper
            Looper.prepare();
            mWorkerHandler = new Handler();
            Looper.loop();
        }
    };
    workerThread.start();
}

public Context getContext() {
    return InstrumentationRegistry.getTargetContext();
}

/**
 * 显示Toast公开方法
 */
public void showToast(String msg) {
    ShowToastRunnable runnable = new ShowToastRunnable(msg);
    if (mWorkerHandler != null) {
        mWorkerHandler.post(runnable);
    }
}

private class ShowToastRunnable implements Runnable {
    private String msg;

    ShowToastRunnable(String msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }
}

调用:

mLocalUtils.showToast("测试弹出信息");
try {
    //如果APP紧接着结束运行了,需要调用延迟3秒,否则还没弹出,APP就销毁了
    Thread.sleep(3 * 1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

你可能感兴趣的:(UiAutomator踩坑区域)