首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

android servicelifecycle 服务的生命周期跟程序内部调用服务

2012-11-04 
android servicelifecycle 服务的生命周期和程序内部调用服务创建服务类:创建MyService类继承Service,其中

android servicelifecycle 服务的生命周期和程序内部调用服务

创建服务类:创建MyService类继承Service,其中内部类IServiceImpl继承系统的binder类 和实现自定义接口IService

IService提供外部调用的方法:

package com.example.serverlifecycle;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private Button startButton;// 普通开启服务按钮private Button endButton;private Intent intent;private Button startBindButton;// 绑定服务private Button endBindButton;// 解除服务private Button callMethodInService;// 解除服务private MyServiceConnection conn;private IService iService;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);startButton = (Button) findViewById(R.id.start);endButton = (Button) findViewById(R.id.end);startButton.setOnClickListener(this);endButton.setOnClickListener(this);intent = new Intent(this, MyService.class);startBindButton = (Button) findViewById(R.id.startBindService);endBindButton = (Button) findViewById(R.id.endBindService);startBindButton.setOnClickListener(this);endBindButton.setOnClickListener(this);callMethodInService = (Button) findViewById(R.id.callMethod);callMethodInService.setOnClickListener(this);conn = new MyServiceConnection();}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.start:startService(intent);// 启动服务break;case R.id.end:stopService(intent);// 停止服务break;case R.id.startBindService:// 绑定服务bindService(intent, conn, Context.BIND_AUTO_CREATE);// 绑定服务,参数3如果这个绑定的服务不存在的时候,绑定的时候就会创建出这个服务break;case R.id.endBindService:unbindService(conn);// 解除绑定服务break;case R.id.callMethod:iService.callMethodInService();break;}}@Overrideprotected void onDestroy() {unbindService(conn);// 在activity结束的时候,调用unbindService(conn)可避免出现serviceconnectionleaked异常super.onDestroy();}class MyServiceConnection implements ServiceConnection {@Override/** * 绑定某个服务成功后执行的方法,就是在绑定的服务执行了onCreate方法之后 * service,该对象是由绑定服务的onBind方法的返回值,因为onBind()返回值实现IService接口,所以可以强制转换为IService接口类型 */public void onServiceConnected(ComponentName arg0, IBinder service) {iService = (IService) service;}@Overridepublic void onServiceDisconnected(ComponentName arg0) {}}}



热点排行