Android 完全掌握Service

来源:互联网 发布:js下一个兄弟元素 编辑:程序博客网 时间:2024/05/16 17:40

Service


Service生命周期:

1.context.startService() ->onCreate()- >onStartCommand()->Service running--调用context.stopService() ->onDestroy()

 

2.context.bindService()->onCreate()->onBind()->Service running--调用>onUnbind() -> onDestroy()

IBinder

onBind(Intent intent)

该方法时Service子类必须实现的方法.该方法返回一个IBinder对象,通过这个对象与Service组件通信

Void

onCreate()

在该Service被第一次调用后立即调用该方法

Void

onDestroy()

在该Service被关闭前回调该方法

Void

onStartConmmand(Intent intent,int flags,intstartId)

每次调用startService(Intent)方法启动Service时都会回调该方法

Boolean

onUnbind(Intent intent)

当该Service绑定的所有客户端都断开时回调该方法

 

package com.jia.fistservice;

import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.util.Log;

public class FirstService extends Service {

 

    @Override

    public IBinder onBind(Intent intent) {

       Log.d("jia", "必须实现的方法--->onBind(Intent intent)");

       return null;

    }

 

    @Override

    public void onCreate() {

       Log.d("jia", "Service被创建的时回调该方法--->onCreate()");

       super.onCreate();

    }

 

    @Override

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

       Log.d("jia",

              "Service被启动时回调该方法--->onStartCommand(Intent intent, int flags, int startId)");

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

    }

 

    @Override

    public void onDestroy() {

       Log.d("jia", "Service被关闭之前回调该方法--->onCreate()");

       super.onDestroy();

    }

}

使用Service需在AndroidManifest.xml文件中进行配置:

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

Service两种启动方式:

  1. 通过ContextstartService()方法:通过该方法启动Service,访问者与Service之间没有关联,即使访问者退出了,Service也仍然运行.
  2. 通过ContextbindService()方法:使用该方法启动Service,访问者与Service绑定在一起,访问者一旦退出,Service也就终止了.

创建Service:


多次启动与销毁:


onCreate()方法只在第一次创建Service时启动,之后不会在触发.

onStartCommand()方法在每次启动Service时都会调用.

绑定本地Service并与之通信

如果Service与访问者之间进行方法调用或交换数据,应该使用bindService()unbindService()方法启动.关闭Service.

bindService(Intent service,ServiceConnection conn,int flags)方法的三个参数如下:

service:通过Intent指定要启动的Service;

conn:该参数是ServiceConnection的对象,该对象用于监听访问者与Service之间的连接情况.当访问者与Service连接成功时调用ServiceConnection对象的onServiceConnected(ComponentName name, IBinder service)方法;Service与访问者连接异常时,将调用ServiceConnection对象的onServiceDisconnected(ComponentName name)方法

当调用者主动通过unBinderService()方法断开与Service的连接时,ServiceConnection对象的onServiceDisconnected(ComponentName name)方法并不会调用.

flags:指定绑定时是否自动创建Service(如果Service还未创建).该参数可指定为0(不自动创建)Service.BIND_AUTO_CREATE(自动创建);

 

Service类必须提供onBind(Intent intent)方法,该方法返回的IBinder对象将会传给ServiceConnection对象里onServiceConnected(ComponentName name, IBinder service)方法的service参数,这样访问者就可以通过该IBinder对象与Service进行通信了.

开发时会采用继承Binder(IBinder的实现类)的方式实现自己的IBinder对象.

BindService

package com.jia.bindservice;

 

import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

import android.util.Log;

 

public class BindService extends Service {

      private int count;

      private boolean quit;

      private MyBinder bind = new MyBinder();

      public class MyBinder extends Binder {

           public int getCount() {

                 return count;

           }

      }

      @Override

      public IBinder onBind(Intent intent) {

           Log.d("jia", "Service is Binded---->onBind(Intent intent)");

           return bind;

      }

      @Override

      public void onCreate() {

           super.onCreate();

           Log.d("jia", "Service is Created---->onCreate()");

           new Thread() {

                 public void run() {

                      while (!quit) {

                            try {

                                  Thread.sleep(1000);

                            } catch (InterruptedException e) {

                            }

                            count++;

                      }

                 };

           }.start();

      }

 

      @Override

