2014-07-04 42 views
4

我米實際上深化發展具有數據存儲的Android應用程序,和我繼續像這樣:Android的數據存儲性能

活動 - >商務服務 - >回購(有彈簧安置FW)。利用這一點,我必須讓活動在關閉之前完成他的存儲工作(線程處理,進度對話...)。

這是一種不好的編碼方式來使用android服務來存儲數據嗎?

有了這個,用戶可以繼續導航,並有一個印象使用流暢的應用程序。這是一個好的解決方案嗎?

謝謝

回答

27

有沒有必要保持您的活動在前臺等待後臺邏輯來完成。

你應該做的是以一種與你的活動「分離」的方式執行這個背景邏輯。

解決此問題有兩種方法:風險和安全。


高風險的方式

class MyActivity extends Activity { 

    void calledWhenActivityNeedsToBeClosed() { 

      // start a thread to do background work 
      new Thread() { 
       public void run() { 
        perform long running logic here 
       } 
      }.start(); 

      // and clos the activity without waiting for the thread to complete 
      this.finish(); 
    } 
} 

您可以使用的AsyncTask或任何java.concurrent的構建,而不是線程。他們都會做這項工作。

我已經使用了這種方式多年。它大多工作正常。但是..它本質上是有缺陷的。
爲什麼?因爲一旦活動完成(),Android可以隨時將其與其所有資源一起回收,並且包括暫停所有工作線程。
如果你的長時間工作不超過幾秒鐘,並且我假設你的回購更新是這樣的,那麼 的風險很小。但爲什麼要這樣呢?


的安全方法

聲明一個服務和活動下降之前啓動它來執行長時間運行的動作:

class MyActivity extends Activity { 

    void calledWhenActivityNeedsToBeClosed() { 

      // delegate long running work to service 
      startService(this, new Intent(this, MyWorkerService.class)); 

      // and close the activity without waiting for the thread to complete 
      this.finish(); 
    } 

} 


這一世s 更安全。 Android可以也常常會殺死正在運行的服務,但比殺死後臺活動更不情願。


請注意,如果你能看到的場景中,你的UI是可見的,而工人服務仍在運行, 你可能會想使用IntentService代替。


最後 - 如果你想絕對放心,背景邏輯不會被Android的清除,你 應該使用foreground service。下面是如何做到這一點,但是請被警告 - 像你所描述的情況下,前臺的服務可能是在工程:

static final int NOTIF_ID = 100; 

// Create the FG service intent 
Intent intent = new Intent(getApplicationContext(), MyActivity.class); // set notification activity 
showTaskIntent.setAction(Intent.ACTION_MAIN); 
showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER); 
showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

PendingIntent pIntent = PendingIntent.getActivity(
       getApplicationContext(), 
       0, 
       intent, 
       PendingIntent.FLAG_UPDATE_CURRENT); 

Notification notif = new Notification.Builder(getApplicationContext()) 
       .setContentTitle(getString(R.string.app_name)) 
       .setContentText(contentText) 
       .setSmallIcon(R.drawable.ic_notification) 
       .setContentIntent(pIntent) 
       .build(); 

startForeground(NOTIF_ID, notif); 


+0

謝謝您的回答。而且每次都有一種背景變化的服務:他的目標是存儲在我們獲得網絡連接時尚未保存的數據。即使我們有網絡連接,使用它來存儲數據是否是一種糟糕的方式?在需要時將服務綁定到活動上? – mfrachet