如何構建一個結構清晰的Android程序

隨著Android程序功能模塊越來越多,模塊之間的交互也日漸平常,一個結構在開始就設計良好的系統,不會因為上述的原因就出現大量的復制粘貼,如果出現大量的復制粘貼,那說明這個系統的結構設計是失敗的。以前在寫一個電子商務類聯網應用的時候,每個Activity都有一個AsyncTask的異步線程去執行聯網下載數據,解析數據,每當新增一個功能模塊的時候就會出現大量的代碼復制粘貼。導致程序難以維護。所以對於這些需要處理大量耗時工作的應用,提出瞭一個由數據中心負責接收數據請求,處理好數據後將數據異步返回的機制。

初步的設想是將數據中心放在Service中,然後通過binderService,每個想要和Service通信的Activity都可以連接到Service中。然後通過Handler發送數據請求給Service,Service根據請求,處理數據,然後通過BroadcastReceiver機制將數據返回給對此類數據感興趣的對象。

一下是實現的關鍵代碼:

01
package com.hxcy;
02
 
03
import android.app.Service;
04
import android.content.Intent;
05
import android.os.Binder;
06
import android.os.Bundle;
07
import android.os.Handler;
08
import android.os.Handler.Callback;
09
import android.os.IBinder;
10
import android.os.Message;
11
import android.support.v4.content.LocalBroadcastManager;
12
 
13
import com.hxcy.model.Person;
14
 
15
public class DataCenterService extends Service implements Callback {
16
    private Handler msgHandler;
17
 
18
    private MyBinder binder;
19
 
20
    public static final int GET_PERSON_DATA = 0X001;
21
    public static final int GET_COUNTRY_DATA = 0X002;
22
 
23
    public static final String GET_PERSON_ACTION = "com.hxcy.action.person";
24
    public static final String GET_COUNTRY_ACTION = "com.hxcy.action.country";
25
 
26
    private LocalBroadcastManager mLocalBroadcastManager;
27
 
28
    public class MyBinder extends Binder {
29
        public Handler getMessageHandler() {
30
            return msgHandler;
31
        }
32
    }
33
 
34
    @Override
35
    public IBinder onBind(Intent intent) {
36
        binder = new MyBinder();
37
        msgHandler = new Handler(this);
38
        mLocalBroadcastManager = DataCenterApplication
39
                .getLocalBroadcastManager();
40
        return binder;
41
    }
42
 
43
    @Override
44
    public boolean handleMessage(Message msg) {
45
        switch (msg.what) {
46
        case GET_PERSON_DATA:
47
            new PersonDataThrea().start();
48
            return true;
49
        case GET_COUNTRY_DATA:
50
 
51
            return true;
52
        default:
53
            return false;
54
        }
55
    }
56
 
57
    class PersonDataThrea extends Thread {
58
 
59
        @Override
60
        public void run() {
61
 
62
            Intent intent = new Intent(GET_PERSON_ACTION);
63
            Bundle bundle = new Bundle();
64
            Person[] persons = new Person[5];
65
            for (int i = 0; i < 5; i++) {
66
                Person person = new Person();
67
                person.setAge(i + 20);
68
                person.setName(i + " person");
69
                person.setId(i + ":" + System.currentTimeMillis());
70
                persons[i] = person;
71
            }
72
            bundle.putParcelableArray("persons", persons);
73
            intent.putExtras(bundle);
74
            mLocalBroadcastManager.sendBroadcast(intent);
75
 
76
        }
77
 
78
    }
79
}
01
package com.hxcy;
02
 
03
import android.app.Activity;
04
import android.content.BroadcastReceiver;
05
import android.content.ComponentName;
06
import android.content.Context;
07
import android.content.Intent;
08
import android.content.IntentFilter;
09
import android.content.ServiceConnection;
10
import android.os.Bundle;
11
import android.os.Handler;
12
import android.os.IBinder;
13
import android.support.v4.content.LocalBroadcastManager;
14
 
