Android 服务(Service)

[复制链接]

Android 服务(Service)

发表于 2021-12-28 13:50:54 只看大图 阅读模式 倒序浏览
1032 0 查看全部
  服务是一个后台运行的组件,执行长时间运行且不需要用户交互的任务。即使应用被销毁也依然可以工作。服务基本上包含两种状态 -
状态描述
StartedAndroid的应用程序组件,如活动,通过startService()启动了服务,则服务是Started状态。一旦启动,服务可以在后台无限期运行,即使启动它的组件已经被销毁。
Bound当Android的应用程序组件通过bindService()绑定了服务,则服务是Bound状态。Bound状态的服务提供了一个客户服务器接口来允许组件与服务进行交互,如发送请求,获取结果,甚至通过IPC来进行跨进程通信。  服务拥有生命周期方法,可以实现监控服务状态的变化,可以在合适的阶段执行工作。下面的左图展示了当服务通过startService()被创建时的生命周期,右图则显示了当服务通过bindService()被创建时的生命周期:
services.jpg
  要创建服务,你需要创建一个继承自Service基类或者它的已知子类的Java类。Service基类定义了不同的回调方法和多数重要方法。你不需要实现所有的回调方法。虽然如此,理解所有的方法还是非常重要的。实现这些回调能确保你的应用以用户期望的方式实现。
回调描述
onStartCommand()其他组件(如活动)通过调用startService()来请求启动服务时,系统调用该方法。如果你实现该方法,你有责任在工作完成时通过stopSelf()或者stopService()方法来停止服务。
onBind当其他组件想要通过bindService()来绑定服务时,系统调用该方法。如果你实现该方法,你需要返回IBinder对象来提供一个接口,以便客户来与服务通信。你必须实现该方法,如果你不允许绑定,则直接返回null。
onUnbind()当客户中断所有服务发布的特殊接口时,系统调用该方法。
onRebind()当新的客户端与服务连接,且此前它已经通过onUnbind(Intent)通知断开连接时,系统调用该方法。
onCreate()当服务通过onStartCommand()和onBind()被第一次创建的时候,系统调用该方法。该调用要求执行一次性安装。
onDestroy()当服务不再有用或者被销毁时,系统调用该方法。你的服务需要实现该方法来清理任何资源,如线程,已注册的监听器,接收器等。  下面的主服务演示了每个方法的生命周期 -
  1. package com.runoob.androidservices;

  2. import android.app.Service;
  3. import android.os.IBinder;
  4. import android.content.Intent;
  5. import android.os.Bundle;

  6. public class HelloService extends Service {

  7.     /** 标识服务如果被杀死之后的行为 */
  8.     int mStartMode;

  9.     /** 绑定的客户端接口 */
  10.     IBinder mBinder;

  11.     /** 标识是否可以使用onRebind */
  12.     boolean mAllowRebind;

  13.     /** 当服务被创建时调用. */
  14.     @Override
  15.     public void onCreate() {

  16.     }

  17.     /** 调用startService()启动服务时回调 */
  18.     @Override
  19.     public int onStartCommand(Intent intent, int flags, int startId) {
  20.         return mStartMode;
  21.     }

  22.     /** 通过bindService()绑定到服务的客户端 */
  23.     @Override
  24.     public IBinder onBind(Intent intent) {
  25.         return mBinder;
  26.     }

  27.     /** 通过unbindService()解除所有客户端绑定时调用 */
  28.     @Override
  29.     public boolean onUnbind(Intent intent) {
  30.         return mAllowRebind;
  31.     }

  32.     /** 通过bindService()将客户端绑定到服务时调用*/
  33.     @Override
  34.     public void onRebind(Intent intent) {

  35.     }

  36.     /** 服务不再有用且将要被销毁时调用 */
  37.     @Override
  38.     public void onDestroy() {

  39.     }
  40. }
复制代码
实例  这个例子将通过简单地步骤为你展示如何创建自己的Android服务。按照下面的步骤来修改之前在Hello World实例章节中创建的Android应用程序:
步骤描述
1使用Android Studio IDE来创建Android应用程序并在com.runoob.androidservices包下命名为androidservices。类似Hello World实例章节。
2修改主活动文件MainActivity.java来添加startService()和stopService()方法。
3在包com.runoob.androidservices下创建新的Java文件MyService.java。这个文件将实现Android服务相关的方法。
4在AndroidManifest.xml文件中使用‹service.../>标签来定义服务。应用程序可以有一个或多个服务,没有任何限制。
5修改res/layout/activity_main.xml文件中的默认布局,在线性布局中包含两个按钮。
6不要对res/values/strings.xml文件中的任何常量进行修改。Android Studio会注意字符串值。
7启动Android模拟器来运行应用程序,并验证应用程序所做改变的结果。  下面是主活动文件src/com.runoob.androidservices/MainActivity.java文件所修改的内容。这个文件包含所有基本的生命周期方法。我们添加了startService()和stopService()方法来启动和停止服务。
  1. package com.runoob.androidservices;

  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.Menu;


  5. import android.content.Intent;
  6. import android.view.View;

  7. public class MainActivity extends Activity {

  8.     @Override
  9.     public void onCreate(Bundle savedInstanceState) {
  10.         super.onCreate(savedInstanceState);
  11.         setContentView(R.layout.activity_main);
  12.     }

  13.     @Override
  14.     public boolean onCreateOptionsMenu(Menu menu) {
  15.         getMenuInflater().inflate(R.menu.menu_main, menu);
  16.         return true;
  17.     }

  18.     // Method to start the service
  19.     public void startService(View view) {
  20.         startService(new Intent(getBaseContext(), MyService.class));
  21.     }

  22.     // Method to stop the service
  23.     public void stopService(View view) {
  24.         stopService(new Intent(getBaseContext(), MyService.class));
  25.     }
  26. }
