Android開發中一些直接拿來用的代碼片段

分類:編程 時間:2017-03-03

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 datahttp://www.xuebuyuan.com/= "";
		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 = http://www.xuebuyuan.com/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");
	}


Tags: Android activity private public return

文章來源:


ads
ads

相關文章
ads

相關文章

ad