public class MyBinderService extends Service {
private int count;
private boolean quit=false;
private Thread thread;
private MyBinder myBinder=new MyBinder();
public int getCount() {
return count;
}
public class MyBinder extends Binder{
MyBinderService getService(){
return MyBinderService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i("tttttt","onBind service");
return myBinder;
}
// 服务已运行,则不会调用此方法 在 onBind onStartCommand 之前
@Override
public void onCreate() {
super.onCreate();
Log.i("tttttt","onCreate service");
thread=new Thread(new Runnable() {
@Override
public void run() {
while (!quit){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
});
thread.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("tttttt","onStartCommand service");
return super.onStartCommand(intent, flags, startId);
}
// 服务销毁时回调
@Override
public void onDestroy() {
super.onDestroy();
quit=true;
Log.i("tttttt","onDestroy service");
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("tttttt","onUnbind service");
return super.onUnbind(intent);
}
}
在activity使用:
private ServiceConnection connection;
private MyBinderService myBinderService;
// 绑定
bindService(new Intent(MainActivity2.this,MyBinderService.class),connection, Service.BIND_AUTO_CREATE);
connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
MyBinderService.MyBinder myBinder= (MyBinderService.MyBinder) iBinder;
myBinderService=myBinder.getService();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
myBinderService=null;
}
};
// 获取数据
if (myBinderService!=null){
Log.i("tttttt",myBinderService.getCount()+"---get count---");
}
PS:记得在manifest文件中注册;



