Can I instantiate a bound service class in android by calling new? - android

Normal way of using a bound service:
private ServiceConnection musicConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
Intent playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
Instead of this, can't we use this:
MusicService music=new MusicService();
If yes, will there be any differences between the two instances obtained in two different ways?

Bind service or start service will result in a corresponding call to the target service's life cycle methods.
If this service is not already running, it will be instantiated and started (creating a process for it if needed); if it is running then it remains running.
New a service is just create a new object, means nothing, system knows nothing about it.
Just like activity, you cannot new a activity, you should start a activity, then ActivityManager will be response for create the Activity instance and calls its onCreate method.

Related

How to bind to a Service that was started by another instance of the application

I have a background Service that need to be running even if the application gets killed by Android. This is currently working perfectly.
My problem is that when I restart the application (with the background service still running), I want my Activity to bind to the service to have access to some of its methods. When I try to bind with a ServiceConnection, the onServiceConnected is never called.
final private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d(TAG, "onServiceConnected"); //this is never called
MyBackgroundService.ServiceBinder binder = (MyBackgroundService.ServiceBinder) service;
backgroundService = binder.getService();
}
public void onServiceDisconnected(ComponentName className) {
Log.d(TAG, "onServiceDisconnected");
backgroundService = null;
}
};
private void bindBackgroundService(){
this.bindService(new Intent(this, MyBackgroundService.class), serviceConnection, Context.BIND_AUTO_CREATE);
}
Am I doing this the wrong way? Is it better to stop the Service and restart it?
Since the class that binded the background service is a singleton and my alarm broadcast receiver that is making sure the background service is always running instantiates this singleton, I had access to this singleton and I was trying to bind to the service that was already binded.

OnBind() on service always returns False - Android

