Android之Service学习

来源:互联网 发布:java开发实战经典 编辑:程序博客网 时间:2024/05/16 06:35

什么是Service

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

Service和Thread

Service:耗时操作且不需要用户交互
Thread:用户需要和应用程序进行交互

使用Service的方式

startService():调用者和服务之间没有联系,即使调用者退出了,服务仍然进行 [onCreate()-->onStartCommand()-->startService()-onDestory()]

bindService():调用者和服务绑在一起,调用者一旦退出服务也就终止[onCreate()-->onBind()-->onUnbind()-->onDestory()]

通过startService()使用Service

1.编写类继承Service或其子类

2.复写方法:onStartCommand() onBind() onCreate() onDestroy()

3.在manifest文件中声服务<service android:name=".Service" />

4.启动服务

5.关闭服务

三个常量

START_STICKY:当服务进行在运行时被杀死,系统将会把它值为started状态,但是并不保存其传递的Intent对象
START_NOT_STICKY:当服务进行在运行时被杀死,并且没有新的Intent对象传递过来,统将会把它值为started状态,但是并不会再次创建进程,直到startService(Intent)方法被调用。
START_REDELIVER_INTENT:当服务进行在运行时被杀死,它将会间隔一段时间后重新被创建,并且最后一个传递的Intent对象将会再次传递过来。

例子

1.布局文件为两个按钮

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"    android:orientation="vertical" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />        <Buttonandroid:id="@+id/btnStartService"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Start Service"/><Buttonandroid:id="@+id/btnStopService"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Stop Service"/></LinearLayout>
2.继承Service写自己的服务类

package com.sl.servicedemo;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class ExampleService extends Service {private static final String TAG="ExampleService";@Overridepublic void onCreate(){Log.i(TAG, "ExampleService-->onCreate");super.onCreate();}@Overridepublic void onStart(Intent intent, int startId){Log.i(TAG, "ExampleService-->onStart");super.onStart(intent, startId);}@Overridepublic void onDestroy(){Log.i(TAG, "ExampleService-->onDestroy");super.onDestroy();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId){Log.i(TAG, "ExampleService-->onStartCommand");return START_NOT_STICKY;}@Overridepublic IBinder onBind(Intent intent) {return null;}}
3.主程序中调用服务类

package com.sl.servicedemo;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.app.Activity;import android.content.Intent;public class MainActivity extends Activity {private Button btnStartService;private Button btnStopService;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnStartService = (Button) findViewById(R.id.btnStartService);btnStopService = (Button) findViewById(R.id.btnStopService);btnStartService.setOnClickListener(listener);btnStopService.setOnClickListener(listener);}private OnClickListener listener=new OnClickListener(){@Overridepublic void onClick(View v){Intent intent=new Intent(MainActivity.this, ExampleService.class);switch (v.getId()){case R.id.btnStartService:startService(intent);break;case R.id.btnStopService:stopService(intent);break;default:break;}}};}
4.在AndroidManifest中声明

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.sl.servicedemo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.sl.servicedemo.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".ExampleService" />            </application></manifest>


通过bindService()使用Service

什么是Bound Services

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

创建Bound Services

当创建一个能提供绑定功能的服务时,我们必须提供一个IBinder对象,客户端能使用这个对象与服务进行交互。在Android中有三种方式定义方式:
1.扩展Binder类
2.使用Messenger
3.使用AIDL (Android Interface Definition Language)

通过扩展Binder类创建创建Bound Services

步骤:
a.在Service类中,创建一个Binder实例,包含客户端能调用的公共方法,返回当前服务对象
b.在onBind()方法中返回Binder实例
c.在客户端,从onServiceConnected()方法中获得Binder实例

例子

1.布局文件为两个按钮

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><Buttonandroid:id="@+id/btnStartBinderService"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Start BinderService"/><Buttonandroid:id="@+id/btnStopBinderService"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Stop BinderService"/></LinearLayout>

2.继承Service写自己的服务类

package com.sl.servicedemo;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class BinderService extends Service{private static final String TAG = "BinderService";private MyBinder binder =new MyBinder();public class MyBinder extends Binder{public BinderService getService(){return BinderService.this;}}@Overridepublic IBinder onBind(Intent intent){return binder;}public void MyMethod(){Log.i(TAG, "MyMethod()");}}

3.主程序中调用服务类

