2.启动服务按钮
这个类实现的是第一个按钮的功能,在这个类中新开了一个线程,并每隔一秒打印出一行日志
代码如下:
package lovefang.stadyService;
/**引入包*/
import Android.app.Service;// 服务的类
import android.os.IBinder;
import android.os.Binder;
import android.content.Intent;
import android.util.Log;
/**计数的服务*/
public class CountService extends Service{
/**创建参数*/
boolean threadDisable ;
int count;
public IBinder onBind(Intent intent){
return null;
}
public void onCreate(){
super.onCreate();
/**创建一个线程,每秒计数器加一,并在控制台进行Log输出*/
new Thread(new Runnable(){
public void run(){
while(!threadDisable){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
}
count++;
Log.v("CountService","Count is"+count);
}
}
}).start();
}
public void onDestroy(){
super.onDestroy();
/**服务停止时,终止计数进程*/
this.threadDisable = true;
}
public int getConunt(){
return count;
}
class ServiceBinder extends Binder{
public CountService getService(){
return CountService.this;
}
}
}
3.绑定服务
服务有两种实现的方法:
1.startService,启动服务,这时需要程序员管理服务的生命周期
2.bindService,绑定服务,此时Service与Activity绑定在一起
下面是实现的代码:
package lovefang.stadyService;
/**引入包*/
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.util.Log;
/**通过bindService和unBindSerivce的方式启动和结束服务*/
public class UseBrider extends Activity {
/**参数设置*/
CountService countService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new UseBriderFace(this));
Intent intent = new Intent(UseBrider.this,CountService.class);
/**进入Activity开始服务*/
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
private ServiceConnection conn = new ServiceConnection(){
/**获取服务对象时的操作*/
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
countService = ((CountService.ServiceBinder)service).getService();
}
/**无法获取到服务对象时的操作*/
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
countService =null;
}
};
protected void onDestroy(){
super.onDestroy();
this.unbindService(conn);
Log.v("MainStadyServics", "out");
}
}