我正在尝试创建绑定服务。作为测试,我创建了播放音乐的服务:
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;
}
}
}
当我从 Activity 绑定它时,什么也没有发生:
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 android:name=".MusicService" />
出现绑定失败,没有任何反应
编辑:bindService() 返回 false
EDIT2:当我在清单中添加完整名称时,例如。com.mypackage.mypackage2.MusicService 绑定 Service() 返回 true。但是永远不会调用 onServiceConnected() 。
下一个问题是:当我创建实现 LocationListener 的服务时,每次 onLocationChanged() 时我应该使用什么来向活动发送消息?