public class MainActivity extends Activity {
private MBind mBind;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(MainActivity.this, MyService.class);
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 绑定服务
mBind = (MyService.MBind) service;
}
};
// 开启服务
bindService(intent, connection, Service.BIND_AUTO_CREATE);
}
}
//Service里面的代码
public class MyService extends Service {
private MBind mBind;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mBind = new MBind();
}
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBind;
}
//建立自定义的类 继承Binder
public class MBind extends Binder {
}
}