package com.sl.servicedemo;import com.sl.servicedemo.BinderService.MyBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Context;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 BinderActivity extends Activity{private Button btnStartBinderService;private Button btnStopBinderService;private Boolean isConnected = false;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.binder);btnStartBinderService=(Button)findViewById(R.id.btnStartBinderService);btnStopBinderService=(Button)findViewById(R.id.btnStopBinderService);btnStartBinderService.setOnClickListener(listener);btnStopBinderService.setOnClickListener(listener);}private OnClickListener listener=new OnClickListener(){@Overridepublic void onClick(View v){switch (v.getId()){case R.id.btnStartBinderService:bindService();break;case R.id.btnStopBinderService:unBind();break;default:break;}}};private void unBind(){if (isConnected){unbindService(conn);}}private void bindService(){Intent intent=new Intent(BinderActivity.this, BinderService.class);bindService(intent, conn, Context.BIND_AUTO_CREATE);}private ServiceConnection conn=new ServiceConnection(){@Overridepublic void onServiceDisconnected(ComponentName name){isConnected=false;}@Overridepublic void onServiceConnected(ComponentName name, IBinder binder){MyBinder myBinder= (MyBinder)binder;BinderService service=myBinder.getService();service.MyMethod();isConnected=true;}};}
4.在AndroidManifest中声明

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.sl.servicedemo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.sl.servicedemo.BinderActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <service android:name=".BinderService" />            </application></manifest>


IntentService使用

IntentService是Service类的子类,用来处理异步请求,不能同时处理多个请求。客户端通过startService(Intent)方法传递请求给IntentService,IntentService通过worker thread处理每个Intent对象,执行完所有工作后自动停止Service。 

步骤:

1.写构造方法
2.复写onHandleIntent()方法

IntentService执行如下操作 

创建一个与应用程序主线程分开worker thread用来处理所有通过传递过来的Intent请求
创建一个work queue,一次只传递一个intent到onHandleIntent()方法中,从而不用担心多线程带来的问题
当处理完所有请求后自动停止服务,而不需要我们自己调用stopSelf()方法
默认实现了onBind()方法,返回值为null
默认实现了onStartCommand()方法,这个方法将会把我们的intent放到work queue中,然后在onHandleIntent()中执行。

例子

1.布局文件为两个按钮

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><Buttonandroid:id="@+id/btnStartNormalService"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Start NormalService"/><Buttonandroid:id="@+id/btnStartIntentService"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Start IntentService"/></LinearLayout>

2.继承Service写自己的服务类

package com.sl.servicedemo;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class MyService extends Service{protected static final String TAG = "IntentActivity";@Overridepublic void onCreate(){super.onCreate();}@Overridepublic void onDestroy(){super.onDestroy();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId){//try//{//Log.i(TAG, "MyService线程ID:"+Thread.currentThread().getId());//Log.i(TAG, "文件下载....");//Thread.sleep(2000);//} catch (InterruptedException e)//{//e.printStackTrace();//}new MyThread().start();return START_STICKY;}@Overridepublic IBinder onBind(Intent intent){return null;}private class MyThread extends Thread{@Overridepublic void run(){try{Log.i(TAG, "MyService线程ID:"+Thread.currentThread().getId());Log.i(TAG, "文件下载....");Thread.sleep(2000);} catch (InterruptedException e){e.printStackTrace();}}}}
3.继承IntentService写自己的服务类

package com.sl.servicedemo;import android.app.IntentService;import android.content.Intent;import android.util.Log;public class ExampleIntentService extends IntentService{protected static final String TAG = "IntentActivity";public ExampleIntentService(){super("ExampleIntentService");}@Overrideprotected void onHandleIntent(Intent intent){try{Log.i(TAG, "MyService线程ID:"+Thread.currentThread().getId());Log.i(TAG, "文件下载....");Thread.sleep(2000);} catch (InterruptedException e){e.printStackTrace();}}}

4.主程序中调用服务类

package com.sl.servicedemo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class IntentActivity extends Activity{protected static final String TAG = "IntentActivity";private Button btnStartNormalService;private Button btnStartIntentService;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.intent);btnStartNormalService = (Button) findViewById(R.id.btnStartNormalService);btnStartIntentService = (Button) findViewById(R.id.btnStartIntentService);btnStartNormalService.setOnClickListener(listener);btnStartIntentService.setOnClickListener(listener);}private OnClickListener listener=new OnClickListener(){@Overridepublic void onClick(View v){Intent intent;switch (v.getId()){case R.id.btnStartNormalService:intent=new Intent(IntentActivity.this, MyService.class);Log.i(TAG, "主线程ID:"+Thread.currentThread().getId());startService(intent);break;case R.id.btnStartIntentService:intent=new Intent(IntentActivity.this, ExampleIntentService.class);Log.i(TAG, "主线程ID:"+Thread.currentThread().getId());startService(intent);break;default:break;}}};}

5.在AndroidManifest中声明

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.sl.servicedemo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.sl.servicedemo.IntentActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity><service android:name=".MyService"/><service android:name=".ExampleIntentService"/>            </application></manifest>

好了,这里只是简单地使用了Service,以后我们可以根据需要再深入了解学习!


0 0
原创粉丝点击