Search code examples
javaandroidandroid-activityviewjobservice

How to call a method from MainActivity which takes views as parameters, from a class which extends JobService?


I want to execute this method which is in MainActivity...

public void checkNow(View view) {
        new Thread(() -> {

            //codes...

            EditText getSite = findViewById(R.id.site);
            site = getSite.getText().toString();

            //codes...

            Toast.makeText(this, "Connecting...", Toast.LENGTH_SHORT).show();

            new MovieAsyncTask().execute(movie, url, site);

        }).run();
    }

...from the following class

public class MovieUpdatesService extends JobService {

    private static final String TAG = "MovieUpdatesService";
    private boolean jobCancelled = false;

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.d(TAG, "Job started");
        doBackgroundWork(params);
        return true;
    }

    public void doBackgroundWork(final JobParameters params) {
        if (jobCancelled)
            return;

        //call checkNow() method here

        Log.d(TAG, "Job finished");
        jobFinished(params, false);
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.d(TAG, "Job cancelled before completion");
        jobCancelled = true;
        return true;
    }
}

I want to call checkNow(View view) but I don't know how to access those views from this class. I tried using interface but I can't understand how to make it work in my case. I'm new to android so I'm looking for a simple solution if possible


Solution

  • To allow your service to save the value of the textview, you could add a member variable. Then you could expose a setter method for this string.

    public class MovieUpdatesService extends JobService {
    
    private static final String TAG = "MovieUpdatesService";
    private boolean jobCancelled = false;
    private String siteDetails = "";  <----
    
    //Use this method from the Activity
    public void setSiteDetails(String _siteDetails) {
      siteDetails = _siteDetails
    }
    
    @Override
    public boolean onStartJob(JobParameters params) {
        Log.d(TAG, "Job started");
        doBackgroundWork(params);
        return true;
    }
    
    public void doBackgroundWork(final JobParameters params) {
        if (jobCancelled)
            return;
    
        //use siteDetails here
    
        Log.d(TAG, "Job finished");
        jobFinished(params, false);
    }
    
    @Override
    public boolean onStopJob(JobParameters params) {
        Log.d(TAG, "Job cancelled before completion");
        jobCancelled = true;
        return true;
      }
    }