标签:
在Android四大组件中,Service和Activity两个比较相似,区别是Activity用于前台,Service用于后台。
当你的程序不需要用组件呈现界面时,这时候用Service。典型范例就是播放音乐,界面退出后仍需播放音乐,这时需要的就是Service后台运行了。
public class BindService extends Service
{
private int count;
private boolean quit;
// 定义onBinder方法所返回的对象
private MyBinder binder = new MyBinder();
<span style="background-color: rgb(102, 255, 153);">// 通过继承Binder来实现IBinder类
<span style="color:#333333;">public class MyBinder extends Binder //①
{
public int getCount()
{
// 获取Service的运行状态:count
return count;
}
}
// 必须实现的方法,绑定该Service时回调该方法
@Override
public IBinder onBind(Intent intent)
{
System.out.println("Service is Binded");
// 返回IBinder对象
return binder;
}</span></span>
// Service被创建时回调该方法。
@Override
public void onCreate()
{
super.onCreate();
System.out.println("Service is Created");
// 启动一条线程、动态地修改count状态值
new Thread()
{
@Override
public void run()
{
while (!quit)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
}
count++;
}
}
}.start();
}
// Service被断开连接时回调该方法
@Override
public boolean onUnbind(Intent intent)
{
System.out.println("Service is Unbinded");
return true;
}
// Service被关闭之前回调该方法。
@Override
public void onDestroy()
{
super.onDestroy();
this.quit = true;
System.out.println("Service is Destroyed");
}
}public class BindServiceTest extends Activity
{
Button bind, unbind, getServiceStatus;
// 保持所启动的Service的IBinder对象
BindService.MyBinder binder;
<span style="background-color: rgb(102, 255, 153);">// 定义一个ServiceConnection对象
private ServiceConnection conn = new ServiceConnection()
{
// 当该Activity与Service连接成功时回调该方法
@Override
public void onServiceConnected(ComponentName name
, IBinder service)
{
System.out.println("--Service Connected--");
// 获取Service的onBind方法所返回的MyBinder对象
binder = (BindService.MyBinder) service; //①
}
// 当该Activity与Service断开连接时回调该方法
@Override
public void onServiceDisconnected(ComponentName name)
{
System.out.println("--Service Disconnected--");
}
};</span>
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取程序界面中的start、stop、getServiceStatus按钮
bind = (Button) findViewById(R.id.bind);
unbind = (Button) findViewById(R.id.unbind);
getServiceStatus = (Button) findViewById(R.id.getServiceStatus);
// 创建启动Service的Intent
final Intent intent = new Intent();
// 为Intent设置Action属性
intent.setAction("org.crazyit.service.BIND_SERVICE");
bind.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 绑定指定Serivce
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
});
unbind.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 解除绑定Serivce
unbindService(conn);
}
});
getServiceStatus.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 获取、并显示Service的count值
Toast.makeText(BindServiceTest.this,
"Serivce的count值为:" + binder.getCount(),
Toast.LENGTH_SHORT).show(); //②
}
});
}
}标签:
原文地址:http://blog.csdn.net/u010456903/article/details/45503091