2014-08-29 130 views
0

我试图做一个方法来下载文件,但在请求中的方法中,它有一个函数调用,显示下载通知。问题是我的应用程序所需的最低api是API 9,并且IDE向我显示错误,因为setNotificationVisibility适用于API 11及更高版本。如何避免API级别警告?

这是我的源代码:

public void init_download(String title, String filename, String url) { 
     File path = new File(Environment.DIRECTORY_DOWNLOADS); 

     if (!path.exists()) { 
      path.mkdirs(); 
     } 

     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(title) 
       .setDescription(getResources().getString(R.string.downloading)) 
       .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); 
       .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 

     long id = downloadManager.enqueue(request); 

     //Save the request id 
     SharedPreferences.Editor PrefEdit = shared_pref.edit(); 
     PrefEdit.putLong("DOWNLOAD_ID", id); 
     PrefEdit.commit(); 
    } 

我该如何解决这两个版本中运行的通知?

谢谢。

回答

3

添加@SuppressLint("NewApi")您functioin的声明,这是:

@SuppressLint("NewApi") 
public void init_download(String title, String filename, String url) { 

} 
1

你能解决这个警告与@SuppressLint("NewApi")但在较低的API的你setNotificationVisibility将无法工作,因为在支持软件包没有下载管理器。

+0

另一个问题是通知只显示几毫秒,但它不会保留在状态栏中。 – MAOL 2014-08-29 09:48:58

1

我已经改变通知的可视性解决了最后一个问题:

public void init_download(String title, String filename, String url) { 
     File path = new File(Environment.DIRECTORY_DOWNLOADS); 

     if (!path.exists()) { 
      path.mkdirs(); 
     } 

     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(title) 
       .setDescription(getResources().getString(R.string.downloading)) 
       .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
     } 
     else { 
      request.setShowRunningNotification(true); 
     } 

     long id = downloadManager.enqueue(request); 

     //Save the request id 
     SharedPreferences.Editor PrefEdit = shared_pref.edit(); 
     PrefEdit.putLong("DOWNLOAD_ID", id); 
     PrefEdit.commit(); 
    } 

这是将文件下载到Android设备的下载目录。

1

您应该在您的方法之前添加@SuppressLint("NewApi")。但是最好升级min sdk版本或者不要使用这种方法。如果您添加@SuppressLint("NewApi"),请不要忘记可以使用9 api在设备上运行应用程序的用户。