个性化阅读
专注于IT技术分析

android service使用教程

本文概述

Android服务是用于在后台执行操作(例如播放音乐,处理网络交易,与内容提供者进行交互等)的组件。它没有任何UI(用户界面)。

即使应用程序被破坏,该服务也会无限期地在后台运行。

此外,服务可以受组件限制以执行交互性和进程间通信(IPC)。

android.app.Service是ContextWrapper类的子类。

注意:Android服务不是线程或单独的进程。

Android服务的生命周期

服务可以有两种形式。服务的生命周期可以遵循两种不同的路径:启动或绑定。

  1. 已开始

1)开始服务

当组件(如活动)调用startService()方法时,服务将启动,现在该服务将无限期在后台运行。它由stopService()方法停止。该服务可以通过调用stopSelf()方法来停止自身。

2)绑定服务

当另一个组件(例如客户端)调用bindService()方法时,服务便被绑定。客户端可以通过调用unbindService()方法来取消绑定服务。

在所有客户端解除绑定服务之前,无法停止该服务。

通过背景音乐示例了解启动和绑定服务

假设我想在后台播放音乐,因此调用startService()方法。但是我想获取正在播放的当前歌曲的信息,因此我将绑定提供有关当前歌曲信息的服务。


Android服务示例

让我们看一下在后台播放音频的android服务示例。即使你切换到其他活动,音频也不会停止。要停止音频,你需要停止服务。

activity_main.xml

从面板上拖动3个按钮,现在activity_main.xml将如下所示:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="example.srcmini02.com.androidservice.MainActivity">


    <Button
        android:id="@+id/buttonStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="74dp"
        android:text="Start Service" />

    <Button
        android:id="@+id/buttonStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Stop Service" />

    <Button
        android:id="@+id/buttonNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="63dp"
        android:text="Next Page" />
</RelativeLayout>

activity_next.xml

它是下一个活动的布局文件。

它仅包含一个textview显示消息下一页

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="example.srcmini02.com.androidservice.NextPage">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="200dp"
        android:text="Next Page"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

服务等级

现在,通过继承Service类并覆盖其回调方法来创建服务实现类。

package example.srcmini02.com.androidservice;

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

public class MyService extends Service {
    MediaPlayer myPlayer;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();

        myPlayer = MediaPlayer.create(this, R.raw.sun);
        myPlayer.setLooping(false); // Set looping
    }
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        myPlayer.start();
    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
        myPlayer.stop();
    }
}

活动类

现在创建MainActivity类以执行事件处理。在这里,我们正在编写代码以启动和停止服务。此外,在buttonNext上调用第二个活动。

package example.srcmini02.com.androidservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    Button buttonStart, buttonStop, buttonNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStart = findViewById(R.id.buttonStart);
        buttonStop = findViewById(R.id.buttonStop);
        buttonNext =  findViewById(R.id.buttonNext);

        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
        buttonNext.setOnClickListener(this);


    }
    public void onClick(View src) {
        switch (src.getId()) {
            case R.id.buttonStart:

                startService(new Intent(this, MyService.class));
                break;
            case R.id.buttonStop:
                stopService(new Intent(this, MyService.class));
                break;
            case R.id.buttonNext:
                Intent intent=new Intent(this, NextPage.class);
                startActivity(intent);
                break;
        }
    }
}

NextPage类

现在,创建另一个活动。

package example.srcmini02.com.androidservice;

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

public class NextPage extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);
    }
}

在AndroidManifest.xml文件中声明服务

最后,在清单文件中声明服务。

让我们看看完整的AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.srcmini02.com.androidservice">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NextPage"></activity>
        <service
            android:name=".MyService"
            android:enabled="true" />
    </application>

</manifest>

输出:

赞(0)
未经允许不得转载:srcmini » android service使用教程

评论 抢沙发

评论前必须登录!