      public boolean onUnbind(Intent intent) {

           Log.d("jia", "Service is Unbinded---->onUnbind(Intent intent)");

           return true;

      }

      @Override

      public void onDestroy() {

           super.onDestroy();

           this.quit = true;

           Log.d("jia", "Service is Destroyed--->onDestroy()");

      }

}

 

MainActivity

package com.jia.bindservice;

 

import android.app.Activity;

import android.app.Service;

import android.content.ComponentName;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.Bundle;

import android.os.IBinder;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

 

public class MainActivity extends Activity {

 

    private Button bind;

    private Button unbind;

    private Button getServiceStatus;

    BindService.MyBinder binder;

    // 定义一个ServiceConnection对象

    private ServiceConnection conn = new ServiceConnection() {

 

        @Override

        public void onServiceDisconnected(ComponentName name) {

            Log.d("jia",

                    "Service DisConnected--->onServiceDisconnected(ComponentName name)");

        }

 

        @Override

        public void onServiceConnected(ComponentName name, IBinder service) {

            Log.d("jia",

                    "Service Connected--->onServiceConnected(ComponentName name, IBinder service)");

            binder = (BindService.MyBinder) service;

 

        }

    };

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

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

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

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

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

        bind.setOnClickListener(new OnClickListener() {

 

            @Override

            public void onClick(View v) {

                bindService(intent, conn, Service.BIND_AUTO_CREATE);

            }

        });

        unbind.setOnClickListener(new OnClickListener() {

 

            @Override

            public void onClick(View v) {

                unbindService(conn);

            }

        });

        getServiceStatus.setOnClickListener(new OnClickListener() {

 

            @Override

            public void onClick(View v) {

                Toast.makeText(MainActivity.this,

                        "Servicecount值为:" + binder.getCount(),

                        Toast.LENGTH_SHORT).show();

            }

        });

    }

 

}

对于ServiceonBind()方法所返回的IBinder对象来说,它可被当成该Service组件所返回的代理对象,Service允许客户端通过该IBinder对象来访问Service内部的数据,这样既可实现客户端与Service之间的通信.

当调用unbindService(conn);来断开与Service的绑定时,会先调用onUnbind(Intent intent)方法然后调用onDestroy()方法.


bindService(intent, conn, Service.BIND_AUTO_CREATE)方法与startService(intent)方法不同的是,多次调用bindService()方法不会进行重复绑定,只调用一次onBind(),而对于每次调用startService()方法绑定Service,系统每次都会回调ServiceonStartCommand()方法一次.


Activity调用bindService()绑定一个已启动的Service,系统只是把Service内部IBinder对象传给Activity,并不会把该Service生命周期完全绑定到该Activity,因而当Activity调用unBindeService()方法取消与该Service的绑定时,也只是切断该ActivityService之间的关联,并不能停止该Service组件.

使用IntentService

Service两个问题:

  1. Service不会专门启动一个单独的进程,Service与它所在应用位于同一个进程中.
  2. Serivice不是一条新的线程,因此不应该在Service中直接处理耗时的任务.

IntentService具有如下特征:

  1. IntentService会创建单独的worker线程来处理所有的Intent请求.
  2. IntentService会创建单独的worker线程来处理onHandleIntent()方法实现的代码,无须处理多线程问题.
  3. 当所有请求处理完成后,IntentService会自动停止,无须调用stopSelf()方法来停止该Service.
  4. ServiceonBind()方法提供了默认实现,默认实现的onBind()方法返回null.
  5. ServiceonStartCommand()方法提供了默认实现,该实现会将请求Intent添加到队列中.

MyIntentService

package com.jia.intentservicetest;

 

import android.app.IntentService;

import android.content.Intent;

import android.util.Log;

 

public class MyIntentService extends IntentService {

 

    public MyIntentService() {

        super("MyIntentService");

    }

 

    @Override

    protected void onHandleIntent(Intent intent) {

        long endTime = System.currentTimeMillis() + 20 * 1000;

        Log.d("jia", "MyIntentService---onHandleIntent(Intent intent)");

        while (System.currentTimeMillis() < endTime) {

            synchronized (this) {

                try {

                    wait(endTime - System.currentTimeMillis());

                } catch (InterruptedException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

        Log.d("jia", "--MyIntentService-耗时任务执行完成---");

    }

 

}

 

1 0
原创粉丝点击