Mark Witt Mark Witt - 26 days ago 30
Android Question

Android Programming Download Manager Cannot resolve getSystemService

In my Code on the latest Android Studio, I followed a tutorial how to moke 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)'
Sorry for my bad English

Answer

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

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