下载后的BroadcastReceiver和打开文件

时间:2018-07-26 12:53:56

标签: android android-intent broadcastreceiver android-download-manager

我正在处理一个项目,需要正常下载文件,然后打开(通常在PDF阅读器中)。

我有一个看起来像这样的广播接收器类

public class DownloadBroadcastReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    String action = intent.getAction();
    if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
    {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));
        DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Cursor cursor = manager.query(query);
        if (cursor.moveToFirst()) {
            if (cursor.getCount() > 0) {

                int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                Long download_id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0);
                String downloadFilePath = null;
                String downloadFileLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                File file = new File(Uri.parse(downloadFileLocalUri).getPath());
                // status contain Download Status
                // download_id contain current download reference id

                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    String fname=cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
                    File pdfFile = new File(Environment.getExternalStorageDirectory()+"/Downloads/"+fname);//File path
                    if (pdfFile.isFile()) //Checking if the file exists or not
                    {
                        Uri path = Uri.fromFile(pdfFile);
                        Intent objIntent = new Intent(Intent.ACTION_VIEW);
                        objIntent.setDataAndType(path, "application/pdf");
                        objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(objIntent);//Starting the pdf viewer
                    } else {
                        Log.d("OO",Environment.getExternalStorageDirectory()+"/Downloads/"+fname);
                        Log.d("OO",fname);
                       // Toast.makeText(getApplicationContext(),"Test",Toast.LENGTH_LONG).show();

                    }
                }
            }
        }
        cursor.close();
    }
}

}

清单看起来像这样

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="uk.org.bridgewaterha.boardapp">

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".pdf"></activity>
    <receiver android:name=".DownloadBroadcastReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
        </intent-filter>
    </receiver>
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

</manifest>

路径文件如下

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="Download" path="."/>
    <cache-path name="cache" path="/" />
</paths>

我遇到的问题是在广播接收器类中,

if (pdfFile.isFile())

始终返回false。

我尝试了一些在网络上遇到的变体,但似乎根本没有用。

任何提示都非常感谢。

1 个答案:

答案 0 :(得分:0)

下载后,您必须检查文件是否为mFile.exists()...

使用此打开pdf文件:

  

我认为您的应用程序默认行为不是直接打开它。   所以我们需要使用选择器

Intent myIntent = new Intent(Intent.ACTION_VIEW);
        myIntent.setData(Uri.fromFile(file));
        Intent j = Intent.createChooser(myIntent, "Choose an application to open with:");
        startActivity(j);

   while (cursor.moveToNext()) {
        if (cursor.getCount() > 0) {
            Log.e("filelistingloop","loopfollowingss      "+cursor.getCount());
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            if (status == DownloadManager.STATUS_SUCCESSFUL) {
                String file = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                if (file != null) {
                    File mFile = new File(Uri.parse(file).getPath());
                    final String fileName = mFile.getAbsolutePath().substring(mFile.getAbsolutePath().lastIndexOf('/') + 1, mFile.getAbsolutePath().length());
                    if (mFile.exists()){
                        Toast.makeText(yourActivit.this,"  File  donwloaded successfully",Toast.LENGTH_LONG).show();
                            //here you can open your pdf 
                    }
                }
                // So something here on success
            }else if (status == DownloadManager.STATUS_FAILED){
                int message = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
                // So something here on failed.
                Toast.makeText(getActivity(),"File Not donwloaded   "+  message,Toast.LENGTH_LONG).show();
            }
        }
    }