本地广播管理器用于下载文件

时间:2013-12-10 10:40:47

标签: android android-asynctask android-broadcast

我正在创建一个本地广播接收器,用于在下载开始和完成时通知活动。我有两个类,一个是我调用下载某个文件的DownloadFileFromURL类,在其中我定义了这个:

Intent intent = new Intent("completeDownloadItem");
        // You can also include some extra data.
        intent.putExtra("completedItem", suraName);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

我认为应该向我的具有以下代码的DownloadManager类发送广播:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download_manager);
        LocalBroadcastManager.getInstance(this).registerReceiver(itemReceiver,
                new IntentFilter("addDownloadItem"));
        LocalBroadcastManager.getInstance(this).registerReceiver(
                completeReceiever, new IntentFilter("completeDownloadItem"));

    }

    private BroadcastReceiver itemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            Songs s = (Songs) intent.getSerializableExtra("newItems");
            Log.d("receiver", "Got song: " + s.getTitle());
        }
    };
    private BroadcastReceiver completeReceiever = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            String message = intent.getStringExtra("completedItem");
            Log.d("receiver", "Downloaded: " + message);
        }
    };

任何人都能告诉我我错过了什么,我应该在清单中定义本地广播接收器吗?

这是DownloadFileFromURL类:

public class DownloadFileFromURL extends AsyncTask<String, String, String> {

    private Context context;
    private ProgressDialog dialog;
    private String reciterName, suraName;
    private String file_url, filePath;
    private MediaScannerConnection msc;
    private DatabaseHelper db;
    private int songNumber;

    public DownloadFileFromURL(Context context, String reciterName,
            String suraName, String fileURL, int songNumber) {
        this.context = context;
        this.songNumber = songNumber;
        this.reciterName = reciterName;
        this.suraName = suraName;
        this.file_url = fileURL;
        db = new DatabaseHelper(context);
    }

    protected void createDialog() {
        // switch (id) {
        // case progress_bar_type: // we set this to 0
        dialog = new ProgressDialog(context);
        // dialog.setMessage(context.getString(R.string.downloading) + " "
        // + songName);
        /*
         * dialog.setIndeterminate(false); dialog.setMax(100);
         */
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);
        dialog.show();
        // default:
        // return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // createDialog();
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(file_url);
            URLConnection conection = url.openConnection();
            conection.connect();
            // this will be useful so that you can show a tipical 0-100%
            // progress bar
            int lenghtOfFile = conection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream
            File appDir = new File(Environment.getExternalStorageDirectory()
                    .getPath() + "/" + context.getString(R.string.app_name));
            appDir.mkdirs();
            File albumDir = new File(appDir.getPath().toString() + "/"
                    + reciterName);
            albumDir.mkdirs();
            OutputStream output = new FileOutputStream(appDir + "/"
                    + reciterName + "/" + suraName + ".mp3");
            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        // dialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String file_url) {
        msc = new MediaScannerConnection(context,
                new MediaScannerConnection.MediaScannerConnectionClient() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        msc.disconnect();
                    }

                    @Override
                    public void onMediaScannerConnected() {
                        msc.scanFile(filePath, null);
                    }
                });
        if (!msc.isConnected()) {
        }
        // dialog.dismiss();
        db.openDB();
        db.addDownloaded(songNumber, reciterName);
        db.closeDB();
        Intent intent = new Intent("completeDownloadItem");
        // You can also include some extra data.
        intent.putExtra("completedItem", suraName);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        Toast.makeText(context, "Sucessfully downloaded " + suraName,
                Toast.LENGTH_SHORT).show();

    }

}

1 个答案:

答案 0 :(得分:0)

不,不需要在AndroidManifest.xml中配置本地广播接收器。我不得不说我有点疑惑为什么通知不起作用;您是否调试过代码并检查广播是否实际发送以及接收器是否已正确注册?

如果您无法正常工作(无论出于何种原因),请考虑使用EventBus之类的库来满足您的组件间通信需求。就个人而言,我还没有使用LocalBroadcastManager年龄......