课程表

Android Studio

Android SDK

工具箱
速查手册

安卓 Services

当前位置:免费教程 » 移动开发 » Android

服务是一个在后台运行的组件,无需与用户交互即可执行长时间运行的操作,即使应用程序被销毁也能正常运行.服务基本上可以采用两种状态 :

Sr.No.State&描述
1

Started

当应用程序组件(例如活动)通过调用 startService()启动它时,服务启动 .一旦启动,服务可以无限期地在后台运行,即使启动它的组件被销毁.

2

Bound

服务绑定当应用程序组件通过调用 bindService()绑定到它时.绑定服务提供了一个客户端 - 服务器接口,允许组件与服务交互,发送请求,获取结果,甚至跨进程间通信(IPC)进程.

服务具有生命周期回调方法,您可以实施这些方法来监视服务状态的变化,并且您可以在适当的阶段执行工作.左侧的下图显示了使用startService()创建服务时的生命周期,右侧的图显示了使用bindService()创建服务时的生命周期:(图片提供:android.com)

1.jpg

要创建服务,您创建一个扩展Service基类或其现有子类之一的Java类.。Service 基类定义了各种回调方法,下面给出了最重要的回调方法.您不需要实现所有回调方法。但是,了解每一个并实现那些确保您的应用程序的行为符合用户期望的方式非常重要。

Sr.No.Callback&说明
1

onStartCommand()

当另一个组件(例如活动)通过调用 startService()请求启动服务时,系统会调用此方法.如果实现此方法,则通过调用 stopSelf()或 stopService()方法,您有责任在工作完成后停止服务.

2

onBind()

当另一个组件想通过调用 bindService()与服务绑定时,系统调用此方法.如果实现此方法,则必须通过返回 IBinder 对象来提供客户端用于与服务通信的接口.您必须始终实现此方法,但如果您不想允许绑定,则应返回 null .

3

onUnbind()

当所有客户端与服务发布的特定接口断开连接时,系统会调用此方法.

4

onRebind()

系统在新客户端连接时调用此方法之前已通知其所有已断开连接的 onUnbind(意图).

5

onCreate()

系统首次使用 onStartCommand()或 onBind()创建服务时调用此方法.此调用是执行一次性设置所必需的.

6

onDestroy()

当服务不再使用且正在销毁时,系统会调用此方法.您的服务应该实现此操作以清理任何资源,如线程,注册的侦听器,接收器等.

以下骨架服务演示了每个生命周期方法 :

  1. package com.it1352;
  2.  
  3. import android.app.Service;
  4. import android.os.IBinder;
  5. import android.content.Intent;
  6. import android.os.Bundle;
  7.  
  8. public class HelloService extends Service {
  9.    
  10.    /** indicates how to behave if the service is killed */
  11.    int mStartMode;
  12.    
  13.    /** interface for clients that bind */
  14.    IBinder mBinder;     
  15.    
  16.    /** indicates whether onRebind should be used */
  17.    boolean mAllowRebind;
  18.  
  19.    /** Called when the service is being created. */
  20.    @Override
  21.    public void onCreate() {
  22.      
  23.    }
  24.  
  25.    /** The service is starting, due to a call to startService() */
  26.    @Override
  27.    public int onStartCommand(Intent intent, int flags, int startId) {
  28.       return mStartMode;
  29.    }
  30.  
  31.    /** A client is binding to the service with bindService() */
  32.    @Override
  33.    public IBinder onBind(Intent intent) {
  34.       return mBinder;
  35.    }
  36.  
  37.    /** Called when all clients have unbound with unbindService() */
  38.    @Override
  39.    public boolean onUnbind(Intent intent) {
  40.       return mAllowRebind;
  41.    }
  42.  
  43.    /** Called when a client is binding to the service with bindService()*/
  44.    @Override
  45.    public void onRebind(Intent intent) {
  46.  
  47.    }
  48.  
  49.    /** Called when The service is no longer used and is being destroyed */
  50.    @Override
  51.    public void onDestroy() {
  52.  
  53.    }
  54. }


示例

此示例将指导您完成简单操作显示如何创建自己的Android服务的步骤。按照以下步骤修改我们在 Hello World示例章节中创建的Android应用程序:

Step描述
1您将使用Android StudioIDE创建一个Android应用程序,并将其命名为包裹下的我的应用程序 com.example.it13527.myapplication ,如 Hello World Example 章节中所述.
2修改主活动文件 MainActivity.java 以添加 startService()和 stopService()方法.
3创建一个新的包 com.example.My Application 下的java文件 MyService.java .此文件将实现与Android服务相关的方法.
4定义使用< service .../>在 AndroidManifest.xml 文件中提供服务标签.一个应用程序可以有一个或多个服务,没有任何限制.
5修改 res/layout/activity_main.xml 文件的默认内容,使其包含线性布局中的两个按钮.
6无需更改 res/values/strings.xml 文件中的任何常量. Android工作室负责字符串值
7运行应用程序以启动Android模拟器并验证应用程序中所做更改的结果.

