這篇文章主要講解了“android Robospice的工作原理是什么”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“android Robospice的工作原理是什么”吧!
在茌平等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都網(wǎng)站制作、做網(wǎng)站 網(wǎng)站設(shè)計(jì)制作按需設(shè)計(jì),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站建設(shè),成都營(yíng)銷網(wǎng)站建設(shè),外貿(mào)網(wǎng)站制作,茌平網(wǎng)站建設(shè)費(fèi)用合理。
Robospice 比起 AsyncTask 的確好太多了,但是依然存在一些問題。比如下面這段常見代碼,通過Robospice在Activity中發(fā)起一個(gè)請(qǐng)求的過程。你并不需要細(xì)讀,只要有個(gè)大概的概念就好:
FollowersRequest request = new FollowersRequest(user); lastRequestCacheKey = request.createCacheKey(); spiceManager.execute(request, lastRequestCacheKey, DurationInMillis.ONE_MINUTE, new RequestListener{ @Override public void onRequestFailure(SpiceException e) { // On success } @Override public void onRequestSuccess(FollowerList listFollowers) { // On failure } });
然后是請(qǐng)求的具體代碼:
public class FollowersRequest extends SpringAndroidSpiceRequest{ private String user; public FollowersRequest(String user) { super(FollowerList.class); this.user = user; } @Override public FollowerList loadDataFromNetwork() throws Exception { String url = format("https://api.github.com/users/%s/followers", user); return getRestTemplate().getForObject(url, FollowerList.class); } public String createCacheKey() { return "followers." + user; } }
你需要為每個(gè)請(qǐng)求都做上述的處理,代碼會(huì)顯得很臃腫:
- 對(duì)于你的每種請(qǐng)求你都需要繼承SpiceRequest寫一個(gè)特定的子類。
- 同樣的,對(duì)于每種請(qǐng)求你都需要實(shí)現(xiàn)一個(gè)RequestListener來監(jiān)聽。
- 如果你的緩存過期時(shí)間很短,用戶就需要花較長(zhǎng)時(shí)間等待你的每個(gè)請(qǐng)求結(jié)束。
- RequestListener持有了Activity的隱式引用,那么是不是還需要內(nèi)存泄露的問題。
綜上,這并不是一個(gè)很好的解決方案。
在我開始開發(fā)Candyshop的時(shí)候,我嘗試了其他的方法。我試圖通過混合一些擁有有趣特性的庫來構(gòu)造一個(gè)簡(jiǎn)單而健壯的解決方案。這是我用到的庫的列表:
* AndroidAnnotations用來處理后臺(tái)任務(wù),EBean等等……
* Spring RestTemplate用來處理 REST(含狀態(tài)傳輸)的網(wǎng)絡(luò)請(qǐng)求,這個(gè)庫和AndroidAnnotations配合的非常好。
* SnappyDB這個(gè)庫主要用來將一些 Java 對(duì)象緩存到本地文件中。
* EventBus 通過 Event Bus 來解耦處理 App 內(nèi)部組建間的通訊。
下圖就是我將要詳細(xì)講解的整體架構(gòu):
你肯定會(huì)需要一個(gè)持久化的緩存系統(tǒng),保持這個(gè)系統(tǒng)盡可能簡(jiǎn)單。
@EBean public class Cache { public static enum CacheKey { USER, CONTACTS, ... } publicT get(CacheKey key, Class returnType) { ... } public void put(CacheKey key, Object value) { ... } }
這里我通過下面的例子來說明。記得要確保你使用 REST API 放在同一個(gè)地方。
@Rest(rootUrl = "http://anything.com") public interface CandyshopApi { @Get("/api/contacts/") ContactsWrapper fetchContacts(); @Get("/api/user/") User fetchUser(); }
在程序最初的時(shí)候就初始化Event bus對(duì)象,然后應(yīng)用的全局都可以訪問到這個(gè)對(duì)象。在Android中, Application初始化是一個(gè)很好的時(shí)機(jī)。
public class CandyshopApplication extends Application { public final static EventBus BUS = new EventBus(); ... }
對(duì)于這一類的Activity,我的處理方式和Robospice非常類似,同樣是基于Service解決。不同的是,我的Service并不是Android提供的那個(gè),而是一個(gè)常規(guī)的單例對(duì)象。這個(gè)對(duì)象可以被App的各處訪問到,具體的代碼我們會(huì)在第五步進(jìn)行講解,在這一步,我們先看看這種處理Activity代碼結(jié)構(gòu)是怎么樣的。因?yàn)?,這一步可以看到的是我們簡(jiǎn)化效果***烈的部分!
@EActivity(R.layout.activity_main) public class MainActivity extends Activity { // Inject the service @Bean protected AppService appService; // Once everything is loaded… @AfterViews public void afterViews() { // … request the user and his contacts (returns immediately) appService.getUser(); appService.getContacts(); } /* The result of the previous calls will come as events through the EventBus. We'll probably update the UI, so we need to use @UiThread. */ @UiThread public void onEvent(UserFetchedEvent e) { ... } @UiThread public void onEvent(ContactsFetchedEvent e) { ... } // Register the activity in the event bus when it starts @Override protected void onStart() { super.onStart(); BUS.register(this); } // Unregister it when it stops @Override protected void onStop() { super.onStop(); BUS.unregister(this); } }
一行代碼完成對(duì)用戶數(shù)據(jù)的請(qǐng)求,同樣也只需要一行代碼來解析請(qǐng)求所返回的數(shù)據(jù)。對(duì)于通訊錄等其他數(shù)據(jù)也可以用一樣的方式來處理,聽起來不錯(cuò)吧!
正如我在上一步說的那樣,這里使用的Service并不是Android提供的Service類。其實(shí),一開始的時(shí)候,我考慮使用Android提供的Services,不過***還是放棄了,原因還是為了簡(jiǎn)化。因?yàn)?Android提供的Services通常情況下是為那些在沒有Activity展示情況下但還需要處理的操作提供服務(wù)的。另一種情況,你需要提供一些功能給其他的應(yīng)用。這其實(shí)和我的需求并不完全相符,而且用單例來處理我的后臺(tái)請(qǐng)求可以讓我避免使用復(fù)雜的借口,譬如:ServiceConnection,Binder等等……
這一部分可以探討的地方就多了。為了方便理解,我們從架構(gòu)切入展示當(dāng)Activity調(diào)用getUser()和getContacts()的時(shí)候究竟發(fā)生了什么。
你可以把下圖中每個(gè)serial當(dāng)作一個(gè)線程:
正如你所看到的,這是我非常喜歡的模式。大部分情況下用戶不需要等待,程序的視圖會(huì)立刻被緩存數(shù)據(jù)填充。然后,當(dāng)抓取到了服務(wù)端的***數(shù)據(jù),視圖數(shù)據(jù)會(huì)被新數(shù)據(jù)替代掉。與此對(duì)應(yīng)的是,你需要確保你的Activity
可以接受多次同樣類型的數(shù)據(jù)。在構(gòu)建Activity
的時(shí)候記住這一點(diǎn)就沒有任何問題啦。
下面是一些示例代碼:
// As I said, a simple class, with a singleton scope @EBean(scope = EBean.Scope.Singleton) public class AppService { // (Explained later) public static final String NETWORK = "NETWORK"; public static final String CACHE = "CACHE"; // Inject the cache (step 1) @Bean protected Cache cache; // Inject the rest client (step 2) @RestService protected CandyshopApi candyshopApi; // This is what the activity calls, it's public @Background(serial = CACHE) public void getContacts() { // Try to load the existing cache ContactsFetchedEvent cachedResult = cache.get(KEY_CONTACTS, ContactsFetchedEvent.class); // If there's something in cache, send the event if (cachedResult != null) BUS.post(cachedResult); // Then load from server, asynchronously getContactsAsync(); } @Background(serial = NETWORK) private void getContactsAsync() { // Fetch the contacts (network access) ContactsWrapper contacts = candyshopApi.fetchContacts(); // Create the resulting event ContactsFetchedEvent event = new ContactsFetchedEvent(contacts); // Store the event in cache (replace existing if any) cache.put(KEY_CONTACTS, event); // Post the event BUS.post(event); } }
似乎每個(gè)請(qǐng)求之中的代碼還是有點(diǎn)多!實(shí)際上,這是我為了更好說明才進(jìn)行了展開。不難發(fā)現(xiàn),這些請(qǐng)求都遵守了類似的模式,所以你可以很容易的構(gòu)造一個(gè) Helper 來簡(jiǎn)化他們。比如 getUser()可以是這樣的:
@Background(serial = CACHE) public void getUser() { postIfPresent(KEY_USER, UserFetchedEvent.class); getUserAsync(); } @Background(serial = NETWORK) private void getUserAsync() { cacheThenPost(KEY_USER, new UserFetchedEvent(candyshopApi.fetchUser())); }
那么serial是用來做什么的? 讓我們看看文檔是怎么說的:
默認(rèn)情況下,所有@Background的匿名方法都是并行執(zhí)行的。但是如果兩個(gè)方法使用了同樣名字的serial則會(huì)順序運(yùn)行在同一個(gè)線程中,一個(gè)接著一個(gè)執(zhí)行。
雖然把網(wǎng)絡(luò)請(qǐng)求放在一個(gè)線程中順序執(zhí)行可能會(huì)導(dǎo)致性能下降,但是這使得“先POST然后GET獲得數(shù)據(jù)”的那類事務(wù)處理起來非常容易,這是個(gè)特性值得為此犧牲一些性能。退一步講,如果你真的發(fā)現(xiàn)性能不可接受,還是可以很容易使用多個(gè)serial來解決。現(xiàn)在版本的Candyshop中,我同時(shí)使用了四個(gè)不同的serial。
感謝各位的閱讀,以上就是“android Robospice的工作原理是什么”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)android Robospice的工作原理是什么這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!