Загрузить файл с BroadcastReceiver в Android Studio - PullRequest
0 голосов
/ 10 апреля 2019

Я хочу скачать базу файлов по URL в функции Android.file_download, имеющую два параметра: URL и имя файла после загрузки в память. после нажатия на кнопку это тост ERROR_FILE_ERROR. Как я могу запустить это правильно? правильный BroadcastReceiver? путь загрузки / правильный?

Это явное разрешение

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

Это mainActivity

public class MainActivity extends AppCompatActivity {
    TextView txt;
    Button dow;
    public static long  downloadID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dow = (Button) findViewById(R.id.dow);
        txt = (TextView) findViewById(R.id.txt);

        MainActivity.this.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        dow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try{

                    file_download("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png",
                            "abcdef789");

                }catch (Exception e) {
                }

            }
        });

    } //oncreate

    DownloadManager mgr;
    public void file_download(String uRl,  String mee) {
        try{
            if(true){
                File direct = new File(Environment.getExternalStorageDirectory()
                        + "/download");
                if (!direct.exists()) {
                    direct.mkdirs();
                }
                mgr = (DownloadManager) MainActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
                Uri downloadUri = Uri.parse(uRl);
                DownloadManager.Request request = new DownloadManager.Request(
                        downloadUri);
                request.setAllowedNetworkTypes(
                        DownloadManager.Request.NETWORK_WIFI
                                | DownloadManager.Request.NETWORK_MOBILE)
                        .setAllowedOverRoaming(false).setTitle("Download file ....")
                        .setDescription("Something useful. No, really.")
                        .setDestinationInExternalPublicDir("/download", mee);
                downloadID = mgr.enqueue(request);
            }//if
        }catch (Exception e){
        }
    }//file_download


    BroadcastReceiver onComplete=new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {

            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0L);
            if(id != downloadID){
                Toast.makeText(MainActivity.this , "NO Message"  , Toast.LENGTH_LONG).show();
            }
            else
            {
                CheckDwnloadStatus();
            }//else

        }
    };


    private void CheckDwnloadStatus()
    {
        // TODO Auto-generated method stub
        DownloadManager.Query query = new DownloadManager.Query();
        //  long id = preferenceManager.getLong(strPref_Download_ID, 0);
        query.setFilterById(downloadID);

        Cursor cursor = mgr.query(query);
        if(cursor.moveToFirst()){
            int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            int status = cursor.getInt(columnIndex);
            int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
            int reason = cursor.getInt(columnReason);
            switch(status){
                case DownloadManager.STATUS_FAILED:
                    String failedReason = "";
                    switch(reason){
                        case DownloadManager.ERROR_CANNOT_RESUME:
                            failedReason = "ERROR_CANNOT_RESUME";
                            break;
                        case DownloadManager.ERROR_DEVICE_NOT_FOUND:
                            failedReason = "ERROR_DEVICE_NOT_FOUND";
                            break;
                        case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
                            failedReason = "ERROR_FILE_ALREADY_EXISTS";
                            break;
                        case DownloadManager.ERROR_FILE_ERROR:
                            failedReason = "ERROR_FILE_ERROR";
                            break;
                        case DownloadManager.ERROR_HTTP_DATA_ERROR:
                            failedReason = "ERROR_HTTP_DATA_ERROR";
                            break;
                        case DownloadManager.ERROR_INSUFFICIENT_SPACE:
                            failedReason = "ERROR_INSUFFICIENT_SPACE";
                            break;
                        case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
                            failedReason = "ERROR_TOO_MANY_REDIRECTS";
                            break;
                        case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
                            failedReason = "ERROR_UNHANDLED_HTTP_CODE";
                            break;
                        case DownloadManager.ERROR_UNKNOWN:
                            failedReason = "ERROR_UNKNOWN";
                            break;
                    }
                    Toast.makeText(MainActivity.this, "FAILED: " + failedReason,Toast.LENGTH_LONG).show();
                    break;
                case DownloadManager.STATUS_PAUSED:
                    String pausedReason = "";

                    switch(reason){
                        case DownloadManager.PAUSED_QUEUED_FOR_WIFI:
                            pausedReason = "PAUSED_QUEUED_FOR_WIFI";
                            break;
                        case DownloadManager.PAUSED_UNKNOWN:
                            pausedReason = "PAUSED_UNKNOWN";
                            break;
                        case DownloadManager.PAUSED_WAITING_FOR_NETWORK:
                            pausedReason = "PAUSED_WAITING_FOR_NETWORK";
                            break;
                        case DownloadManager.PAUSED_WAITING_TO_RETRY:
                            pausedReason = "PAUSED_WAITING_TO_RETRY";
                            break;
                    }

                    Toast.makeText(MainActivity.this,"PAUSED:" + pausedReason,Toast.LENGTH_LONG).show();
                    break;
                case DownloadManager.STATUS_PENDING:
                    Toast.makeText(MainActivity.this,"PENDING",Toast.LENGTH_LONG).show();
                    break;
                case DownloadManager.STATUS_RUNNING:
                    Toast.makeText(MainActivity.this,"RUNNING", Toast.LENGTH_LONG).show();
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    Toast.makeText(MainActivity.this, "Download is  SUCCESSFUL" ,Toast.LENGTH_LONG).show();
                    txt.setText(" Download is  SUCCESSFUL  ");
                    break;
            }
        }
    }

}//class
...