绑定服务android

时间:2011-08-29 10:29:55

标签: android service

我正在尝试将活动绑定到服务,这是我的代码 以下是活动代码

         Button start = (Button) findViewById(R.id.button1);
         Button stop = (Button) findViewById(R.id.button2);
         start.setOnClickListener(this);
         stop.setOnClickListener(this);
        }
    @Override
       public void onClick(View v) {
       if(v.getId() == R.id.button1)
       {
        Intent i = new Intent(Intent.ACTION_MAIN);
        i.setClassName("org.example","org.example.ServicesActivity");
        bindService(i, conn, 0);
       }
       else if(v.getId() == R.id.button2)
       {
        unbindService(conn);
        counter.setText("Number of Binding issss");
       }    
       }
        public ServiceConnection conn = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {
        System.out.println("Service is disconnected");  
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        System.out.println("Service is connected"); 
    }
       };

这是我服务的代码

             IBinder mBinder = new LocalBinder();
         @Override
          public IBinder onBind(Intent intent) {
    System.out.println("came to onBind in service");
    return mBinder ;

         }
           @Override
           public void onCreate(){
          super.onCreate();
            System.out.println("came to oncreate in service");      
                 }
              @Override
               public void onStart(Intent intent,int startId){
            super.onStart(intent, startId);
             System.out.println("came to onstart in service");
                  }
          public class LocalBinder extends Binder{
            ServicesActivity getService(){
          System.out.println("came to Localbinder getservice in service");
         return ServicesActivity.this;  
         }
              }

我的服务和活动是两个不同的应用程序 我的问题是,当我按下启动按钮时,活动应绑定到服务但它没有绑定,它甚至没有显示任何错误 你能告诉我我在做错误吗? 感谢

1 个答案:

答案 0 :(得分:0)

您是否在安装了包含服务的apk中运行了活动?您无法安装独立服务,并希望在用户交互之前运行该服务。用户必须至少运行一次以使其脱离"停止"州。然后服务可以对意图做出反应。此安全功能是在Android 3.1中引入的。

http://developer.android.com/about/versions/android-3.1.html#launchcontrols