复制代码
  以下是src/com.runoob.androidservices/MyService.java的内容。这个文件可以基于需求实现一个或多个服务关联的方法。对于新人,我们只实现onStartCommand()和onDestroy() -
  1. package com.runoob.androidservices;

  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.IBinder;
  5. import android.widget.Toast;

  6. public class MyService extends Service {

  7.     @Override
  8.     public IBinder onBind(Intent arg0) {
  9.         return null;
  10.     }

  11.     @Override
  12.     public int onStartCommand(Intent intent, int flags, int startId) {
  13.         // Let it continue running until it is stopped.
  14.         Toast.makeText(this, "服务已经启动", Toast.LENGTH_LONG).show();
  15.         return START_STICKY;
  16.     }

  17.     @Override
  18.     public void onDestroy() {
  19.         super.onDestroy();
  20.         Toast.makeText(this, "服务已经停止", Toast.LENGTH_LONG).show();
  21.     }
  22. }
复制代码
  下面将修改AndroidManifest.xml文件。这里添加‹service.../>标签来包含我们的服务:
  1. ‹?xml version="1.0" encoding="utf-8"?>
  2. ‹manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3.     package="com.runoob.androidservices"
  4.     android:versionCode="1"
  5.     android:versionName="1.0">

  6.     ‹uses-sdk
  7.         android:minSdkVersion="13"
  8.         android:targetSdkVersion="22" />

  9.     ‹application
  10.         android:icon="@drawable/ic_launcher"
  11.         android:label="@string/app_name"
  12.         android:theme="@style/AppTheme" >

  13.         ‹activity
  14.             android:name=".MainActivity"
  15.             android:label="@string/title_activity_main" >

  16.             ‹intent-filter>
  17.                 ‹action android:name="android.intent.action.MAIN" />
  18.                 ‹category android:name="android.intent.category.LAUNCHER"/>
  19.             ‹/intent-filter>

  20.         ‹/activity>

  21.         ‹service android:name=".MyService" />

  22.     ‹/application>

  23. ‹/manifest>
复制代码
  以下是res/layout/activity_main.xml文件的内容,包含两个按钮:
  1. ‹RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  3.     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
  4.     android:paddingRight="@dimen/activity_horizontal_margin"
  5.     android:paddingTop="@dimen/activity_vertical_margin"
  6.     android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

  7.     ‹TextView
  8.         android:id="@+id/textView1"
  9.         android:layout_width="wrap_content"
  10.         android:layout_height="wrap_content"
  11.         android:text="Android 服务实例"
  12.         android:layout_alignParentTop="true"
  13.         android:layout_centerHorizontal="true"
  14.         android:textSize="30dp" />

  15.     ‹TextView
  16.         android:id="@+id/textView2"
  17.         android:layout_width="wrap_content"
  18.         android:layout_height="wrap_content"
  19.         android:text="www.runoob.com"
  20.         android:textColor="#ff87ff09"
  21.         android:textSize="30dp"
  22.         android:layout_above="@+id/imageButton"
  23.         android:layout_centerHorizontal="true"
  24.         android:layout_marginBottom="40dp" />

  25.     ‹ImageButton
  26.         android:layout_width="wrap_content"
  27.         android:layout_height="wrap_content"
  28.         android:id="@+id/imageButton"
  29.         android:src="@drawable/ic_launcher"
  30.         android:layout_centerVertical="true"
  31.         android:layout_centerHorizontal="true" />

  32.     ‹Button
  33.         android:layout_width="wrap_content"
  34.         android:layout_height="wrap_content"
  35.         android:id="@+id/button2"
  36.         android:text="启动服务"
  37.         android:onClick="startService"
  38.         android:layout_below="@+id/imageButton"
  39.         android:layout_centerHorizontal="true" />

  40.     ‹Button
  41.         android:layout_width="wrap_content"
  42.         android:layout_height="wrap_content"
  43.         android:text="停止服务"
  44.         android:id="@+id/button"
  45.         android:onClick="stopService"
  46.         android:layout_below="@+id/button2"
  47.         android:layout_alignLeft="@+id/button2"
  48.         android:layout_alignStart="@+id/button2"
  49.         android:layout_alignRight="@+id/button2"
  50.         android:layout_alignEnd="@+id/button2" />

  51. ‹/RelativeLayout>
复制代码
  下面是res/values/strings.xml的内容,来定义两个新的常量:
  1. ‹?xml version="1.0" encoding="utf-8"?>
  2. ‹resources>

  3.     ‹string name="app_name">Android Services‹/string>
  4.     ‹string name="title_activity_main">MainActivity‹/string>
  5.     ‹string name="menu_settings">Settings‹/string>
  6.     ‹string name="action_settings">Settings‹/string>

  7. ‹/resources>
复制代码
  让我们运行刚刚修改的My Application应用程序。我假设你已经在安装环境时创建了AVD。打开你的项目中的活动文件,点击工具栏中的 eclipse_run.png 图标来在Android Studio中运行应用程序。Android Studio在AVD上安装应用程序并启动它。如果一切顺利,将在模拟器窗口上显示如下:
android_services_1-1.png
  现在点击"启动服务"按钮来启动服务,这将执行我们编写的onStartCommand()方法,一条"服务已经启动"的消息在模拟器的底部出现,如下:
android_services_2-1.png
  点击底部的"停止服务"按钮,可以停止服务。

来源:菜鸟教程
回复

使用道具 举报

游客~
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|极客同行 ( 蜀ICP备17009389号-1 )

© 2013-2016 Comsenz Inc. Powered by Discuz! X3.4