首页 > 代码库 > android Activity绑定Service
android Activity绑定Service
activity可以绑定Service,并且可以调用Service中定义的方法
Service代码:在里面多了一个IBinder;个人理解是用来与Activity绑定的主要通道;
public class MainServer extends Service { private final String TAG = "Service------->"; private final IBinder binder = new MyBinder(); //绑定器 public class MyBinder extends Binder { public MainServer getService() { return MainServer.this; //返回本服务 } } /** 绑定时执行 */ @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind()"); return binder; } /** 只在创建时执行一次 */ @Override public void onCreate() { super.onCreate(); Log.i(TAG, "onCreate()"); } /** 断开绑定或者停止服务时执行 */ @Override public void onDestroy() { super.onDestroy(); Log.i(TAG, "onDestroy()"); } /** 当内存不够是执行该方法 */ @Override public void onLowMemory() { super.onLowMemory(); Log.i(TAG, "onLowMemory()"); onDestroy(); } /** 当从新绑定是执行 */ @Override public void onRebind(Intent intent) { // TODO Auto-generated method stub super.onRebind(intent); Log.i(TAG, "onRebind()"); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); Log.i(TAG, "onStart()"); } /** 每次执行Service都会执行该方法 */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "onStartCommand --->flags = " + flags + " startId = " + startId); con = new Connect(); con.start(); return super.onStartCommand(intent, flags, startId); } /** 断开绑定是执行 */ @Override public boolean onUnbind(Intent intent) { Log.i(TAG, "onUnbind()"); return super.onUnbind(intent); }
MainActivity代码: 必须声明实例ServiceConnection,并且在绑定成功后获取到Service,用以调用Service的方法
public class MainActivity extends Activity { private MainServer mainService; //绑定Service监听 ServiceConnection sconnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Log.i("activity---->", "已断开Service"); } /**当绑定时执行*/ @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub Log.i("activity---->", "已绑定到Service"); mainService = ((MainServer.MyBinder)service).getService(); Intent i = new Intent(); mainService.onStartCommand(i, 0, 0); //绑定成功后可以调用Service方法,此处等与是启动Service } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button start = (Button)findViewById(R.id.start); Button stop = (Button)findViewById(R.id.stop); Button send = (Button)findViewById(R.id.send); Button skip = (Button)findViewById(R.id.skip); start.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent bind = new Intent(MainActivity.this,MainServer.class); bindService(bind, sconnection, Context.BIND_AUTO_CREATE); } }); stop.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { unbindService(sconnection); } });
android Activity绑定Service
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。