2016-11-09 90 views
2

我遵循教程如何製作下載.pdf文件的應用程序。下載管理器無法解析getSystemService

下面的代碼:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_vertretungsplan); 
    Button dlbutton = (Button) findViewById(R.id.buttondownload); 
    dlbutton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myurl)); 
      request.setTitle("Vertretungsplan"); 
      request.setDescription("wird heruntergeladen"); 
      request.allowScanningByMediaScanner(); 
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
      String filename = URLUtil.guessFileName(myurl,null, MimeTypeMap.getFileExtensionFromUrl(myurl)); 
      request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "Schul-App",filename); 
      DownloadManager manager =(DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE); 
      manager.enqueue(request); 
     } 
    }); 

它顯示了我的錯誤:

Cannot resolve method 'getSystemService(java.lang.string)'

+0

能使用'getSystemService'沒有'this'前綴。 –

回答

2

this指的是你正在使用的對象,因爲它裏面View.OnClickListener它指的是對象,而不是你的Activity類。

像這樣的東西應該做

final Context c = this; 
dlbutton.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     //... 
     DownloadManager manager =(DownloadManager) c.getSystemService(Context.DOWNLOAD_SERVICE); 
     manager.enqueue(request); 
    } 
});