【问题标题】:how to send data rapidly between a service and an activty如何在服务和活动之间快速发送数据
【发布时间】:2017-08-24 23:35:38
【问题描述】:

如果该活动正在运行而不重新启动服务或活动,我如何将数据从服务发送到活动。实际上,我的服务中有一个 Asynctask 类,用于下载文件,我想在活动中的进度条上显示下载百分比。谁能告诉我该怎么做? 我在 asynctask 中尝试了界面,但它发出了一个新请求,我的进度条为空。

public class Downloader extends AsyncTask<Combine,String,Combine> {
Responcer1 responder;
HttpURLConnection connection;
int id;
int position;


public Downloader(int position){
    this.position=position;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();

    responder=new SavedLinks();
    responder.start(position);
}

@Override
protected Combine doInBackground(Combine... param) {

    try {
        int position=param[0].position;
        Log.i("downloader",param[0].caption+param[0].link+param[0].url+param[0].user);
        id=param[0].id;

        connection = null;
        URL url;
        url = new URL(param[0].link);
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(45000);
        connection.setReadTimeout(5000);
        InputStream in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");}
        in.close();
        connection.disconnect();
        return saperate(sb.toString(),param[0]);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }}

}

【问题讨论】:

    标签: android class service android-asynctask download


    【解决方案1】:

    我建议您使用EventBus,这是一个专门为简化活动、服务等之间的交互而编写的库。使用起来相当简单,可以开始阅读quick start guide

    【讨论】:

      【解决方案2】:

      好吧,您实际上不需要那么频繁地发送它。每隔几秒钟就足以显示一个进度条。但忽略这一点,有几个很好的解决方案:

      1)从Service广播状态并在Activity中使用BroadcastReceiver

      2)绑定到服务并传入一个状态回调给服务以回调你的活动

      3)使用EventBus进行状态消息传递

      2 和 3 要求服务处于同一进程中,但由于这是默认设置,因此它们可能没问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-22
        • 1970-01-01
        • 1970-01-01
        • 2012-07-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多