Service: starting a bound service - android

I'm kind of confused with bound services. I read Can anybody explain what is difference between unbound and bound service in android this post and based on that I'm trying out a sample. I created a Service and binding it to My activity as shown below
public class MyService extends Service {
private static final String TAG = "MyService";
MyBinder mMyBinder = new MyBinder();
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
// start long running operation
return super.onStartCommand(intent, flags, startId);
}
#Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind: ");
return super.onUnbind(intent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return mMyBinder;
}
public class MyBinder extends Binder {
public MyService getService(){
return MyService.this;
}
}
}
Activity is
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
MyService.MyBinder mMyBinder;
private Connect mConn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, MyService.class);
mConn = new Connect();
bindService(intent, mConn, BIND_AUTO_CREATE);
}
public class Connect implements ServiceConnection {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "onServiceConnected: ");
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "onServiceDisconnected: ");
}
}
}
The service 'onStartCommand' is not called when I call bindService(intent, mConn, BIND_AUTO_CREATE);
should I call startService after binding? binding will not start the service?
If I already have a service which is started using startService and running , and I'm bindind the same service in some other activity, what happens if activity goes out of scope?

Related

Start and stop service

I have a code like this, which run, when click the button
if (isMyServiceRunning(PlayerService.class)) {
stopService(mIntent);
unbindService(serviceConnection);
} else {
startService(mIntent);
bindService(mIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
When I click button and my service do not running, service start to work( all good here)
When I click button and my service running, service stop and destroy( all good here)
but when I click, to service start to work, service do not working
My Service
public class PlayerService extends Service {
private final IBinder binder = new LocalBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
doAnything();
return START_STICKY;
}
public class LocalBinder extends Binder {
PlayerService getService() {
return PlayerService.this;
}
}
}
Service Connection
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
PlayerService.LocalBinder binder = (PlayerService.LocalBinder) service;
myService = binder.getService();
Log.d("TEST", "MainActivity onServiceConnected");
bound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
Log.d("TEST", "MainActivity onServiceDisconnected");
bound = false;
}
};

Service killed before starting loop