I'm trying to bind a service, but onBind() always returns false.
This is the code for the ServiceConnection-
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with our service has been established,
// giving us the service object we can use to interact with our service.
mBoundService = ((ScheduleService.ServiceBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
This is call to bindService() -
boolean test = getApplicationContext().bindService(new Intent(this, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
This is the declaration of the service in the Manifest -
<service android:name=".Notifications.ScheduleService" android:enabled="true"/>
I've read previous questions regarding the subject and couldn't find an answer(tried switching the Activity context with the Application context, but it didn't help).
I'm using using Frgaments and ActionBarSherlock, and my Activity extends SlidingFragmentActivity (That's why i'm using the application context, which doesn't help).
Edit - This is the code of the service i'm trying to start -
public class ScheduleService extends Service {
/**
* Class for clients to access
*/
public class ServiceBinder extends Binder {
public ScheduleService getService() {
return ScheduleService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("ScheduleService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
private final IBinder mBinder = new ServiceBinder();
/**
* Show an alarm for a certain date when the alarm is called it will pop up a notification
*/
public void setAlarm(Calendar c) {
// This starts a new thread to set the alarm
// You want to push off your tasks onto a new thread to free up the UI to carry on responding
new AlarmTask(this, c).run();
}
}
Any help will be appreciated . Thanks.
What is the fully qualified class-name of ScheduleService (i.e. including the full package-name)?
I'm asking this, because in your AndroidManifest.xml file, your service's name is .Notifications.ScheduleService, which seems a bit odd:
This tells me that either
The (last part of the) package-name contains a upper-case
character... not so good.
I would expect .notifications.ScheduleService instead, if this is the case.
The ScheduleService is defined within a file called Notifications.java.
I would expect .Notifications$ScheduleService instead, if this is the case (dollar sign instead of period).
Do you mean bindService() returns false? onBind() returns IBinder type.
Keep in mind that service binding takes some time. If you want to perform some action after binding is done you can perform it in the onServiceConnected() method.
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((ScheduleService.ServiceBinder) service).getService();
Calendar c = new Calendar();
mBoundService.setAlarm(c);
}
If you need more guidance on this you need to show us your Activity code.
Why do you use the application context to bind the service?
The method bindService is called through the ContextWrapper. It might not be the issue but I'd share contexts across the place where you bind the service and where you have the connection.
In your case instead of
boolean test = getApplicationContext().bindService(new Intent(this, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
I'd do the following
boolean test = bindService(new Intent(this, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
Or if you want to keep a global context within the application, move everything to your Application file and call it similarly the same way suggested above.
The issue can also be on the package name of your app and the declaration of your service in your manifest. If you are unsure make sure to give the global route to your service in the manifest.

Android: Getting a variable from my running service

My activity starts a Service, and when I close my app, the service continues to run.
OK, that's right. But when I open my application again, in the activity, I need to know the value of a public variable defined on the running Service(class) that I've started previously.
How can I do that?
Thanks
If you are binding your Activity to the Service, you should have an implementation of the Binder interface in your Service, e.g.
public class ServiceBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
In your Activity, create a new ServiceConnection class which will be used to give you access to your Service:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mMyService = ((MyService.ServiceBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mMyService = null;
}
};
Here the member variable mMyService will give you access to all public members of your Service class.
To create the connection, implement doBindService and doUnbindService in your Activity:
void doBindService() {
bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
}
void doUnbindService() {
// Detach our existing connection.
unbindService(mConnection);
}
Hope this helps!
If you don't call unbindService, your activity still have connection to service and you can simply check the variable through the service's method.
You could use messenger.
As per android website
A messenger is reference to a Handler, which others can use to send messages to it. This allows for the implementation of message-based communication across processes, by creating a Messenger pointing to a Handler in one process, and handing that Messenger to another process.

Binding a service before calling a method on it

i have a problem with binding a service to an activity in Android. The problem occurs in the activity:
public class ServiceTestActivity extends Activity {
private static final String TAG = "ServiceTestAct";
boolean isBound = false;
TestService mService;
public void onStopButtonClick(View v) {
if (isBound) {
mService.stopPlaying();
}
}
public void onPlayButtonClick(View v) throws IllegalArgumentException, IllegalStateException, IOException, InterruptedException {
if (isBound) {
Log.d(TAG, "onButtonClick");
mService.playPause();
} else {
Log.d(TAG, "unbound else");
Intent intent = new Intent(this, TestService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
isBound = true;
}
};
}
isBound tells if the service (called TestService) is already bound to the activity.
mService is the reference to the service.
Now if i call "onPlayButton(..)" the first time, with the service not beeing bound, bindService(..) is called and isBound switches from false to true. Then if i call "onPlayButton(..)" again, it calls "playPause()" on the service object. To here everything works fine.
But i want "playPause()" to be called right after the service has been bound, so i changed my code to this:
public void onPlayButtonClick(View v) throws IllegalArgumentException, IllegalStateException, IOException, InterruptedException {
if (isBound) {
Log.d(TAG, "onButtonClick");
mService.playPause();
} else {
Log.d(TAG, "unbound else");
Intent intent = new Intent(this, TestService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
mService.playPause();
}
}
From this point on I get a NullPointerException, because mService doesn't have a reference to the bound service, it's still null. I checked that by logging the value of mService at different positions in the code.
Any tips on what I am doing wrong here? I am pretty new to programming (especially binding) services in android, but I still don't see where the major differences between my to versions are.
One solution is to call playPause() in onServiceConnected(). Another solution is to call startService() with a custom intent that will tell the service to play. I think you might want to think about a redesign. I would try to design the service so that you can start and bind to the service when the activity starts and stop the service when the activity stops. If you need a service that will stay active past the lifetime of the activity, extend the Application class and you can start the service in the onCreate() method.
The binding of the service occurs asynchronously, i.e. the service may not be bound if bindService() returns but when onServiceConnected() has completed. Because of that mService is still null and the exception is thrown.
One solution would be to disable the button by default (in XML or onCreate()) and enable the button in onServiceConnected().

Wait on startService before bindService

It is my understanding that if I want a service to run even if nothing is bounded to it, then it must first be started with startService(Intent i).
My question is WHAT IF I want to bind to the service immediately after I start it, would the following code guarantee the service is created with startService()?
Static method within the service class:
public static void actStart(Context ctx) {
Intent i = new Intent(ctx, BGService.class);
i.setAction(ACTION_START);
ctx.startService(i);
}
The binding activity:
BGService.actionStart(getApplicationContext());
bindService(new Intent(this, BGService.class), serviceConnection, Context.BIND_AUTO_CREATE);
I am not sure what you are trying to do here, but "Context.BIND_AUTO_CREATE" creates the service then binds to the service even if it hasn't been started.
Now if you want to access it immediately after binding, you can use the onServiceConnected() method of the serviceConnection:
new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
//put your code here...
} ...
To add to Bugdayci's answer, a complete example is as follows:
ServiceConnection myConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
... your code that needs to execute on service connection
}
#Override
public void onServiceDisconnected(ComponentName name) {
... your code that needs to execute on service disconnection
}
};
Intent intent = new Intent(this, TheServiceClassName.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
...
Without the bindService at the end, the onServiceConnected() code will not execute.

Categories

Resources