Android:服务不会绑定

时间:2013-07-19 08:51:45

标签: java android

我正在尝试创建绑定服务。作为测试,我创建了播放音乐的服务:

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 bind Service()返回true。但是永远不会调用onServiceConnected()。

接下来的问题是:当我创建实现LocationListener的服务时,每次onLocationChanged()时我应该使用什么来向活动发送消息?

1 个答案:

答案 0 :(得分:2)

我已经知道了解决方案。我将TabActivity actionBarSherlock扩展为Activity而不是 getApplicationContext().bindService(); 。这是众所周知的问题:

{{1}}

解决这个问题。