📜  Android-服务

📅  最后修改于: 2021-01-05 04:51:38             🧑  作者: Mango


服务是在后台运行以执行长时间运行的操作而无需与用户交互的组件,即使服务被破坏,它也可以正常工作。服务实际上可以采取两种状态-

Sr.No. State & Description
1

Started

A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.

2

Bound

A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC).

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

Android服务生命周期

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

Sr.No. Callback & Description
1

onStartCommand()

The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). If you implement this method, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService() methods.

2

onBind()

The system calls this method when another component wants to bind with the service by calling bindService(). If you implement this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder object. You must always implement this method, but if you don’t want to allow binding, then you should return null.

3

onUnbind()

The system calls this method when all clients have disconnected from a particular interface published by the service.

4

onRebind()

The system calls this method when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent).

5

onCreate()

The system calls this method when the service is first created using onStartCommand() or onBind(). This call is required to perform one-time set-up.

6

onDestroy()

The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc.

以下框架服务演示了每种生命周期方法-

package com.tutorialspoint;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;

public class HelloService extends Service {
   
   /** indicates how to behave if the service is killed */
   int mStartMode;
   
   /** interface for clients that bind */
   IBinder mBinder;     
   
   /** indicates whether onRebind should be used */
   boolean mAllowRebind;

   /** Called when the service is being created. */
   @Override
   public void onCreate() {
     
   }

   /** The service is starting, due to a call to startService() */
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      return mStartMode;
   }

   /** A client is binding to the service with bindService() */
   @Override
   public IBinder onBind(Intent intent) {
      return mBinder;
   }

   /** Called when all clients have unbound with unbindService() */
   @Override
   public boolean onUnbind(Intent intent) {
      return mAllowRebind;
   }

   /** Called when a client is binding to the service with bindService()*/
   @Override
   public void onRebind(Intent intent) {

   }

   /** Called when The service is no longer used and is being destroyed */
   @Override
   public void onDestroy() {

   }
}

本示例将带您通过简单的步骤来展示如何创建自己的Android服务。请按照以下步骤修改我们在“ Hello World示例”一章中创建的Android应用程序-

Step Description
1 You will use Android StudioIDE to create an Android application and name it as My Application under a package com.example.tutorialspoint7.myapplication as explained in the Hello World Example chapter.
2 Modify main activity file MainActivity.java to add startService() and stopService() methods.
3 Create a new java file MyService.java under the package com.example.My Application. This file will have implementation of Android service related methods.
4 Define your service in AndroidManifest.xml file using tag. An application can have one or more services without any restrictions.
5 Modify the default content of res/layout/activity_main.xml file to include two buttons in linear layout.
6 No need to change any constants in res/values/strings.xml file. Android studio take care of string values
7 Run the application to launch Android emulator and verify the result of the changes done in the application.

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

package com.example.tutorialspoint7.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {
   String msg = "Android : ";

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.d(msg, "The onCreate() event");
   }

   public void startService(View view) {
      startService(new Intent(getBaseContext(), MyService.class));
   }

   // Method to stop the service
   public void stopService(View view) {
      stopService(new Intent(getBaseContext(), MyService.class));
   }
}

以下是MyService.java的内容。该文件可以根据需要实现与服务相关联的一种或多种方法。现在,我们将仅实现两种方法onStartCommand()onDestroy()

package com.example.tutorialspoint7.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
   * Created by TutorialsPoint7 on 8/23/2016.
*/

public class MyService extends Service {
   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }
    
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }

   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

以下将修改AndroidManifest.xml文件的内容。在这里,我们添加了标签以包括我们的服务-




   
        
      
         
            

            
         
      
        
      
   


以下是res / layout / activity_main.xml文件的内容,其中包括两个按钮-


   
   
      
   

   

   

   


让我们尝试运行修改后的Hello World!我们刚刚修改的应用程序。我假设您在进行环境设置时已创建了AVD 。要从Android Studio运行该应用,请打开您项目的活动文件之一,然后点击运行Android StudioRun图标工具栏中的图标。 Android Studio将应用程序安装在您的AVD上并启动它,如果设置和应用程序一切正常,它将显示在“模拟器”窗口下面-

Android服务演示

现在开始您的服务,让我们单击“开始服务”按钮,这将启动服务,并且根据我们在onStartCommand()方法中的编程,一条消息“服务已启动”将出现在模拟器的底部,如下所示:

Android服务启动

要停止服务,可以单击“停止服务”按钮。