0

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

Tashila Pathum
  • 109
  • 2
  • 11

1 Answers1

1

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;
  }
}
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
  • 1
    Sorry for late reply. I'm not active on this site. I didn't exactly use your answer but it gave me the idea to split methods into parts and get around the problem. So thanks! :) – Tashila Pathum Dec 02 '19 at 19:03