关于startService 与 bindservice的混用

                                       关于startService 与 bindservice的混用

俗话说得好细节决定成败,好多就是因为细节没注意,导致效率不高,从而花费很多时间调代码,今天我就来讲讲startService 与 bindservice的混用

先看示例代码:
public class MYService extends Service{

MyBinder myBinder=new MyBinder();
@Override
public IBinder onBind(Intent intent) {
    System.out.println("------------>"+"onBind");
    return myBinder;
}

public class MyBinder extends Binder {

    public void play(){
        int i=0;
        while (i++<2){
            System.out.println("++++++++++++++");
        }

    }
}

@Override
public boolean onUnbind(Intent intent) {
    System.out.println("------------>"+"onUnbind");
    return super.onUnbind(intent);
}

@Override
public void onCreate() {
    super.onCreate();
    System.out.println("------------>" + "onCreate");
}

@Override
public void onDestroy() {
    super.onDestroy();
    System.out.println("------------>" + "onDestroy");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    int i=0;
    while (i++<3){
        System.out.println("=======================");
    }

    return super.onStartCommand(intent, flags, startId);
}

}

public class MainActivity extends AppCompatActivity {

MYService.MyBinder myBinder;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button= (Button) findViewById(R.id.my_button);
    button.setOnClickListener(new View.OnClickListener(){      
        @Override
        public void onClick(View v) {
            myBinder.play();
        }
    });

    Intent intent=new Intent(this,MYService.class);
    startService(intent);

    ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder= (MYService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
     bindService(intent,conn,Service.BIND_AUTO_CREATE);

 //   unbindService(conn);
  //    startService(intent);

      stopService(intent);
}

}

这样的执行结果:后台的service是不会停止的,因为执行bindService之后,并没有执行unbindService(conn); 所以你此刻去掉startService(intent);的注释就可以看见,其实后台还是在执行。

若把 unbindService(conn)的注释去掉,那么后台service就执行完了,会调用onDestroy函数

你可能感兴趣的:(Android)