如何构建一个结构清晰的Android程序

随着Android程序功能模块愈来愈多,模块之间的交互也日渐日常,一个结构在开始就设计良好的系统,不会由于上述的缘由就出现大量的复制粘贴,若是出现大量的复制粘贴,那说明这个系统的结构设计是失败的。之前在写一个电子商务类联网应用的时候,每一个Activity都有一个AsyncTask的异步线程去执行联网下载数据,解析数据,每当新增一个功能模块的时候就会出现大量的代码复制粘贴。致使程序难以维护。因此对于这些须要处理大量耗时工做的应用,提出了一个由数据中心负责接收数据请求,处理好数据后将数据异步返回的机制。java

初步的设想是将数据中心放在Service中,而后经过binderService,每一个想要和Service通讯的Activity均可以链接到Service中。而后经过Handler发送数据请求给ServiceService根据请求,处理数据,而后经过BroadcastReceiver机制将数据返回给对此类数据感兴趣的对象。android

一下是实现的关键代码:app

package com.hxcy;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;

import com.hxcy.model.Person;

public class DataCenterService extends Service implements Callback {
	private Handler msgHandler;

	private MyBinder binder;

	public static final int GET_PERSON_DATA = 0X001;
	public static final int GET_COUNTRY_DATA = 0X002;

	public static final String GET_PERSON_ACTION = "com.hxcy.action.person";
	public static final String GET_COUNTRY_ACTION = "com.hxcy.action.country";

	private LocalBroadcastManager mLocalBroadcastManager;

	public class MyBinder extends Binder {
		public Handler getMessageHandler() {
			return msgHandler;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		binder = new MyBinder();
		msgHandler = new Handler(this);
		mLocalBroadcastManager = DataCenterApplication
				.getLocalBroadcastManager();
		return binder;
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case GET_PERSON_DATA:
			new PersonDataThrea().start();
			return true;
		case GET_COUNTRY_DATA:

			return true;
		default:
			return false;
		}
	}

	class PersonDataThrea extends Thread {

		@Override
		public void run() {

			Intent intent = new Intent(GET_PERSON_ACTION);
			Bundle bundle = new Bundle();
			Person[] persons = new Person[5];
			for (int i = 0; i < 5; i++) {
				Person person = new Person();
				person.setAge(i + 20);
				person.setName(i + " person");
				person.setId(i + ":" + System.currentTimeMillis());
				persons[i] = person;
			}
			bundle.putParcelableArray("persons", persons);
			intent.putExtras(bundle);
			mLocalBroadcastManager.sendBroadcast(intent);

		}

	}
}

package com.hxcy;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;

import com.hxcy.model.Person;
import com.hxcy.util.LogUtil;

public class DataCenterDemoActivity extends Activity {
	private LocalBroadcastManager mLocalBroadcastManager;
	private Handler msgHandler;
	private BroadcastReceiver personDataReceiver=new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle=intent.getExtras();
			if(bundle!=null){
				Person[] persons=(Person[]) bundle.getParcelableArray("persons");
				for(int j=persons.length-1;j>=0;j--){
					LogUtil.d(getApplicationContext(), persons[j]+"");
				}
				
			}
		}
	};
	
	private ServiceConnection conn=new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			msgHandler=((DataCenterService.MyBinder)service).getMessageHandler();
			
			msgHandler.postDelayed(refreshPersonData, 3000);
		}
	};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mLocalBroadcastManager=DataCenterApplication.getLocalBroadcastManager();
        
        mLocalBroadcastManager.registerReceiver(personDataReceiver, new IntentFilter(DataCenterService.GET_PERSON_ACTION));
        bindService(new Intent(this,DataCenterService.class), conn, BIND_AUTO_CREATE);
    }
    
    Runnable refreshPersonData =new Runnable() {
		
		@Override
		public void run() {
			msgHandler.sendEmptyMessage(DataCenterService.GET_PERSON_DATA);
			msgHandler.postDelayed(this, 3000);
		}
	};
}


package com.hxcy;

import android.app.Application;
import android.support.v4.content.LocalBroadcastManager;

public class DataCenterApplication extends Application {
    private static LocalBroadcastManager mLocalBroadcastManager;
    @Override
    public void onCreate() {
        super.onCreate();
        mLocalBroadcastManager=LocalBroadcastManager.getInstance(this);
    }
   
    public static LocalBroadcastManager getLocalBroadcastManager(){
        return mLocalBroadcastManager;
    }
}异步

Person类:ide

package com.hxcy.model;

import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable {
	private String name;
	private int age;
	private String id;
	
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", id=" + id + "]";
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(id);
		dest.writeString(name);
		dest.writeInt(age);

	}
	
	public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {

		@Override
		public Person createFromParcel(Parcel source) {
			// TODO Auto-generated method stub
			Person person=new Person();
			person.setId(source.readString());
			person.setName(source.readString());
			person.setAge(source.readInt());
			return person;
		}

		@Override
		public Person[] newArray(int size) {
			
			return new Person[size];
		}
		
	};
}
相关文章
相关标签/搜索