Android开发中一些直接拿来用的代码片段

1.再按一次退出程序:

private long exitTime = 0;
@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), "再按一次退出程序",
						Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

2.webview的activity中按返回键返回到上次浏览的页面:

@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (webview.canGoBack()) {
				webview.goBack();
			} else {
				this.finish();
			}
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

3.判断终端是否联网:

public static boolean canConnect(Context context){
		ConnectivityManager cManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cManager.getActiveNetworkInfo();
		  if (info != null && info.isAvailable()){
		       //能联网
		        return true;
		  }else{
		       //不能联网
		        return false;
		  } 
	}
4.通过访问的接口以及传入的键值对得到服务器返回的数据:

public static String getData(String url, List<NameValuePair> nameValuePairs) throws JSONException {
		if (nameValuePairs == null) {
			nameValuePairs = new ArrayList<NameValuePair>();
		}
		String data = "";
		StringBuffer stringBuffer = new StringBuffer();
		try {
			HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairs,
					"utf-8");
			System.out.println("访问的接口是: ----》" + url);
			HttpPost post = new HttpPost(url);
			post.setEntity(httpEntity);
			System.out.println("HttpEntity is : "
					+ new BufferedReader(new InputStreamReader(httpEntity
							.getContent())).readLine());
			HttpClient client = getHttpClient();
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				String line;
				while ((line = reader.readLine()) != null) {
					stringBuffer.append(line);
				}
			} else
				return null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ConnectTimeoutException e) {
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		data = stringBuffer.toString();
		return parseData(data);
	}

	private static HttpClient getHttpClient() {
		HttpClient client = new DefaultHttpClient();
		client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,
				20000); // 超时设置
		client.getParams().setIntParameter(
				HttpConnectionParams.CONNECTION_TIMEOUT, 20000);// 连接超时
		return client;
	}

4.通过Url得到数据:

/**
	 * @param url
	 * @throws IOException 
	 */
	public static String getDataFromUrl(String url) throws IOException {
		String result = "";
		URL uri = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		if(conn.getResponseCode() == 200){
			String encode = conn.getContentEncoding();
			InputStream in = conn.getInputStream();
			result = getStrFromInput(in, encode);
		}
		return result;
	}

	

5.通过输入流得到String

/**
	 * @param in
	 * @param encode 
	 * @return
	 * @throws IOException 
	 */
	private static String getStrFromInput(InputStream in, String encode) throws IOException {
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		byte[] buffer = new byte[1024];
		
		int len = 0;
		
		while((len = in.read(buffer)) != -1){
			out.write(buffer, 0, len);
		}
		out.flush();
		out.close();
		return new String(out.toByteArray(), "UTF-8");
	}















你可能感兴趣的:(android,代码片段,直接用)