如何在android中添加下载计数器(下载次数)?

时间:2017-04-20 11:16:34

标签: android download

我正在构建一个用户可以下载壁纸或直接将其保存到桌面的应用程序。

我现在要做的是在Textview中添加下载计数器或下载次数,这将显示该特定图像的下载总次数。换句话说,其他用户下载特定图像的次数。

我不知道该怎么做,我猜我可以使用谷歌分析,但有没有办法不使用任何图书馆或服务?

3 个答案:

答案 0 :(得分:0)

  1. 创建一个静态整数变量。
  2. 每次下载开始都会增加计数器
  3. 每次完成下载或错误都会减少计数器。
  4. 因此,计数器将为您提供准确的正在进行的图像下载。

答案 1 :(得分:0)

此方法允许您同时执行一些后台进程并更新UI(在这种情况下,我们将更新进度条)。

这是一个示例代码:

//将对话框声明为活动的成员字段

ProgressDialog mProgressDialog;

// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);

//必须触发下载程序时执行此操作 finalTall downloadTask = new DownloadTask(YourActivity.this); downloadTask.execute("你要下载的文件的网址");

mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){     @覆盖     public void onCancel(DialogInterface dialog){         downloadTask.cancel(真);     } }); AsyncTask看起来像这样:

//通常,AsyncTask的子类在activity类中声明。 //这样,你可以从这里轻松修改UI线程 私有类DownloadTask扩展了AsyncTask {

 private Context context;
    private PowerManager.WakeLock mWakeLock;

    public DownloadTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/file_name.extension");

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }

上面的方法(doInBackground)总是在后台线程上运行。你不应该在那里做任何UI任务。另一方面,onProgressUpdate和onPreExecute在UI线程上运行,因此您可以更改进度条:

 @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user 
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
             getClass().getName());
        mWakeLock.acquire();
        mProgressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
    }

要运行此功能,您需要WAKE_LOCK权限。

<uses-permission android:name="android.permission.WAKE_LOCK" />

答案 2 :(得分:0)

这是一项非常直接的任务,您还必须在服务器端和设备端进行一些更改。

服务器端的更改
1.添加带有表的数据库,以记录图像详细信息,如image_url,image_name,image_id等(确保拥有合法的主键),然后添加最重要的内容,即下载次数。
2.在您要调用服务器以获取图像详细信息的API中,添加另一个下载次数参数 3.创建另一个端点以更新成功下载。

设备端的更改
1.下载成功后,调用新API,以便服务器更新数据库中的下载次数 2.现在这是有趣的部分,如果您的下载成功,那么在textview中,您应该增加之前从服务器收到的下载次数。
3.如果您希望下载计数是动态的,也就是说,如果您想在每次有人下载图像时更新下载次数,那么您可以使用 Firebase动态数据库

使用Firebase动态数据库的步骤
1. Firebase动态数据库是免费的,如果你使用它,你不必像我在上面的步骤中提到的那样将任何数据库添加到你的服务器。
3. Firebase DB实现起来并不复杂,因此请花些时间了解它为它设计架构 4. Firebase DB具有以下功能:任何具有访问权限的客户端都可以更新数据库中的值,并且此更新将自动通知给在DB上具有侦听器的其他客户端。此功能可让您在不进行服务器调用的情况下获得最新的下载次数 5.最重要的一步是,下载成功后,更新Firebase动态数据库,以便所有客户都收到可用于更新TextView的最新值的通知

  

我建议您使用Firebase数据库,因为它很快,您不必在服务器上执行其他工作,和最重要的部分,将来如果您想要将推送通知添加到您的应用中,您可以使用同样的Firebase项目也可以添加推送通知。