Android开发总结

最近在整理新人配置知识,整理一些实用的,能让新人快速上手的开发知识,先让新人能看到效果,在深入研究具体的细节,让开发有个整体的思路及流程,不然开发干讲理论,很难让新人上手,所以我对主要的关键点进行整理,通过以下的生产方法,很容易也很好理解的快速上手。今天主要整理了严苛模式,网络判断,调用后台服务,Activity间参数传递及Activity声明周期管理。稍后会更新后续知识。

1.StrictMode,严苛模式.这个是必须的,我们需要在onCreate方法中声明

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
				.build());
2.我们目前的开发都是基于网络的,所以网络是否连接必须进行判断,来区分处理需要网络和不需要网络的服务,并且对使用网络做wifi及移动网的判断。

public boolean isWifiConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mWiFiNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (mWiFiNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
				return mWiFiNetworkInfo.isAvailable();
			}
		}
		return false;
	}

public boolean isMobileConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mMobileNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (mMobileNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
				return mMobileNetworkInfo.isAvailable();
			}
		}
		return false;
	}
boolean mobile_net = isNetworkConnected(getApplicationContext());
					boolean wifi_net = isWifiConnected(getApplicationContext());

					if (wifi_net) {
						httpConnect(inner_ip, num);
					} else {
						if (mobile_net) {
							httpConnect(outter_ip, num);
						} else {
							Toast.makeText(getApplicationContext(),
									"请保持网络连接畅通后重试!", Toast.LENGTH_SHORT).show();
						}

					}
3.调用后端服务,我们现在服务一般都是有专门的后台,所以我们需要进行调用,调用restful服务,我们使用httpclient进行调用。这里有个说明,我们一般是通过Bundle进行数据的传递接收,如果参数较少的时候可以直接使用Intent。这里我们解析json引用了json-lib

	public void httpConnect(String ip_address, String num) {
		String baseUrl = "http://" + ip_address
				+ ":port/appNmae/ServiceName?param=" + num;
		HttpGet getMethod = new HttpGet(baseUrl);
		HttpClient httpClient = new DefaultHttpClient();
		try {
			HttpResponse response = httpClient.execute(getMethod);
			if (response.getStatusLine().getStatusCode() == 200) {
				int state = response.getStatusLine().getStatusCode();
				System.out.println(state);
				String result = EntityUtils.toString(response.getEntity());
				JSONTokener jsonParser = new JSONTokener(result);
				JSONObject permanent = (JSONObject) jsonParser.nextValue();
				JSONObject per_obj = permanent.getJSONObject("obj");
				Bundle bundle = new Bundle();
				bundle.putString("permanent_num",
						per_obj.getString("permanent_num"));
				bundle.putString("permanent_user",
						per_obj.getString("permanent_user"));
				bundle.putString("org_unit", per_obj.getString("org_unit"));
				bundle.putString("ip_address", per_obj.getString("ip_address"));
				Intent intent = new Intent(MainActivity.this,
						MainActivity2.class);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
4.Activity间调用返回值

	private static final int REQUEST_CODE_KEY = 0x0000;
        Intent intent = new Intent(MainActivity.this,CaptureActivity.class);
     startActivityForResult(intent, REQUEST_CODE_KEY);
        @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_KEY && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                aa.setText(content);
                bb.setImageBitmap(bitmap);
            }
        }
    }
5.Activity接收Intent传递的值

Bundle bundle = this.getIntent().getExtras();
textView6.setText(bundle.getString("permanent_num"));
textView7.setText(bundle.getString("permanent_user"));
textView8.setText(bundle.getString("org_unit"));
textView9.setText(bundle.getString("ip_address"));
button = (Button) findViewById(R.id.button1);
6.Activity声明周期管理

import java.util.Stack;

import android.app.Activity;
import android.app.Application;

public class MyApplication extends Application {
	private static Stack<Activity> activityStack;
	private static MyApplication singleton;

	@Override
	public void onCreate() {
		super.onCreate();
		singleton = this;
	}

	/**
	 * Returns the application instance
	 */
	public static MyApplication getInstance() {
		return singleton;
	}

	/**
	 * add Activity
	 */
	public void addActivity(Activity activity) {
		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	/**
	 * close last in stack Activity is current Activity
	 */
	public void finishActivity() {
		Activity activity = activityStack.lastElement();
		finishActivity(activity);
	}

	/**
	 * close Activity
	 */
	public void finishActivity(Activity activity) {
		if (activity != null) {
			activityStack.remove(activity);
			activity.finish();
			activity = null;
		}
	}

	/**
	 * close Activity by Class
	 */
	public void finishActivity(Class<?> cls) {
		for (Activity activity : activityStack) {
			if (activity.getClass().equals(cls)) {
				finishActivity(activity);
			}
		}
	}

	/**
	 * close all Activity
	 */
	public void finishAllActivity() {
		for (int i = 0, size = activityStack.size(); i < size; i++) {
			if (null != activityStack.get(i)) {
				activityStack.get(i).finish();
			}
		}
		activityStack.clear();
	}

	/**
	 * exit application
	 */
	public void AppExit() {
		try {
			finishAllActivity();
		} catch (Exception e) {
		}
	}
}
7.Activity声明周期帮助类使用方式
我们所有实现的Activity必须继承父类onDestroy方法,在方法中关闭Activity
@Override
protected void onDestroy() {
   super.onDestroy();
   MyApplication.getInstance().finishActivity(this);
}
我们所有实现的Activity必须加入到管理类中
MyApplication.getInstance().addActivity(this);
当我们需要退出application时,需要关闭所有的Activity
MyApplication.getInstance().AppExit();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值