【问题标题】:Download Manager Sometimes Displays Unsuccessful下载管理器有时显示不成功
【发布时间】:2020-04-05 10:01:12
【问题描述】:

正如标题所说,我有一个下载管理器,它可以工作,但只是有时。这很奇怪,我找不到模式。我有一个按钮,单击该按钮时,会向服务器发送请求,该服务器返回要下载的文件,然后有时会下载,有时则不会。我看不到任何模式,也没有从电话或服务器收到任何错误。

这对我的应用程序不利,因为我需要知道它是否已成功下载,因此我要么需要找出它有时无法正常工作的原因,要么在下载失败时找到运行函数的方法。这是我用来下载文件的代码:

        GlobalVariables globalVariables = new GlobalVariables();
        String url = globalVariables.getIPAddress() + "downloadsong/" + Integer.toString(songId) + "/";
        SharedPreferences sharedPreferences = getSharedPreferences("StoredValues", MODE_PRIVATE);
        String token = sharedPreferences.getString("token", "null");

        DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle("Downloading");
        request.setDescription("Downloading new titles");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, "" + songId + ".mp3");
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.addRequestHeader("Authorization", "Token " + token);
        request.allowScanningByMediaScanner();
        request.setAllowedOverMetered(true);
        request.setAllowedOverRoaming(true);

        long downloadReference = downloadManager.enqueue(request);
        if (downloadReference != 0) {
            Toast.makeText(getApplicationContext(), "download started", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(getApplicationContext(), "no download started", Toast.LENGTH_SHORT).show();
        }

感谢任何帮助或见解。谢谢!

【问题讨论】:

    标签: android download android-download-manager


    【解决方案1】:

    这是我的例子:

    public class MainActivity extends AppCompatActivity {
    
    private Button button;
    private long downloadID;
    
    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (downloadID == id) {
                validDownload(MainActivity.this, downloadID);
            }
        }
    };
    
    public void validDownload(Context context, long downloadId) {
        DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (dm != null) {
            try (Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId))) {
                if (c.moveToFirst()) {
                    int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    if (status == DownloadManager.STATUS_SUCCESSFUL) {
                        Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show();
                    } else if (status == DownloadManager.STATUS_FAILED) {
                        Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.download);
        registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                if (downloadManager != null) {
                    downloadID = downloadManager.enqueue(prepareDownloadRequest());
                }
            }
        });
    }
    
    private DownloadManager.Request prepareDownloadRequest() {
        File file = new File(getExternalFilesDir(null), "Dummy");
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://speedtest.ftp.otenet.gr/files/test10Mb.db"))
                .setTitle("Dummy File")
                .setDescription("Downloading")
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
                .setDestinationUri(Uri.fromFile(file))// Uri of the destination file
                .setAllowedOverMetered(true)
                .setAllowedOverRoaming(true);// Set if download is allowed on roaming networ
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            request.setRequiresCharging(false);
        }
        return request;
    }
    

    }

    【讨论】:

    • 这正是我所需要的。有什么方法可以根据 ID 重新开始下载吗?
    【解决方案2】:

    您必须注册一个广播接收器

    public static int validDownload(Context context, long downloadId) {
        //Verify if download is a success
        DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId));
    
        try {
            if (c.moveToFirst()) {
                int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
    
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    return 0; //Download is valid, celebrate
                } else {
                    return c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                }
            }
        } finally {
            c.close();
        }
    
        return -1; 
    }
    
    
    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
    
           //Fetching the download id received with the broadcast
           long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
    
           //Checking if the received broadcast is for our enqueued download by matching download id
           if (downloadID == id) {
               validDownload(this, id);
           }
    
       }
    

    };

    并在活动的 onCreate 方法中注册 ACTION_DOWNLOAD_COMPLETE。

      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
    

    【讨论】:

    • 如何将它与我已有的代码一起使用?抱歉给您添麻烦
    • 另外,我在哪里输入downloadId
    • 您的downloadReference 是downloadId。您必须注册接收者并调用您的代码。
    • 好吧,我输入了你的代码,但我仍然无法弄清楚如何将BroadcastReceiver 与我的DownloadManager 一起使用。我在 onReceive 覆盖中的 downloadId 上收到“无法解析符号”
    • 我给你写了一个例子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 2013-01-25
    • 2014-02-23
    • 1970-01-01
    相关资源
    最近更新 更多