使用IntentService时从已保存状态加载活动的实例

时间:2015-07-29 09:57:53

标签: android service intentservice

我有一个Activity,从那里我开始使用IntentService创建任务(考虑将多个文件上传到服务器)。完成每次上传后,我会使用Activity将上传结果发送回ResultReceiver。我将结果返回到Activity并更新了用户界面。

在上传文件时,我关闭了ActivityIntentService仍在运行并返回结果。但Activity因为被摧毁而无法获得结果。现在我再次打开Activity我想继续显示上传进度。但它没有发生。我正在分享我所做的代码。

MyResultReceiver.java

public class MyResultReceiver extends ResultReceiver {

    private Receiver receiver;

    public MyResultReceiver(Handler handler) {
        super(handler);
    }

    public void setReceiver(Receiver receiver) {
        this.receiver = receiver;
    }

    public interface Receiver {
        public void onReceiveResult(int resultCode, Bundle resultData);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        if (receiver != null) {
             receiver.onReceiveResult(resultCode, resultData);
        }
    }
}

MainActivity.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.textView);

    resultReceiver = new MyResultReceiver(new Handler());
    resultReceiver.setReceiver(new MyResultReceiver.Receiver() {
        @Override
        public void onReceiveResult(int resultCode, Bundle resultData) {
            if (resultCode == RESULT_OK) {
                isCompleted = resultData.getBoolean("IsCompleted");
                textView.setText(resultData.getString("Message"));
            }
        }
    });

    Intent intent = new Intent(MainActivity.this, MyIntentService.class);
    intent.putExtra("receiver", resultReceiver);
    startService(intent);
}

MyIntentService.java

@Override
protected void onHandleIntent(final Intent intent) {

    for (int count = 0; count <= i; count--) {
        ResultReceiver receiver = intent.getParcelableExtra("receiver");
        i -= 1;
        Bundle bundle = new Bundle();
        if (count == i)
            bundle.putBoolean("IsCompleted", true);
        else
            bundle.putBoolean("IsCompleted", false);

        bundle.putString("Message", "This is " + i);

        receiver.send(Activity.RESULT_OK, bundle);
        Log.i("Intent Service", "This is " + i);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在上面的代码中,我试图在TextView中显示递减的计数。

我已尝试使用onSaveInstanceState,但根据文档,它仅在操作系统决定时才会保存。在我的情况下,我希望一直存储这些数据,并在重新创建活动时恢复它。

我们鼓励您提供任何帮助或参考。

编辑:我如何尝试存储和恢复实例

Intent intent = new Intent(MainActivity.this, MyIntentService.class);
if (savedInstanceState != null) {
   intent.putExtra("receiver", savedInstanceState.getParcelable("savedReceiver"));
} else
   intent.putExtra("receiver", resultReceiver);
startService(intent);

我试过这样的事情。但没有帮助。我无法使用savedInstanceState,因为它不会一直被调用。希望这有帮助!

0 个答案:

没有答案