ProgressBar的活动 - >服务 - > AsyncTask下载 - 但如何更新进度?

时间:2009-12-28 14:03:01

标签: android service progress-bar

这是当前的状态/情况:我有一个Activity绑定一个Service,它创建AsyncTasks,下载各种Web资源。这很好用,但ProgressBar当然没有显示任何内容。

以前我有一个Activity创建了一个下载了一些东西的AsyncTask。 AsyncTask获得了持有ProgressBar的View。所以我可以使用onProgressUpdate和publishProgress更新进度。显然这不再起作用,因为我没有引用ProgressBar。

那么,您对如何更新进度有任何想法吗?

提前致谢。

3 个答案:

答案 0 :(得分:10)

很好解释确实只是错过了这个例子:) 我去扔它,它就在这里。

public class Detail extends Activity {

    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(DownloadService.CUSTOM_INTENT)) {
                mProgressDialog.setProgress(intent.getFlags());
            }
        }
    };

    // Flag if receiver is registered 
    private boolean mReceiversRegistered = false;
    // Define a handler and a broadcast receiver
    private final Handler mHandler = new Handler();

    @Override
    protected void onResume() {
      super.onResume();

      // Register Sync Recievers
      IntentFilter intentToReceiveFilter = new IntentFilter();
      intentToReceiveFilter.addAction(DownloadService.CUSTOM_INTENT);
      this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
      mReceiversRegistered = true;
    }

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

      // Make sure you unregister your receivers when you pause your activity
      if(mReceiversRegistered) {
        unregisterReceiver(mIntentReceiver);
        mReceiversRegistered = false;
      }
    }
}








public class DownloadService extends Service {
    private static final String CLASS_NAME = DownloadService.class.getSimpleName();
    private List<Download> downloads = new ArrayList<Download>();
    private int currentPosition;
    public static final String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    private Context ctx;
    @Override
    public IBinder onBind(Intent arg0) {
        ctx = getApplicationContext();
        return mBinder;
    }


    private class DownloadFile extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... _url) {
            Log.d(Constants.LOG_TAG, CLASS_NAME + " Start the background GetNewsTask \nURL :" + _url[0]);
            int count;
            File finalFile = new File(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
            try {
                if (!finalFile.exists()) {
                    Log.i(Constants.LOG_TAG, CLASS_NAME + " Donwloading apk from the Web");
                    URL url = new URL(_url[0]);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();
                    // this will be useful so that you can show a tipical 0-100%
                    // progress bar
                    int lenghtOfFile = conexion.getContentLength();
                    // downlod the file
                    InputStream input = new BufferedInputStream(url.openStream());
                    File dir = new File(sdcardPath + Constants.APK_LOCAL_PATH);
                    if (!dir.exists())
                        dir.mkdirs();
                    OutputStream output = new FileOutputStream(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } else {
                    Log.i(Constants.LOG_TAG, CLASS_NAME + " Apk in SDcard");
                    publishProgress(100);
                }
            } catch (Exception e) {
            }

            return null;

        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            Intent i = new Intent();
            i.setAction(CUSTOM_INTENT);
            i.setFlags(progress[0]);
            ctx.sendBroadcast(i);
        }
    }

    private String splitName(String url) {
        String[] output = url.split("/");
        return output[output.length - 1];
    }

    public static final String CUSTOM_INTENT = "es.tempos21.sync.client.ProgressReceiver";

    private final IDownloadService.Stub mBinder = new IDownloadService.Stub() {

        public void downloadAsynFile(String url) throws DeadObjectException {
            try {
                DownloadFile d = new DownloadFile();
                d.execute(url);
            } catch (Exception e) {
                Log.e(Constants.LOG_TAG, CLASS_NAME + " " +e.getMessage());         }
        }


        }
};


interface IDownloadService {

    void downloadAsynFile(String url);    
}

答案 1 :(得分:9)

Service通知当时正在运行的Activity来自onProgressUpdate()的进度。这可以通过广播Intent,或通过Activity注册的回调对象(当Activity被销毁时未注册,例如在屏幕上旋转)。

答案 2 :(得分:0)

您可以通过Toast轻松显示进度,这可以避免所有UI问题:

public class foo extends Service {
private Toast toast;

@SuppressLint("ShowToast")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    ctxt = getApplicationContext();
    toast = Toast.makeText(ctxt, "", Toast.LENGTH_SHORT);
    ...
}

public void functionCalledByYourAsyncWithUpdates(String progress){
    toast.setText (progress);
    toast.show;
}
}