Android 下载后广播接收器并打开文件

Android 下载后广播接收器并打开文件,android,android-intent,broadcastreceiver,android-download-manager,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 =

我有一个项目,我正在工作,需要一个文件正常下载,然后打开(通常在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>
总是返回false

我尝试了一些在网络上遇到的变体,但似乎没有一个是有效的


非常感谢任何提示。

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

使用此选项打开pdf文件:

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



使用file.exists()方法检查它是否存在。@Stephen MCGinley如果有任何问题,请告诉我
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="Download" path="."/>
    <cache-path name="cache" path="/" />
</paths>
if (pdfFile.isFile())
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();
            }
        }
    }