I am new in android development. My service killed before starting loop..
I started service from another activity like MainActivity
package com.example.ch_m_usman.sharedtasklist.Services;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class ReminderService extends IntentService {
public ReminderService() {
super("Reminder Service");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.e("check","")
//Loop does not start.
for (int i=0;i<5;i++){
Log.e("Inside for","");
}
}
}
//How to use loop in intent service
Use below code:
public class TaskConfirm extends IntentService {
private final IBinder mBinder = new LocalBinder();
public TaskConfirm() {
super("TaskConfirm");
setIntentRedelivery(true);
}
#Override
public void onCreate() {
super.onCreate();
//Initilise your objects here like below...
taskIdList=new ArrayList<String>();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return super.onStartCommand(intent, flags, startId);
}
#Override
protected void onHandleIntent(Intent intent) {
// get intent data here like below if required......
if (intent != null) {
String taskId=intent.getStringExtra("taskId");
}
// apply your loop here .......
for (int i=0;i<5;i++){
Log.e("Inside for","");}
}
public class LocalBinder extends Binder {
public TaskConfirm getService() {
return TaskConfirm.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
Start service like below from your activity :
Intent serviceIntent = new Intent(context, TaskConfirm.class);
// put some extra data if required
serviceIntent.putExtra("taskId","1");
startService(serviceIntent);
If you want to access this service in other activity then bind that activity to service:
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, TaskConfirm.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
TaskConfirm.LocalBinder binder = (TaskConfirm.LocalBinder) service;
mService = binder.getService();
mBound = true;
// do your task on service-connected...
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};

Android, why is background thread stopped?

MainActivity starts my TestService in onCreate and bind in onStart method. AsyncThread is started in TestService onStartCommand. bind and unbind methods are called in correct sequences. All things work perfectly, absolutely no issue :).
Issue starts from here: If MainActivity is terminated then running Async thread is also stopped w/o any interrupt exception but TestService is still running which I can check at Running Application Setting.
Please help me to find out why thread stops working.
PS: I cross checked with Thread/Handler but same result.
MainActivity and Service code are here:
public class MainActivity extends Activity implements IServiceInterface {
boolean mBound = false;
TestService mTestService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent serviceIntent = new Intent(this, TestService.class);
startService(serviceIntent);
}
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
NSLogger.i("service binding....");
Intent intent = new Intent(this, TestService.class);
bindService(intent, mBindConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
NSLogger.i("service unbinding....");
unbindService(mBindConnection);
mBound = false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mBindConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
NSLogger.i("UI is connected to service");
LocalBinder binder = (LocalBinder) service;
mTestService = binder.getTestService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
NSLogger.i("UI is disconnected from service");
mBound = false;
mTestService = null;
}
};
}
public class TestService extends Service implements Runnable, Handler.Callback{
// Binder given to inproc clients
private final IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
mUIIsBound = true;
return mBinder;
}
public boolean onUnbind (Intent intent) {
mUIIsBound = false;
NSLogger.i("unbind service");
return true;
}
public class LocalBinder extends Binder {
TestService getTestService() {
return TestService.this;
}
}
public void onDestroy() {
//NEVER CALLED.
}
public int onStartCommand(Intent intent2, int flags, int startId) {
NSLogger.i("TestService start!");
new DownloadConfiguration().execute();
return START_STICKY;
}
private class DownloadConfiguration extends AsyncTask<Void, Integer, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
NSLogger.i("before sleep");
Thread.sleep(5000);
NSLogger.i("After sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}

Update service running on background

I need to implement such a procedure:
Start a background service
Update the service with parameters (from UI - user input)
After activity ended the service should keep on running and preform requests to HTTP server every minute. in this stage i still need the parameters I updated in the second stage - I send them to the server.
The service should store the server last response and compere each with the last. if there is a change, notify the user.
Finally, when the activity starts again, the service should update UI with latest the server response.
What I tried:
BroadcastReciver - The problem is after onRecive ended all the arguments which aren't declared as final will wipe out, as well as I didn't found a way to update the Intent being sent automatically every minute.
Service - Using startService() - The problem is when the activity ended the service like stops and starts , flushing all it's arguments. and once again I didn't figured out how to update the arguments after the service is already started.
So how to handle such a situation?
Thanks.
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.
//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);
}
}
//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<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
Log.d("yourTag", "long running service task");
return null;
}
};
}
Thanks javaJoe, although your answer didn't solved my problem it gave me some a good ideas.
What I did:
in the Activity onCreate, check if my service is running, if so bind it else, create new one and bind it.
Transferring arguments between the Service and the Activity using setters and getters.
in the Activity onDestroy (the problem was that the service calls self Destory) the Activity sends the final arguments through Intent to a Broadcastreciver. The Broadcastreciver than starts the Service again, initiating it with the correct arguments.
I don't know if this architecture is ideal, i'd like to get some feedback.
Here is the code:
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set Service Intent
serviceIntent = new Intent(this, UpdateService.class);
if (isMyServiceRunning()) {
//Bind to the service
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}else{
updateService=new UpdateService();
//Start the service
startService(serviceIntent);
//Bind to the service
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (UpdateService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
updateService = ((UpdateService.MyBinder) service).getService();
//Set Initial Args
updateService.setParams(int arg0);
}
#Override
public void onServiceDisconnected(ComponentName name) {
updateService = null;
}
};
#Override
protected void onDestroy() {
//UnBind from service
unbindService(serviceConnection);
//Stop Service
stopService(serviceIntent);
//Prepare intent to broadcast reciver
Intent intent = new Intent(MainActivity.this,ServiceRunnerBCR.class);
intent.setAction(ServiceRunnerBCR.ACTION_SET_UpdateService);
intent.putExtra(ServiceRunnerBCR.keyVal_arg0, arg0);
intent.putExtra(ServiceRunnerBCR.keyVal_arg1, arg1);
//Send broadcast to start UpdateService after the activity ended
sendBroadcast(intent);
super.onStop();
}
Broadcastreciver:
public class ServiceRunnerBCR extends BroadcastReceiver {
public static final String ACTION_SET_UpdateService = "ACTION_ALARM";
public static final String keyVal_arg0="ARG0";
public static final String keyVal_arg1="ARG1";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_SET_UpdateService)){
updateIntent(context, intent.getDoubleExtra(keyVal_arg0, 0.02), intent.getStringExtra(keyVal_arg1));
}
}
private void updateIntent(Context context, double arg0, String arg1){
Intent intent = new Intent(context,UpdateService.class);
intent.setAction(ACTION_SET_UpdateService);
intent.putExtra(keyVal_arg0, arg0);
intent.putExtra(keyVal_arg1, arg1);
synchronized (this){
try {
this.wait(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
context.startService(intent);
Log.d("OREN","ServiceRunner");
}
}
Service:
public class UpdateService extends Service {
private final IBinder binder = new MyBinder();
public static final String keyVal_arg0="ARG0";
public static final String keyVal_arg1="ARG1";
private Timer timer;
private HTTPHandler http = new HTTPHandler();
private int test=0;
double arg0=0;
String arg1= "";
private TimerTask updateTask = new TimerTask() {
#Override
public void run() {
test++;
Log.d("OREN", "Timer task doing work " + test + " arg0: " + arg0);
//Do some work here
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent!=null){
arg0=intent.getDoubleExtra(keyVal_arg0, 0.002);
arg1=intent.getStringExtra(keyVal_arg1);
timer = new Timer("UpdateTimer");
timer.schedule(updateTask, 1000L, 10 * 1000L);
Log.d("OREN", "ServiceStarted" + test);
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.d("OREN", "OnBind" + test);
return binder;
}
public void setArg0(double d){
arg0=d;
}
// create an inner Binder class
public class MyBinder extends Binder {
public UpdateService getService() {
return UpdateService.this;
}
}
#Override
public void onDestroy() {
Log.d("OREN", "OnDestroy" + test);
super.onDestroy();
}
#Override
public boolean onUnbind(Intent intent) {
Log.d("OREN", "OnUnBind" + test);
return super.onUnbind(intent);
}
}

Not able to get binder object from Service

I am receiving a boot completed intent in my BootReceiver class and start a service when I receive that intent.
#Override
public void onReceive(Context arg0, Intent arg1) {
Intent myIntent = new Intent(arg0, BootService.class);
arg0.startService(myIntent);
}
The service is started normally and now, I want to use the binder object within the service . Here is the service code.
public class BootService extends Service implements IBinder{
private IBinder binder;
public class LocalBinder extends Binder {
IBinder getService() {
return BootService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
Log.d("BootService", "onCreate()");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("BootService", "onStartCommand()");
binder = new LocalBinder().getService();
//This doesn't seem to work
//I wana use this binder object here
return START_STICKY;
}
.....
}
I am not sure if this is the correct way to get a binder.
Any help is much appreciated!!
In ur Acivity
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(getApplicationContext(), MyService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
unbindService(mConnection);
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(getApplicationContext(), "Service disconnected", 1000).show();
mBindr = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(getApplicationContext(), "Service connected", 1000).show();
LocalBinder mLocalBinder = (LocalBinder) service;
myService = mLocalBinder.getSrvice();
mBindr = true;
}
};
Update your code
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class BootService extends Service {
private IBinder binder = new LocalBinder();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return binder;
}
public class LocalBinder extends Binder {
BootService getService() {
return BootService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
Log.d("BootService", "onCreate()");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("BootService", "onStartCommand()");
//binder = new LocalBinder().getService();
//This doesn't seem to work
//I wana use this binder object here
return START_STICKY;
}
.....
}

Categories

Resources