【Android基础知识】Service

Service是什么?

1.Service是一种长生命周期的、没有用户界面的应用程序组件。

2.所有用户实现的Service 必须继承系统的Service类,并且在配置文件中进行注册。

3.有些用时比较长的操作我们希望它在后台运行,不影响当前操作,这里引入了Service概念。常见的如:访问网络、文件IO操作,大型数据库任务、音乐播放等。

4.可以使用Service更新ContentProvider,发送Intent以及启动系统通知等。

5.Service在后台运行,且不与用户进行交互。在默认情况下,Service运行在应用程序的主线程中,如果需要在Service中处理一些网络连接等耗时的操作,那么应该将这些任务放在单独的线程中处理,避免阻塞用户界面。

Service不是什么?

Service不是一个单独的进程。(进程就是拥有独立的内存空间,一个进程里可以拥有多个线程)。

Service不是一个线程。

Service和整个应用程序在同一个进程或者同一个线程中运行。

 

Service的开发步骤

第一步:继承Service

public class SMSService extends Service { }

第二步:在AndroidManifest.xml文件中的<application>节点里对服务进行配置:

<service android:name=".SMSService" />

Service的分类:分为两种 StartedBound

服务不能自己运行,需要通过调用Context.startService()Context.bindService()方法启动服务,两种启动方式有一些区别。

 

两种方式的生命周期


 

Service中的生命周期方法

IBinder onBind(Intent intent); 该方法返回一个IBinder 对象,应用程序可通过该对象与Service组件通信。

Void onCreate():当Service第一次被创建后立即回调。

Void onDestroy():当该Service被关闭之前会回调。

Void onStartCommand(Intent intent, int flags,int startld):每次客户端调用startService(intent)方法启动该Service时都会回调该方法。

Boolean onUnbind(Intent intent):当该Service上绑定的所有客户端都断开连接时将回调。

 

 

StartService方法的特点

 

1、使用startService()方法启用服务,调用者与服务之间没有关连,即使调用者退出了,服务仍然运行。

 

2、onCreate()该方法在服务被创建时调用,该方法只会被调用一次,无论调用多少次startService()bindService()方法,服务也只被创建一次。

 

3、onStartCommand() 只有采用Context.startService()方法启动服务时才会回调该方法。该方法在服务开始运行时被调用。多次调用startService()方法尽管不会多次创建服务,但onStartCommand() 方法会被多次调用。

 

4采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法

 

onBind方法的特点

 

1、采用Context.bindService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onBind()方法,这个时候调用者和服务绑定在一起,调用者一旦退出,服务也就终止。onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用Context.bindService()方法并不会导致该方法被多次调用。

 

2、通过startService()stopService()启动关闭服务。适用于服务和Activity之间没有调用交互的情况。如果客户端要与服务进行通信,要使用onBindService()方法,onBind()方法必须返回Ibinder对象。

 

3如果调用者希望与正在绑定的服务解除绑定,可以调用unbindService()方法,调用该方法也会导致系统调用服务的onUnbind()-->onDestroy()方法。

 

 

Started启动方式: 

startService()来启动,一旦启动,就运行在后台,即便启动它的对象已经销毁了。

通常只启动,不返回值。通常网络上传或下载,操作完成后,自动停止。

onStartCommand()。业务核心

 

public class FirstService extends Service{

@Override

public IBinder onBind(Intent arg0) {

// TODO Auto-generated method stub

return null;}

@Override

public void onCreate() {

// TODO Auto-generated method stub

super.onCreate();}

@Override

public void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

// 启动Service后的主要操作都在这里进行

return super.onStartCommand(intent, flags, startId);

    }

}

注意要在AndroidManifest文件中注册Service

public class StartService extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        Intent intent  = new Intent(StartService .this,FirstService .class);

        //启动服务

        startService(intent);

}

}

 

Bound启动方式

如果Service和访问者之间需要进行方法调用或数据交换,则使用bindService()来绑定启动Service

bindService(Intent service,ServiceConnection conn,int flags);

Service :指定要启动的service

Conn:一个ServiceConnection 对象,该对象用于监听访问者与Service之间的连接 情况。连接成功调用 onServiceConnected(ComponentName name, IBinder service)方法;

终止或其他原因终止,则调用 onServiceDisconnected(ComponentName name);

当调用者主动通过unBindService()方法断开连接时,onServiceDisconnected(ComponentName name)不会调用。

Flags:指定绑定时是否自动创建Service(如果Service还未创建)。0不自动创建。

提供客户端服务器接口来启动。发送请求,得到返回值,甚至通过IPC来通讯。

只要有一个绑定者,服务运行,所有绑定者都退出,服务退出。

OnBind()。核心业务依赖于底层,有服务器和客户端概念。

 

实际开发通常会采用继承Binder的方式实现自己的IBinder

public class BindService extends Service {

private static final String TAG="BindService";

private int count;

private boolean quit;

//定义onBind 方法返回的对象

private MyBinder binder = new MyBinder();

public class MyBinder extends Binder{

public int getCount(){

//获取Service运行状态,count

return count;

}

}

@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

//绑定该Service时回调的方法

Log.i(TAG,"service is binded");

return binder;

}

 

@Override

public void onCreate() {

// TODO Auto-generated method stub

super.onCreate();

Log.i(TAG,"service is created");

//启动一条线程,动态修改count状态值

new Thread(){

@Override

public void run() {

// TODO Auto-generated method stub

while(!quit){

try{

Thread.sleep(1000);

}catch(InterruptedException e){

}

count++;

}

}

}.start();

}

@Override

public void onDestroy() {

//service关闭之前回调

super.onDestroy();

this.quit = true;

Log.i(TAG, "service is destroy");

}

@Override

public boolean onUnbind(Intent intent) {

// TODO Auto-generated method stub

//断开连接时回调

Log.i(TAG,"service onUnbind");

return true;

}

}

 

Activity分别有三个按钮,绑定Service,解除绑定,获取Service状态。

public class MainActivity extends Activity {

private static final String TAG="BindService";

Button bind,unbind,getServiceStatus;

//保持所启动ServiceIBinder对象

BindService.MyBinder binder;

//定义一个ServiceConnection对象

private ServiceConnection  conn = new ServiceConnection() {

@Override

public void onServiceDisconnected(ComponentName name) {

// TODO Auto-generated method stub

Log.i(TAG,"Service disconnected");

}

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

// TODO Auto-generated method stub

Log.i(TAG,"service connected");

//获取ServiceonBind方法所返回的MyBinder对象

binder = (BindService.MyBinder) service;

}

};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

bind = (Button)findViewById(R.id.button1);

unbind =(Button)findViewById(R.id.button2);

getServiceStatus=(Button)findViewById(R.id.button3);

//创建Serviceintent

final Intent intent = new Intent(MainActivity.this,BindService.class);

bind.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

//绑定Service

bindService(intent, conn, Service.BIND_AUTO_CREATE);

}

});

unbind.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

//解除绑定

unbindService(conn);

}

});

getServiceStatus.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

//获取显示Servciecount

Toast.makeText(MainActivity.this, "Service count值为"+binder.getCount(),Toast.LENGTH_SHORT).show();

}

});

}

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值