Android的 - 重试最佳实践IntentService [英] Android - Best practice for retrying IntentService

查看:187
本文介绍了Android的 - 重试最佳实践IntentService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Andr​​oid应用程序发送的文件加载到Amazon S3。每个文件URI在单独调用传递给 IntentService 其执行上载。

My Android app sends a load of files to Amazon S3. Each file URI is passed in separate calls to IntentService which performs the upload.

不过,我想知道什么是处理故障的最佳途径......我应该能够检测到故障与我的 IntentService onHandleIntent同样的方法中()法并重,还是应该允许失败之外处理方法(如果有的话,怎么样?)?

However, I'm wondering what is the best way to handle failures... Should I detect the failure with my IntentService's onHandleIntent() method and retry within that same method, OR should I allow the failure to be handled outside of the method (and if so, how?)?

我个人对我会preFER任何文件中的第一个建议倚成功上传之前尝试后续文件上传,但我不知道,如果检测错误和<$ C范围内进行重试$ C> onHandleIntent()的方法是很好的做法(?)。

I'm personally leaning towards the first suggestion as I would prefer any file to be successfully uploaded before subsequent files are attempted to be uploaded, but I am not sure if detecting errors and performing retries within the onHandleIntent() method is good practice(?).

推荐答案

这是一个非常好的问题。有人问我,这一次采访,我未能回答。但我会尝试和经过一番搜索的答案在这里回答。

This is a very nice question. I was asked this in one interview and i had failed to answer it. But i will try and answer it here after some searching for the answer.

步骤1:您启动IntentService。你可以开始无论是从某项活动或片段的IntentService。

Step-1: You start an IntentService. You can start an IntentService either from an Activity or a Fragment.

/* Starting Download Service */

DownloadResultReceiver mReceiver = new DownloadResultReceiver(new Handler());
mReceiver.setReceiver(this);
Intent intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class);

/* Send optional extras to Download IntentService */
intent.putExtra("url", url);
intent.putExtra("receiver", mReceiver);
intent.putExtra("requestId", 101);
startService(intent);

步骤2:请扩展IntentService类

Step-2: Make the class that extends IntentService.

public class DownloadService extends IntentService {

    public static final int STATUS_RUNNING = 0;
    public static final int STATUS_FINISHED = 1;
    public static final int STATUS_ERROR = 2;

    private static final String TAG = "DownloadService";

    public DownloadService() {
        super(DownloadService.class.getName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        Log.d(TAG, "Service Started!");

        final ResultReceiver receiver = intent.getParcelableExtra("receiver");
        String url = intent.getStringExtra("url");

        Bundle bundle = new Bundle();

        if (!TextUtils.isEmpty(url)) {
            /* Update UI: Download Service is Running */
            receiver.send(STATUS_RUNNING, Bundle.EMPTY);

            try {
                String[] results = downloadData(url);//make your network call here and get the data or download a file.

                /* Sending result back to activity */
                if (null != results && results.length > 0) {
                    bundle.putStringArray("result", results);
                    receiver.send(STATUS_FINISHED, bundle);
                }
            } catch (Exception e) {

                /* Sending error message back to activity */
                bundle.putString(Intent.EXTRA_TEXT, e.toString());
                receiver.send(STATUS_ERROR, bundle);
            }
        }
        Log.d(TAG, "Service Stopping!");
        this.stopSelf();
    }
}

步骤3::要收到成效,从IntentService回来了,我们可以用ResultReciever的子类。一旦结果是从服务发送的onReceiveResult()方法将被调用。您的活动处理该响应并获取来自捆绑的结果。一旦结果收到,因此活动实例更新UI。

Step-3: To receive results back from IntentService, we can use subclass of ResultReciever. Once results are sent from Service the onReceiveResult() method will be called. Your activity handles this response and fetches the results from the Bundle. Once results are recieved, accordingly the activity instance updates the UI.

public class DownloadResultReceiver extends ResultReceiver {
    private Receiver mReceiver;

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

    public void setReceiver(Receiver receiver) {
        mReceiver = receiver;
    }

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

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

步骤4:在MainActivity:

Step-4: In your MainActivity:

@Override
    public void onReceiveResult(int resultCode, Bundle resultData) {
        switch (resultCode) {
            case DownloadService.STATUS_RUNNING:
                //progress bar visible.
                break;
            case DownloadService.STATUS_FINISHED:
                /* Hide progress & extract result from bundle */
                /* Update ListView with result */
                break;
            case DownloadService.STATUS_ERROR:
                /* Handle the error */
                String error = resultData.getString(Intent.EXTRA_TEXT);
                Toast.makeText(this, error, Toast.LENGTH_LONG).show();
                /*It is here, i think, that you can again check (eg your net connection) and call the IntentService to restart fetching of data from the network. */  
                break;
        }
    }

我希望以上回答可以帮助你。改善回答任何建议者居多。谢谢。

I hope the above answer helps you. Any suggestions to improve the answer are most welcome. Thanks.

这篇关于Android的 - 重试最佳实践IntentService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