Service
来源:互联网 发布:新手程序员刚进公司 编辑:程序博客网 时间:2024/05/17 11:59
服务的基本用法
创建一个继承Service的类 里面会重写一些方法 1 onBind()方法,这是服务中唯一的一个抽象方法,必须在子类里实现,2 onCreat()方法 ,创建服务时调用 。3 onStartCommand()方法,每次启动服务时调用。 4 onDestroy()方法,服务销毁时调用。
服务需要在AndroidManifest.xml中进行注册,加一个 Service节点 name---- 和 broadcastReceiver的注册差不多。
启动服务 Intent intent=new intent(this,建的那个服务类) startService(intent)
停止服务 、、、、、、、 stopService(intent)。
如果想让服务自己停止,只需要在建的那个类的任何一个位置调用stopSelf()方法。
private ServiceConnection connection = new ServiceConnection() {
、、、新建个 ServiceConnection 对象
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
};
@Override
public void onClick(View v) {
switch (v.getId()) {
绑定服务 case R.id.bind_service:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
解除绑定 case R.id.unbind_service:
unbindService(connection);
break;
}
绑定之后就可以活动就可以调用服务里面的Binder提供的方法
public class MyService extends Service {
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder {
建个继承Binder的类
里面有一些方法
public void startDownload() {
new Thread(new Runnable() {
@Override
public void run() {
// start downloading
}
}).start();
Log.d("MyService", "startDownload executed");
}
public int getProgress() {
Log.d("MyService", "getProgress executed");
return 0;
}
@Override
public IBinder onBind(Intent intent) {
Log.d("MyService", "onBind executed");
return mBinder; 要返回你建的那个 类的实例
}
- Service
- Service
- service
- Service
- service
- Service
- Service
- service
- Service
- Service
- Service
- service
- service
- Service
- Service
- Service
- Service
- Service
- JS中函数声明与函数表达式的不同
- C++中的构造函数/析构函数,虚函数/纯虚函数
- 隐式 参数
- 2015年第五周项目一:体验常成员函数
- 改变状态栏的颜色
- Service
- mac brew install
- 2015-4-7 中度贫血 食记
- 乐观锁的作用
- Java习惯用法总结
- IMEI和IMSI的区别
- (宏代码)Execl 中 比较两个Sheet内容是否一致
- leetcode172:Factorial Trailing Zeroes
- 按键监听类KeyListener及适配器改良方案