2016-10-01 28 views
3

我開始一個IntentService以下方法:IntentService的onCreate()調用,但onHandleIntent()不

private void startMyService(Data data) { 
    Intent intent = new Intent(this, MyService.class); 
    intent.putExtra(KEY_DATA, data.toJson()); 
    startService(intent); 
} 

Data類:

public class Data extends ArrayList<MyObject> { 

    public Data() { 
     super(); 
    } 

    public Data(Collection<MyObject> myObjects) { 
     super(myObjects); 
    } 

    public String toJson() { 
     return new Gson().toJson(this); 
    } 

    public static Data fromJson(String jsonString) { 
     return new Gson().fromJson(jsonString, Data.class); 
    } 
} 

IntentService的相關部分:

public class MyService extends IntentService { 

    private Data data; 

    public MyService() { 
     super("myServiceName"); 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

     // this gets called properly 
     Log.d("myTag", "Service onCreate()"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     // this is not called in case of the bigger dataset 
     Log.d("myTag", "Service onHandleIntent()"); 

     String dataJson = intent.getStringExtra(KEY_DATA); 
     data = Data.fromJson(dataJson); 

     // doing stuff with data 
    } 
} 

我有2個測試場景:

  • 數據保持2000個對象
  • 數據保持4000個對象

隨着2000和目的,Service運行完美無缺。

對於4000個對象,調用ServiceonCreate()方法,就是這樣... onHandleIntent()未被調用。一段時間後,該應用只是拋出一個ANR。

我已經與上onHandleIntent()第一線既Log.d()電話和斷點測試,它是不是在所有的時候Data持有4000個對象調用。

TransactionTooLargeException不是拋出。

我沒有得到Exception,根本不知道有什麼問題。

這種行爲的原因是什麼?

+0

嘗試在sqlite中保存json,以便您可以通過調用intentService類中的方法直接訪問它 – Manifest

+0

可能是[SO帖子](http://stackoverflow.com/a/14379016/5015207)會有幫助:如果Binder事務失敗,似乎不會總是有TransactionTooLargeException – 0X0nosugar

回答

0

如果您正在過濾logcat,則可能看不到TransactionTooLargeException。您可以在Intent中傳遞的數據量有合理的限制。序列化爲JSON的4000個對象絕對太輕鬆!這是錯誤的方法。你的應用程序體系結構有缺陷。

您可以將4000級的對象只是存儲在一個static變量,以便Service可以得到,而不必它們序列化,從Activity通過他們Service,然後反序列化他們。

或者,您需要將4000個對象序列化到一個文件,或使用數據庫來保存數據。

相關問題