package com.example.immediate.mybindservice;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button mButtonBind;
private MyBindService myBindService;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.d("onbind", "得到service对象");
if (iBinder instanceof MyBindService.MyBinder){
myBindService = ((MyBindService.MyBinder) iBinder).getService();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.d("onbind", "service断开连接");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonBind = (Button) findViewById(R.id.button_bind);
mButtonBind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/**
* 三个参数:1、Intent 要启动那个service
* 2、ServiceConnection,连接Activity和绑定的service,得到绑定的service
* 3、启动service的方式
*/
Intent intent = new Intent(getApplicationContext(),MyBindService.class);
bindService(intent,connection ,BIND_AUTO_CREATE);
Log.d("onbind", "开始绑定Service");
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}
package com.example.immediate.mybindservice;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
/**
* Created by Administrator on 2015/11/5.
*/
public class MyBindService extends Service {
class MyBinder extends Binder{
public MyBindService getService() {
Log.d("onbind","返回service对象");
return MyBindService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
Log.d("onbind","绑定 onBind");
return new MyBinder();
}
@Override
public void onCreate() {
super.onCreate();
Log.d("onbind", "Service的创建onCreate");
}
@Override
public boolean onUnbind(Intent intent) {
Log.d("onbind","Service解除绑定onUnbind");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
Log.d("onbind","Service关闭onDestroy");
super.onDestroy();
}
}