Search code examples
javaandroidandroid-download-manager

Download Manager Cannot resolve getSystemService


I followed a tutorial how to make an App that downloads a .pdf file.

Here's the code:

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);
        }
    });

It shows me the error:

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


Solution

  • this refers to the object you're working with, since it's inside View.OnClickListener it refers to that object instead of your Activity class.

    Something like this should do

    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);
        }
    });