Androidアーキテクチャ:MVCモードロードデータフロント表示

21350 ワード

プロジェクトの需要のため、最近ネットプロジェクトのMVCアーキテクチャに接続する必要があることを研究して、1つの新浪微博の開発アーキテクチャを参考にしました
おおよそ次のように述べる
需要:プロジェクトの中でインタフェースはとても多くて、ネットワーキングの操作はActivityの中で処理してとても大きくてしかもそのメンテナンス
ソリューション:データ提供層と表現層を分離し、データ層はインタフェースのデータを要求し、Activityはデータ層からのデータのみを処理する.
Activityの実装を見てみましょう
まず,将来のactivtyを規範化するためのインタフェースの方法を定義した.
package com.testaijialogic;

public interface IAijiaActivity {

	void init();//      

	void initView();//        

	void refresh(Object... param);//                      coreJva

}

そしてActivity
package com.testaijialogic;

/**
 * MVC
 * M     
 * V      
 * C  M        
 */
import java.util.HashMap;
import java.util.List;

import com.testaijialogic.domain.PersonEntity;
import com.testaijialogic.widget.PersonAdapter;

import android.app.Activity;
import android.app.ProgressDialog;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class TestAijiaLogicActivity extends Activity implements IAijiaActivity {
	private Context context;
	private ListView listView;
	private ProgressDialog progressDialog;
	private Button button;
	private ListView listView2;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		context = TestAijiaLogicActivity.this;
		Intent intent = new Intent("com.testaijialogic.MainService");//    Activity    
		startService(intent);
		initView();
		init();
		Log.i("Create", "=====");

	}

	protected void onPause() {

		super.onPause();
		Log.i("onPause", "=====");
	}

	protected void onResume() {

		super.onResume();
		Log.i("onResume", "=====");
	}

	protected void onDestroy() {

		super.onDestroy();
		android.os.Process.killProcess(android.os.Process.myPid());

	}

	@Override
	public void init() {//    list   
		@SuppressWarnings("rawtypes")
		HashMap param = new HashMap();
		param.put("product", "testTask");
		//              
		MainService.addActivity(TestAijiaLogicActivity.this);
		Task task = new Task(Task.GETPRODUCT, param, context);
		MainService.newTask(task);//      
		progressDialog.show();

	}

	@Override
	public void refresh(Object... param) {
		@SuppressWarnings("unchecked")
		HashMap map = (HashMap) param[0];//   map   

		List<PersonEntity> personlist = (List<PersonEntity>) map.get("product");
		PersonAdapter personAdapter = new PersonAdapter(context, personlist);
		listView.setAdapter(personAdapter);

		List<PersonEntity> subpersonlist = (List<PersonEntity>) map//      listview
				.get("subproduct");
		PersonAdapter subpersonAdapter = new PersonAdapter(context,
				subpersonlist);
		listView2.setAdapter(subpersonAdapter);
		progressDialog.dismiss();
		Log.i("  ", "setadapter");

	}

	public void initView() {
		listView = (ListView) findViewById(R.id.listView1);
		listView2 = (ListView) findViewById(R.id.listView2);
		button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				init();
			}
		});
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("      ");

	}
}

表現層はxmlにデータを示すだけで,要求インタフェースには関与していないことがわかる.
次に、データ要求レイヤを示します.
package com.testaijialogic;
/**
 *     ,        
 */
import java.util.HashMap;

import android.content.Context;

public class Task {

	public static final int GETPRODUCT = 1;
	public static final int GETPRODUCT2 = 5;
	public static final int MSGACTIVITY = 4;
	public static final int NEWWEIBO = 7;
	public static final int HOMEREFRESH = 3;
	public static final int VIEWWEIBO = 8;
	private int taskId;
	private HashMap taskParams;
	private Context ctx;

	public Task(int taskId, HashMap taskParams, Context ctx) {
		super();
		this.taskId = taskId;
		this.taskParams = taskParams;
		this.ctx = ctx;  
	}

	public int getTaskId() {
		return taskId;
	}

	public void setTaskId(int taskId) {
		this.taskId = taskId;
	}

	public HashMap getTaskParams() {
		return taskParams;
	}

	public void setTaskParams(HashMap taskParams) {
		this.taskParams = taskParams;
	}

	public Context getCtx() {
		return ctx;
	}

