Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It sounds like what you need to do is to be able to "bind" to your service. What I have posted below is a simple template of how to do that. For your purposes you will need to store variables in your Service class and create getters so that when you re-launch your activity you can get the most up to date variables. Also - please note that I start and stop the Service example below in onResume and onPause. You will no doubt want to do this differently.</p> <pre><code>//Activity //Bind to Service Example public class ExampleActivity extends Activity implements OnClickListener { // UI private Button binderButton; // service private MyService myService; private Intent serviceIntent; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout); // binder button binderButton = (Button) findViewById(R.id.button1); binderButton.setOnClickListener(this); binderButton.setText("start"); serviceIntent = new Intent(this, MyService.class); } private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { myService = ((MyService.MyBinder) service).getService(); } @Override public void onServiceDisconnected(ComponentName name) { myService = null; } }; @Override protected void onResume() { super.onResume(); // start the service startService(serviceIntent); // bind to the service bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: // call method within the service myService.doServiceStuff(); break; } } @Override protected void onPause() { super.onPause(); stopService(serviceIntent); unbindService(serviceConnection); } } </code></pre> <hr> <pre><code>//Service public class MyService extends Service { private final IBinder binder = new MyBinder(); @Override public IBinder onBind(Intent arg0) { return binder; } public void doServiceStuff() { task.execute(); } // create an inner Binder class public class MyBinder extends Binder { public MyService getService() { return MyService.this; } } AsyncTask&lt;Void, Void, Void&gt; task = new AsyncTask&lt;Void, Void, Void&gt;() { @Override protected Void doInBackground(Void... params) { Log.d("yourTag", "long running service task"); return null; } }; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload