2016-11-25 61 views
0

所以我一直在練習下載管理器,我正在嘗試一些程序。 第一個按鈕會將所述Pdf下載到手機中的某個位置。 第二個按鈕應該打開用戶安裝的PDF閱讀器,如WP閱讀器等PDF文件的PDF文件。 下載工作正常,但是當我打開PDF時,它說無效的格式。 我上傳了一個樣本Pdf到谷歌驅動器,所以我知道上傳的文件在任何情況下都沒有損壞。當從服務器下載文件時,會有一些問題。請幫我找到錯誤。我對Android比較陌生。從內部存儲器加載PDF錯誤無效格式

下載按鈕使用Onclicklistener,而loadPdf在xml文件android:onClick =「downloadPdf」中給出。

public class MainActivity extends AppCompatActivity { 

String myHTTPUrl = "https://drive.google.com/open?id=0B5Pev9zz5bVjZTFFZ1dLZVp1WVU"; 
String TAG = "My app"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Button download = (Button) findViewById(R.id.download); 


    download.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      Log.v(TAG,"download method called"); 
      downloadPdf(); 

      Toast.makeText(MainActivity.this,"Listener Called",Toast.LENGTH_SHORT).show(); 
      Log.v(TAG,"On Click Listener Called"); 

     } 
    }); 

} 


public void loadPdf(View view) { 

    Log.v(TAG,"Pdf load called"); 

    File pdfFile = new File(Environment.getExternalStorageDirectory()+"/notes","ssp.pdf"); 
    if(pdfFile.exists()) 
    { 
     Uri path = Uri.fromFile(pdfFile); 
     Intent pdfIntent = new Intent(Intent.ACTION_VIEW); 
     pdfIntent.setDataAndType(path, "application/pdf"); 
     pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     Intent intent = Intent.createChooser(pdfIntent, "Open File"); 
     try 
     { 
      startActivity(intent); 
     } 
     catch(ActivityNotFoundException e) 
     { 
      Toast.makeText(MainActivity.this, "No Application available to view pdf", Toast.LENGTH_LONG).show(); 
     } 
    } 
    else 
    { 
     Toast.makeText(MainActivity.this,"Pdf not found",Toast.LENGTH_SHORT).show(); 
    } 


} 

public void downloadPdf() 
{ 
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myHTTPUrl)); 
    request.setTitle("Solid State Physics"); 
    request.setDescription("File is being Downloaded..."); 
    request.allowScanningByMediaScanner(); 
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
    request.setDestinationInExternalPublicDir("/notes","ssp.pdf"); 
    manager.enqueue(request); 

}} 

編輯: 這是我面臨的截圖 錯誤確切的錯誤:文件格式錯誤,不能將其打開 Screenshot of the error

回答

0

您未下載PDF,您正在下載顯示PDF內容的網頁。如果要直接下載PDF文件,請使用以下URL:

String myHTTPUrl = "https://drive.google.com/uc?export=download&id=0B5Pev9zz5bVjZTFFZ1dLZVp1WVU"; 

並且您的應用程序應該可以正常工作。

(不要忘記先刪除無效notes/ssp.pdf文件,否則將DownloadManager下載的文件以不同的名稱,如notes/ssp-1.pdf)。