	public void setCtx(Context ctx) {
		this.ctx = ctx;
	}
}

Personエンティティ、個人情報の格納
package com.testaijialogic.domain;

public class PersonEntity {
	// {"amount":100,"id":1,"name":"itcastliming"}
	private int id;
	private String name;
	private String amount;

	public PersonEntity(int id, String name, String amount) {
		setId(id);
		setAmount(amount);
		setName(name);
	}

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the amount
	 */
	public String getAmount() {
		return amount;
	}

	/**
	 * @param amount
	 *            the amount to set
	 */
	public void setAmount(String amount) {
		this.amount = amount;
	}

}

コアネットワークサービス、プロジェクトのすべてのインタフェースデータを要求
package com.testaijialogic;

/*
 *          
 *  */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.testaijialogic.domain.PersonEntity;
import com.testaijialogic.util.WebSender;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class MainService extends Service implements Runnable {

	private static ArrayList<IAijiaActivity> allActivity = new ArrayList<IAijiaActivity>();
	private static ArrayList<Task> allTasks = new ArrayList<Task>();
	List<String> p = new ArrayList<String>();// post                      Post 
	List<String> v = new ArrayList<String>();// post   
	public static boolean isRun = false;

	public static void newTask(Task t) {
		allTasks.add(t);
	}

	public static void addActivity(IAijiaActivity iw) {
		allActivity.add(iw);
	}

	public static void removeActivity(IAijiaActivity iw) {
		allActivity.remove(iw);
	}

	public static IAijiaActivity getActivityByName(String name) {
		for (IAijiaActivity iw : allActivity) {
			if (iw.getClass().getName().indexOf(name) >= 0) {
				return iw;
			}
		}
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

		isRun = true;
		new Thread(this).start();
		Log.e("=============================", "MainService    onCreate()");
	}

	@Override
	public void onDestroy() {
		isRun = false;
		stopSelf();
		super.onDestroy();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (isRun) {
			try {
				if (allTasks.size() > 0) {
					//     ,          
					// doTask(allTasks.get(0));
					for (Task task : allTasks) {
						doTask(task);
					}

				} else {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
					}

				}
			} catch (Exception e) {
				if (allTasks.size() > 0)
					allTasks.remove(allTasks.get(0));
				Log.d("error", "------------------" + e);
			}
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			switch (msg.what) {
			case Task.GETPRODUCT:
				MainService.getActivityByName("TestAijiaLogicActivity")
						.refresh(msg.obj);//   TestAijiaLogicActivity       

				break;
			case Task.GETPRODUCT2://     

				break;
			case Task.MSGACTIVITY:

				break;
			case Task.NEWWEIBO:

				break;
			case Task.VIEWWEIBO:

				break;
			default:
				break;
			}
		}

	};

	@SuppressWarnings("unchecked")
	private void doTask(Task task) throws JSONException {
		// TODO Auto-generated method stub
		Message msg = handler.obtainMessage();
		msg.what = task.getTaskId();

		switch (task.getTaskId()) {
		case Task.GETPRODUCT://       
			Log.i("     ", "MainS" + task.getTaskId());
			String urlStr = "http://10.1.49.230/test/testjson.php";
			p.add("product");//   post    
			v.add((String) task.getTaskParams().get("product"));//   post     
			String result = WebSender.httpClientSendPost(urlStr, p, v);//   httppost  

			List<PersonEntity> personEntities = new ArrayList<PersonEntity>();
			JSONArray jsonArray = new JSONArray(result);
			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject jsonObject = jsonArray.getJSONObject(i);
				PersonEntity personEntity = new PersonEntity(
						jsonObject.getInt("id"), jsonObject.getString("name"),
						jsonObject.getString("amount"));
				personEntities.add(personEntity);

			}
			/**
			 *        ,  list ,           ,          listview         
			 */
			String suburlStr = "http://10.1.49.230/test/testsubjson.php";
			p.add("product");//   post    
			v.add((String) task.getTaskParams().get("product"));//   post     
			String subresult = WebSender.httpClientSendPost(suburlStr, p, v);//   httppost  

			List<PersonEntity> subpersonEntities = new ArrayList<PersonEntity>();
			JSONArray subjsonArray = new JSONArray(subresult);
			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject jsonObject = subjsonArray.getJSONObject(i);
				PersonEntity personEntity = new PersonEntity(
						jsonObject.getInt("id"), jsonObject.getString("name"),
						jsonObject.getString("amount"));
				subpersonEntities.add(personEntity);

			}

			@SuppressWarnings("rawtypes")
			HashMap map = new HashMap();
			map.put("product", personEntities);
			map.put("subproduct", subpersonEntities);
			msg.obj = map;
			// msg.obj = personEntities;//       list       
			break;

		default:
			break;
		}
		allTasks.remove(task);
		//        UI
		handler.sendMessage(msg);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 *       
	 * 
	 * @param context
	 */
	public static void exitAPP(Context context) {
		Intent it = new Intent("weibo4android.logic.util.MainService");
		context.stopService(it);//     
		//                  
		android.os.Process.killProcess(android.os.Process.myPid());

	}

	public static void finshall() {

		for (IAijiaActivity activity : allActivity) {//     activity       
			((Activity) activity).finish();
		}
	}

	/**
	 *       
	 * 
	 * @param context
	 */
	public static void AlertNetError(final Context context) {
		AlertDialog.Builder alerError = new AlertDialog.Builder(context);
		alerError.setTitle("    ");
		alerError.setMessage("     ");
		alerError.setNegativeButton("  ", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				exitAPP(context);
			}
		});
		alerError.setPositiveButton("  ", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				context.startActivity(new Intent(
						android.provider.Settings.ACTION_WIRELESS_SETTINGS));
			}
		});
		alerError.create().show();
	}

}
ネットワークツールクラス
package com.testaijialogic.util;

