调用了IntentService onCreate()但是onHandleIntent()不是

时间:2016-10-01 06:40:36

标签: java android android-service intentservice

我使用以下方法开始IntentService

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
    }
}

我有两个测试场景:

  • 数据包含2000个对象
  • 数据包含4000个对象

使用2000个对象,Service可以完美运行。

使用4000个对象时,onCreate()的{​​{1}}方法被调用,而它就是...... Service。该应用程序在一段时间后抛出一个ANR。

我已经在onHandleIntent()的第一行测试了Log.d()个调用和断点,当onHandleIntent()拥有4000个对象时,它根本不被调用。

Data 抛出。

我根本没有被TransactionTooLargeException抛出,不知道出了什么问题。

这种行为可能是什么原因?

1 个答案:

答案 0 :(得分:0)

如果要过滤logcat,则可能看不到TransactionTooLargeException。您可以在Intent中传递的数据量有合理的限制。序列化为JSON的4000个对象肯定太过分了!这是错误的做法。您的应用程序架构存在缺陷。

您可以简单地将4000个对象存储在static变量中,以便Service可以访问它们而无需序列化它们,将它们从Activity传递到Service ,然后反序列化它们。

或者,您需要将4000个对象序列化为文件,或使用数据库来保存数据。

相关问题