Service

Android 完全掌握Service_第1张图片

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绑定的所有客户端都断开时回调该方法

packagecom.jia.fistservice;

importandroid.app.Service;

importandroid.content.Intent;

importandroid.os.IBinder;

importandroid.util.Log;

publicclassFirstServiceextendsService {

@Override

publicIBinder onBind(Intentintent) {

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

returnnull;

}

@Override

publicvoidonCreate() {

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

super.onCreate();

}

@Override

publicintonStartCommand(Intentintent,intflags,intstartId) {

Log.d("jia",

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

returnsuper.onStartCommand(intent,flags,startId);

}

@Override

publicvoidonDestroy() {

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:


多次启动与销毁:

Android 完全掌握Service_第2张图片

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. Android虚拟键盘挡住输入框的处理方法
  2. android intent 传递对象需要序列化实现Parcelable接口
  3. Android中使用AndroidTestCase的方法实例
  4. android中动态实现全屏和动态退出全屏方法
  5. Android延时执行的几种方法
  6. Android 获取当前语言的方法1
  7. android.util.Log常用的方法
  8. Android应用程序获取ROOT权限的方法(android中如何通过代码检测
  9. android 添加预装的方法

随机推荐

  1. 【转】Android(安卓)kernel启动流程
  2. android 退出机制
  3. android字体闪烁动画(线程)
  4. android应用程序设置全屏
  5. Android(安卓)2.2 单点触摸支持的问题
  6. 安卓版本和Api Level
  7. Android(安卓)P WiFi自动连接评分机制
  8. Android(安卓)activity的生命周期
  9. android > 布局文件 > 背景圆角
  10. ScrollView嵌套webview因焦点问题导致自