Reputation: 2076
Im trying to create bound service. As a test I created service which plays music:
public class MusicService extends Service {
private final IBinder myBinder = new LocalBinder();
MediaPlayer player;
@Override
public IBinder onBind(Intent arg0) {
return myBinder;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this,R.raw.teardrop);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
public class LocalBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
}
And when I bind it from Activity nothing happens:
public class MainActivity extends TabSwipeActivity {
boolean isBound = false;
MusicService myService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Some code
Intent intent = new Intent(this, MusicService.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
if(isBound){
Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "bind failed", Toast.LENGTH_SHORT).show();
}
}
private ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,IBinder service) {
LocalBinder binder = (LocalBinder) service;
myService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
}
Service is registred in manifest:
<service android:name=".MusicService" />
Bind failed appears and nothing happens
EDIT: bindService() returns false
EDIT2: when I add complete name in manifest eg. com.mypackage.mypackage2.MusicService bind Service() returned true. But onServiceConnected() is never called.
Next question is: When I create service which implements LocationListener, what should I use to send message to activity everytime when onLocationChanged()?
Upvotes: 1
Views: 1916
Reputation: 2076
I already know the solution. I extends TabActivity
made by actionBarSherlock
instead of Activity
. This is known issue:
getApplicationContext().bindService();
fix that.
Upvotes: 2