android Toast运行在主线程中

Toast运行在主线程中,如果非要在子线程中调用可以用下面的方法 runOnUiThread ( new Runnable () { });
下面是个下载app例子,并在通知栏不断更新下载进度
private File downloadApp(String appurl,String appName){
		File tmpFile = new File(rootDirectry);
		if (!tmpFile.exists()) {
			tmpFile.mkdir();
		}
		final File file = new File(rootDirectry + "/" + appName+".apk");
		Log.e(THSI_FIEL, "fileName:"+rootDirectry);
		try {
			URL url = new URL(appurl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			InputStream inputStream = connection.getInputStream();
			int size = connection.getContentLength();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			connection.connect();
			Long starttime = System.currentTimeMillis();
			int saveLenght = 0;
			while (true) {
				if (inputStream != null) {
					int numRead = inputStream.read(buffer);
					if (numRead <= 0) {
						break;
					} else {
						fos.write(buffer, 0, numRead);
						Long stoptime = System.currentTimeMillis();
						Long time = (stoptime - starttime) / 1000;
						if (time != 0) {
							Message msg = new Message();
							int baifenbi = (int) (file.length() * 100 / size);
							if(baifenbi > saveLenght){//避免信息发送的过快
								saveLenght=baifenbi;
								msg.arg1 = baifenbi;
								msg.what = UPDATE;
								mHandler.sendMessage(msg);
//								timer.schedule(task, 1000, 2000); // 1s后执行task,经过1s再次执行
							}
						}
					}
				}
			}
			if(connection != null){
				connection.disconnect();
			}
			if(fos != null){
				fos.close();
			}
			if(inputStream != null){
				inputStream.close();
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			((Activity)context).runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(context, "下载应用异常...", Toast.LENGTH_SHORT).show();
				}
			});
			e.printStackTrace();
		}
		return file;
		
	}


你可能感兴趣的:(android Toast运行在主线程中)