Service初步

来源:互联网 发布:ipad怎么登陆淘宝卖家 编辑:程序博客网 时间:2024/06/05 18:39

1.Service是什么

A Service is an application component that can perform long-running operations in the background and does not provide a user interface

  a. Service是一个应用程序组件

  b. Service没有图形化界面

  c. Service通常用来处理一些耗时比较长的操作

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

2.Service不是什么

  a. Service不是一个单独的进程(一个进程可能包含多个线程)

  b. Service不是一个线程

3.Service的生命周期

4.启动和停止Service的方法

5.Service操作

  a.新建一个ServiceAcity.java的类,继承自Service,手动添加重写onCreate(),onDestroy(),onStart()方法

package wei.cao.test;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class FirstService extends Service {@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();System.out.println("Service onCreate");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();System.out.println("Service onDestroy");}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubSystem.out.println("startId--->"+startId);System.out.println("Service onStart");super.onStart(intent, startId);}}

b.在AndroidManifes.xml对Service进行注册,注册方法与Activity注册的方法一样

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

c.新建一个启动Service的类ServiceActivity.java

package wei.cao.test;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;public class ServiceActivity extends Activity {    /** Called when the activity is first created. */private Button btnStartService;private Button btnStopService;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                btnStartService=(Button)this.findViewById(R.id.btnStartService);        btnStopService=(Button)this.findViewById(R.id.btnStopService);                btnStartService.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubIntent intent=new Intent();intent.setClass(ServiceActivity.this, FirstService.class);startService(intent);}});                btnStopService.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubIntent intent=new Intent();intent.setClass(ServiceActivity.this, FirstService.class);startService(intent);stopService(intent);}});            }}

d.执行结果(依次单击->StartService,StartService,StopService,StartService):


 3.什么是Bound Services

Bound Services允许其它的组件(比如Activits)绑定到这个Services,可以发送请求,也可以接受请求,甚至进行进程间的通话,Bound Services仅仅在服务于其它组建时存在,不能独自无期限的在后台运行

创建Bound Services

  当创建一个能提供绑定功能的服务时,必须指定一个IBinder对象,客户端使用这个对象与服务端进行交互,在Android中有三种定义方式:

1.继承Binder类

2.使用Messager

3.使用AIDL(Android Interface Defination Language)

  a.通过继承Binder类来创建Bound Services

  创建一个BoundServices类

 

package wei.cao.test;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class BinderServices extends Service {private MyBinder myBinder=new MyBinder();private static final String TAG = "BinderServices";//内部类public  class MyBinder extends Binder{        //返回BinderServices的实例public BinderServices getService(){return BinderServices.this;}}@Overridepublic IBinder onBind(Intent arg0) {return myBinder;}public void myMethod(){Log.i(TAG, "myMethod()");}}

  创建一个Actiivty

 

package wei.cao.test;import wei.cao.test.BinderServices.MyBinder;import android.app.Activity;import android.content.ComponentName;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 Services_03Activity extends Activity {    /** Called when the activity is first created. */private Button btnBind,btnUnBind=null;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                btnBind.setOnClickListener(clickListener);        btnUnBind.setOnClickListener(clickListener);    }    private OnClickListener clickListener=new OnClickListener(){@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btnBind:Intent intent=new Intent();bindService(intent,conn, 1);break;case R.id.btnUnBind:unbindService(conn);break;default:break;}  }        };    //匿名内部类    private ServiceConnection conn=new  ServiceConnection()    {    @Override    public void onServiceConnected(ComponentName name, IBinder service) {       //需要向上转型           MyBinder myBinder=(MyBinder)service;       BinderServices binderServices=myBinder.getService();       //调用BinderServices对象中的myMethod()方法       binderServices.myMethod();    }    @Override    public void onServiceDisconnected(ComponentName name) {    }   };}


4.IntentService的使用(由于Service与主线程在同一线程内,如果Service中的内容执行时间比较长,会导致等待的时间比较长,当然也可以在Service里面重新创建一个线程)

   IntentService是Service类的子类,用来处理异步请求,客户端通过startService(Intent)方法传递请求给IntentService,IntentService通过worker thread处理每个Intent对象(每次只去取一个Intent对象),执行完所有工作后自动停止Service.

  1.写构造函数

  2.复写onHandleIntent()方法

  3.IntentService执行如下操作:

    创建一个与应用程序主线程分开worker thread用来处理通过传递过来的Intent请求

    创建一个work quene,一次只传递一个intent到onHandleIntent()方法中,从而不用担心线程带来的问题

    当处理完所有请求后停止服务,而不需要我们自己调用stopSelf()方法

    默认实现了onBind()方法,值为null

    默认实现了onStartCommand()方法,这个方法将会把我们的intent对象放入到work quene,然后在onHandleIntent()中执行

package wei.cao.test;import android.app.IntentService;import android.content.Intent;import android.util.Log;public class ExampleIntentService extends IntentService {private static final String TAG = "ExampleIntentService";public ExampleIntentService(String name) {super(name);}@Overrideprotected void onHandleIntent(Intent arg0) {try{ Log.i(TAG,"ExampleIntentService线程的ID"+Thread.currentThread().getId()); //模拟运行时间较长的操作 Log.i(TAG,"文件下载......"); Thread.sleep(2000);    }catch(Exception e){e.printStackTrace();}}}


 

原创粉丝点击