15
import com.hxcy.model.Person;
16
import com.hxcy.util.LogUtil;
17
 
18
public class DataCenterDemoActivity extends Activity {
19
    private LocalBroadcastManager mLocalBroadcastManager;
20
    private Handler msgHandler;
21
    private BroadcastReceiver personDataReceiver=new BroadcastReceiver() {
22
        
23
        @Override
24
        public void onReceive(Context context, Intent intent) {
25
            Bundle bundle=intent.getExtras();
26
            if(bundle!=null){
27
                Person[] persons=(Person[]) bundle.getParcelableArray("persons");
28
                for(int j=persons.length-1;j>=0;j–){
29
                    LogUtil.d(getApplicationContext(), persons[j]+"");
30
                }
31
                
32
            }
33
        }
34
    };
35
    
36
    private ServiceConnection conn=new ServiceConnection() {
37
        
38
        @Override
39
        public void onServiceDisconnected(ComponentName name) {
40
            // TODO Auto-generated method stub
41
            
42
        }
43
        
44
        @Override
45
        public void onServiceConnected(ComponentName name, IBinder service) {
46
            msgHandler=((DataCenterService.MyBinder)service).getMessageHandler();
47
            
48
            msgHandler.postDelayed(refreshPersonData, 3000);
49
        }
50
    };
51
    @Override
52
    public void onCreate(Bundle savedInstanceState) {
53
        super.onCreate(savedInstanceState);
54
        setContentView(R.layout.main);
55
        mLocalBroadcastManager=DataCenterApplication.getLocalBroadcastManager();
56
        
57
        mLocalBroadcastManager.registerReceiver(personDataReceiver, new IntentFilter(DataCenterService.GET_PERSON_ACTION));
58
        bindService(new Intent(this,DataCenterService.class), conn, BIND_AUTO_CREATE);
59
    }
60
    
61
    Runnable refreshPersonData =new Runnable() {
62
        
63
        @Override
64
        public void run() {
65
            msgHandler.sendEmptyMessage(DataCenterService.GET_PERSON_DATA);
66
            msgHandler.postDelayed(this, 3000);
67
        }
68
    };
69
}

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類:

view sourceprint?
01
package com.hxcy.model;
02
 
03
import android.os.Parcel;
04
import android.os.Parcelable;
05
 
06
public class Person implements Parcelable {
07
    private String name;
08
    private int age;
09
    private String id;
10
    
11
    
12
    public String getName() {
13
        return name;
14
    }
15
 
16
    public void setName(String name) {
17
        this.name = name;
18
    }
19
 
20
    public int getAge() {
21
        return age;
22
    }
23
 
24
    public void setAge(int age) {
25
        this.age = age;
26
    }
27
 
28
    public String getId() {
29
        return id;
30
    }
31
 
32
    public void setId(String id) {
33
        this.id = id;
34
    }
35
 
36
    @Override
37
    public int describeContents() {
38
        return 0;
39
    }
40
 
41
    @Override
42
    public String toString() {
43
        return "Person [name=" + name + ", age=" + age + ", id=" + id + "]";
44
    }
45
 
46
    @Override
47
    public void writeToParcel(Parcel dest, int flags) {
48
        dest.writeString(id);
49
        dest.writeString(name);
50
        dest.writeInt(age);
51
 
52
    }
53
    
54
    public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
55
 
56
        @Override
57
        public Person createFromParcel(Parcel source) {
58
            // TODO Auto-generated method stub
59www.aiwalls.com
            Person person=new Person();
60
            person.setId(source.readString());
61
            person.setName(source.readString());
62
            person.setAge(source.readInt());
63
            return person;
64
        }
65
 
66
        @Override
67
        public Person[] newArray(int size) {
68
            
69
            return new Person[size];
70
        }
71
        
72
    };
73
}

作者:fneg

發佈留言