private ExecutorService executorService = Executors.newSingleThreadExecutor(); /** * 有超时时间的方法 * @param timeout * @return */ private String timeoutMethod(int timeout) { String result = "默认"; FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() { @Override public String call() throws Exception { return unknowMethod(); } }); executorService.execute(futureTask); try { result = futureTask.get(timeout, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { //e.printStackTrace(); futureTask.cancel(true); result = "默认"; } stringText=result; handler.sendEmptyMessage(0); return result; } /** * 这个方法的耗时不确定 * @return */ private String unknowMethod() { Random random = new Random(); int time = (random.nextInt(10) + 1) * 1000; timeShow=time+""; System.out.println("任务将耗时: " + time + "毫秒"); try { Thread.sleep(time); } catch (Exception e) { // TODO: handle exception } return "获得方法执行后的返回值"; }
private String stringText; private String timeShow; public Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { Toast.makeText(MainActivity.this,"xxxx"+timeShow+":"+stringText+"",Toast.LENGTH_LONG).show(); // finish(); } };