/**
 *     (   )
 * */

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class WebSender {

	/*
	 *       POST Cookies
	 */
	public static String[] sendPost(String urlStr, String[] param,
			String[] value, String cookies) {
		String[] result = { "", "" };
		String paramValue = "";
		StringBuffer buffer = null;
		HttpURLConnection con = null;

		try {
			URL url = new URL(urlStr);
			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			// con.setRequestProperty("Content-Type", "text/html");

			// set cookies
			if (QHFlag.isNotEmpty(cookies)) {
				con.setRequestProperty("cookie", cookies);
			}

			paramValue = WebSender.getParamStr(param, value);

			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setConnectTimeout(50000);//         (  :  )
			con.setReadTimeout(50000);//            (  :  )

			con.connect();// connect open

			PrintWriter out = new PrintWriter(con.getOutputStream());//     
			out.print(paramValue);
			out.flush();
			out.close();

			// get cookies
			String cks = con.getHeaderField("set-cookie");
			if (cks != "" && cks != null)
				result[1] = cks;

			// get status
			int res = 0;
			res = con.getResponseCode();

			// get info response
			if (res == 200 || res == 302) {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						con.getInputStream(), "UTF-8"));
				buffer = new StringBuffer();
				String line = "";
				while ((line = in.readLine()) != null) {
					buffer.append(line);
				}
			} else {
				QHFlag.e("Web Response:" + res);
			}

			con.disconnect();// Connect Close!
		} catch (Exception e) {
			// e.printStackTrace();
		}

		if (buffer.length() != 0 && buffer != null) {
			result[0] = buffer.toString();
		}
		return result;
	}

	/*
	 *   HttpClient    GET  
	 */
	public static String httpClientSendGet(String webUrl) {
		String content = null;
		// DefaultHttpClient
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// HttpGet
		HttpGet httpget = new HttpGet(webUrl);
		// ResponseHandler
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		try {
			content = httpclient.execute(httpget, responseHandler);
		} catch (Exception e) {
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown();
		return content;
	}

	/*
	 *   HttpClient     cookie GET  
	 */
	public static String httpClientSendGet(String urlStr, String Cookies) {
		String httpUrl = urlStr;
		HttpGet httpGet = new HttpGet(httpUrl);
		try {
			HttpClient httpClient = new DefaultHttpClient();
			httpGet.setHeader("cookie", Cookies);
			//   HttpClient,  HttpResponse
			HttpResponse httpResponse = httpClient.execute(httpGet);

			//     
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//         
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				return strResult;
			}
		} catch (Exception e) {
		}
		return "0";
	}

	/*
	 *   HttpClient    POST  
	 */
	public static String httpClientSendPost(String urlStr,
			List<String> paraName, List<String> val) {
		String httpUrl = urlStr;
		// HttpPost  
		HttpPost httpPost = new HttpPost(httpUrl);

		//   NameValuePair       Post  
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		//         
		System.out.println("====================================");
		for (int i = 0; i < paraName.size(); i++) {
			params.add(new BasicNameValuePair(paraName.get(i), val.get(i)));
			System.out.println(paraName.get(i) + "->" + val.get(i));
		}
		System.out.println("====================================");

		try {
			//      
			HttpEntity httpEntity = new UrlEncodedFormEntity(params, "utf-8");
			httpPost.setEntity(httpEntity);

			// httpClient  
			HttpClient httpClient = new DefaultHttpClient();

			//   HttpClient,  HttpResponse
			HttpResponse httpResponse = httpClient.execute(httpPost);

			//     
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//         
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				System.out.println(strResult);
				return strResult;
			}
		} catch (Exception e) {
		}
		return "";
	}

	/*
	 *   HttpClient    POST  
	 */
	public static String httpClientSendPost(String urlStr,
			List<String> paraName, List<String> val, String Cookies) {
		String httpUrl = urlStr;
		// HttpPost  
		HttpPost httpPost = new HttpPost(httpUrl);

		//   NameValuePair       Post  
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		//         
		System.out.println("====================================");
		for (int i = 0; i < paraName.size(); i++) {
			params.add(new BasicNameValuePair(paraName.get(i), val.get(i)));
			System.out.println(paraName.get(i) + "->" + val.get(i));
		}
		System.out.println("====================================");

		try {
			//      
			HttpEntity httpEntity = new UrlEncodedFormEntity(params, "utf-8");
			httpPost.setEntity(httpEntity);
			httpPost.setHeader("cookie", Cookies);
			// httpClient  
			HttpClient httpClient = new DefaultHttpClient();

			//   HttpClient,  HttpResponse
			HttpResponse httpResponse = httpClient.execute(httpPost);

			//     
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//         
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				System.out.println(strResult);
				return strResult;
			}
		} catch (Exception e) {
		}
		return "";
	}

	public static String uploadBitmap1(String urlString, byte[] imageBytes,
			String cookie) {
		// String boundary = "*****";
		try {
			URL url = new URL(urlString);
			final HttpURLConnection con = (HttpURLConnection) url
					.openConnection();
			//   input、Output,   Cache
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);

			//      method=POST
			con.setRequestMethod("POST");
			// setRequestProperty
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type", "text/html");
			if (cookie != null && cookie != "") {
				Log.i("myEvent", "send cookies value is:" + cookie);
				con.setRequestProperty("cookie", cookie);
			}
			//             (  :  )
			con.setReadTimeout(50000);
			//            (  :  )
			con.setConnectTimeout(50000);
			// System.out.println(con.getResponseCode());
			//   DataOutputStream
			DataOutputStream dsDataOutputStream = new DataOutputStream(
					con.getOutputStream());
			// dsDataOutputStream.writeBytes(twoHyphen + boundary + endString);
			// dsDataOutputStream.writeBytes("Content-Disposition:form-data;"
			// + "name=\"file1\";filename=\"" + "11.jpg\"" + endString);
			// dsDataOutputStream.writeBytes(endString);

			dsDataOutputStream.write(imageBytes, 0, imageBytes.length);
			// dsDataOutputStream.writeBytes(endString);
			// dsDataOutputStream.writeBytes(twoHyphen + boundary + twoHyphen
			// + endString);
			dsDataOutputStream.close();
			int cah = con.getResponseCode();
			if (cah == 200) {
				InputStream isInputStream = con.getInputStream();
				int ch;
				StringBuffer buffer = new StringBuffer();
				while ((ch = isInputStream.read()) != -1) {
					buffer.append((char) ch);
				}
				return buffer.toString();
			} else {
				return "false";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "false";
		}

	}

	/**
	 *      
	 * */
	public static String getParamStr(String[] param, String[] value) {
		String res = "";
		if (param.length == value.length) {
			for (int i = 0; i < param.length; i++) {
				res += param[i] + "=" + toUTF8(value[i]) + "&";
			}
		}
		return res.substring(0, res.length() - 1);
	}

	public static String toUTF8(String str) {
		String u = str;
		try {
			u = java.net.URLEncoder.encode(u, "UTF-8");
		} catch (Exception e) {

		}
		return u;
	}

}