以下是修改后的主活动文件的内容 MainActivity.java 的.该文件可以包括每个基本生命周期方法.我们添加了 startService()和 stopService()方法来启动和停止服务.

  1. package com.example.it13527.myapplication;
  2.  
  3. import android.content.Intent;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.os.Bundle;
  6.  
  7. import android.os.Bundle;
  8. import android.app.Activity;
  9. import android.util.Log;
  10. import android.view.View;
  11.  
  12. public class MainActivity extends Activity {
  13.    String msg = "Android : ";
  14.  
  15.    /** Called when the activity is first created. */
  16.    @Override
  17.    public void onCreate(Bundle savedInstanceState) {
  18.       super.onCreate(savedInstanceState);
  19.       setContentView(R.layout.activity_main);
  20.       Log.d(msg, "The onCreate() event");
  21.    }
  22.  
  23.    public void startService(View view) {
  24.       startService(new Intent(getBaseContext(), MyService.class));
  25.    }
  26.  
  27.    // Method to stop the service
  28.    public void stopService(View view) {
  29.       stopService(new Intent(getBaseContext(), MyService.class));
  30.    }
  31. }

以下是 MyService.java 的内容.此文件可以根据需要实现与Service关联的一个或多个方法.现在我们只实现两个方法 onStartCommand()和 onDestroy() :

  1. package com.example.it13527.myapplication;
  2.  
  3. import android.app.Service;
  4. import android.content.Intent;
  5. import android.os.IBinder;
  6. import android.support.annotation.Nullable;
  7. import android.widget.Toast;
  8.  
  9. /**
  10.    * Created by TutorialsPoint7 on 8/23/2016.
  11. */
  12.  
  13. public class MyService extends Service {
  14.    @Nullable
  15.    @Override
  16.    public IBinder onBind(Intent intent) {
  17.       return null;
  18.    }
  19.    @Override
  20.    public int onStartCommand(Intent intent, int flags, int startId) {
  21.       // Let it continue running until it is stopped.
  22.       Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
  23.       return START_STICKY;
  24.    }
  25.  
  26.    @Override
  27.    public void onDestroy() {
  28.       super.onDestroy();
  29.       Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
  30.    }
  31. }

以下是 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.example.it13527.myapplication">
  4.  
  5.    <application
  6.       android:allowBackup="true"
  7.       android:icon="@mipmap/ic_launcher"
  8.       android:label="@string/app_name"
  9.       android:supportsRtl="true"
  10.       android:theme="@style/AppTheme">
  11.       <activity android:name=".MainActivity">
  12.          <intent-filter>
  13.             <action android:name="android.intent.action.MAIN" />
  14.  
  15.             <category android:name="android.intent.category.LAUNCHER" />
  16.          </intent-filter>
  17.       </activity>
  18.       <service android:name=".MyService" />
  19.    </application>
  20.  
  21. </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.    
  8.    <TextView
  9.       android:id="@+id/textView1"
  10.       android:layout_width="wrap_content"
  11.       android:layout_height="wrap_content"
  12.       android:text="Example of services"
  13.       android:layout_alignParentTop="true"
  14.       android:layout_centerHorizontal="true"
  15.       android:textSize="30dp" />
  16.       
  17.    <TextView
  18.       android:id="@+id/textView2"
  19.       android:layout_width="wrap_content"
  20.       android:layout_height="wrap_content"
  21.       android:text="Tutorials point "
  22.       android:textColor="#ff87ff09"
  23.       android:textSize="30dp"
  24.       android:layout_above="@+id/imageButton"
  25.       android:layout_centerHorizontal="true"
  26.       android:layout_marginBottom="40dp" />
  27.  
  28.    <ImageButton
  29.       android:layout_width="wrap_content"
  30.       android:layout_height="wrap_content"
  31.       android:id="@+id/imageButton"
  32.       android:src="@drawable/abc"
  33.       android:layout_centerVertical="true"
  34.       android:layout_centerHorizontal="true" />
  35.  
  36.    <Button
  37.       android:layout_width="wrap_content"
  38.       android:layout_height="wrap_content"
  39.       android:id="@+id/button2"
  40.       android:text="Start Services"
  41.       android:onClick="startService"
  42.       android:layout_below="@+id/imageButton"
  43.       android:layout_centerHorizontal="true" />
  44.  
  45.    <Button
  46.       android:layout_width="wrap_content"
  47.       android:layout_height="wrap_content"
  48.       android:text="Stop Services"
  49.       android:id="@+id/button"
  50.       android:onClick="stopService"
  51.       android:layout_below="@+id/button2"
  52.       android:layout_alignLeft="@+id/button2"
  53.       android:layout_alignStart="@+id/button2"
  54.       android:layout_alignRight="@+id/button2"
  55.       android:layout_alignEnd="@+id/button2" />
  56.  
  57. </RelativeLayout>

让我们尝试运行我们刚修改过的修改过的 Hello World!应用程序。我假设您在进行环境设置时创建了 AVD。要从Android工作室运行应用程序,请打开项目的一个活动文件,然后单击运行Android StudioRun Icon icon从工具栏. Android Studio会在您的AVD上安装该应用并启动它,如果您的设置和应用程序一切正常,它将显示以下模拟器窗口 :

1.png

现在开始服务,点击启动服务按钮,这将启动服务,根据我们在 onStartCommand()方法中的编程,消息 Service Started 将出现在模拟器的底部,如下 :

2.png

要停止服务,可以单击"Stop Services"按钮。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号