Android学习-服务 Service 基础

Android Service

服务(Service)

是Android中的四大组件之一,它能够长期在后台运行,服务是不需要提供用户界面。即使用户切到另一应用程序,服务仍可以在后台运行。

1.Service 的创建

1.Service 的创建
服务创建就是新建一个java类,让他继承Service,添加未实现的方法

	@Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

2.在清单文件中配置
其实这就类似javaweb在web.xml配置过滤器一样,在AndroidManifest.xml文件中application节点下配置,与activity同级;
一下贴出所有的 application 节点,方便理解

<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>
        <service android:name=".RandomService">
            <intent-filter>
                <action android:name="www.lyd.random"/>
            </intent-filter>
        </service>
    </application>

主要代码:

		<service android:name=".RandomService">//服务类,可以直接复制限定名
            <intent-filter>
                <action android:name="www.lyd.random"/>//对应的action
            </intent-filter>
        </service>

2. Service 的生命周期

  • onCreate: 创建服务
  • onStart: 开始服务(2.0以下,已经废弃)
  • onStartCommand 开始服务(2.0以及上使用)

1、直接启动服务
当 startService(intent);//启动service 时候
启动服务可以多次运行,但是oncreate只执行一次

服务会执行onCreate()  onStartCommand()方法,服务处于运行状态,直到自身调用stopSelf()方法或者其他组件调用stopService()方法时服务停止,最终被系统销毁。
服务会长期的在后台运行,并且服务的状态与开启者的状态没有关系。

当启动服务时,会出现
在这里插入图片描述
再看一下代码

Intent intent = new Intent();//添加action意图
intent.setAction("www.lyd.random");

这个就是android5.0的兼容问题,说以要加上

intent.setPackage(MainActivity.this.getPackageName());//兼容Android 5.0

首先运行的是

@Override
    public void onCreate() {
        Log.i("onCreate","服务已经启动");//只会启动一次,在服务没停止之前,不管在启动多少次服务,只运行一次
        super.onCreate();
    }

其次

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int num = (int) (Math.random()*10);
        Log.i("random","num=" + num);
        return super.onStartCommand(intent, flags, startId);
    }

1
多次点击
2
stopService(intent);//销毁服务,未开启时不会销毁
3
2、使用绑定服务

服务会执行onCreate() -> onBind()方法,服务处于绑定状态, 客户端通过unbindService()方法关闭连接,解除绑定时,系统将直接销毁服务。
服务与开启者的状态有关,当调用者销毁了,服务也会被销毁。

绑定服务只能运行一次,也就是绑定之后不能再继续绑定服务
这里就不粘贴代码,最后放总代码

绑定服务会先执行onCreate(),然后onBind方法,最后执行ServiceConnection的回调方法onServiceConnected;
运行绑定服务
在这里插入图片描述
发现,onServiceConnected没有输出

		@Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("MainActivity","服务已经连接 传递信息");
        }

原因就是在onBind返回的是null,应该返回一个IBinder,在onServiceConnected可以调用。

多次运行绑定服务也只会运行一次
2
在点击启动服务,只会运行onStartCommand
在这里插入图片描述
最后解除绑定
在这里插入图片描述

3. Service 的通信

  • 在Android系统中,服务的通信方式有两种,一种是本地服务通信,一种是远程服务通信。

  • 本地服务通信是指应用程序内部的通信,而远程服务通信是指两个应用程序之间的通信。使用这两种方式进行通信时必须满足一个前提,就是服务必须以绑定方式开启

粘贴一张上课ppt内容
在这里插入图片描述

就介绍到这里,有问题请帮忙指证,谢谢!

接下来粘贴代码

AndroidManifest.xml

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

    <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>
        <service android:name=".RandomService">
            <intent-filter>
                <action android:name="www.lyd.random"/>
            </intent-filter>
        </service>
    </application>

</manifest>

activity.layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/start_Service"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="启动服务"/>
        <Button
            android:id="@+id/stop_Service"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="停止服务"/>
        <Button
            android:id="@+id/upBind_Service"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="绑定服务"/>
        <Button
            android:id="@+id/outBind_Service"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="解绑服务"/>

    </LinearLayout>
</LinearLayout>

MainActivity.java

package com.example.myservice;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
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.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private onClickListener listener = new onClickListener();
    private ReceiveServiceMessage conn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.start_Service).setOnClickListener(listener);
        findViewById(R.id.stop_Service).setOnClickListener(listener);
        findViewById(R.id.upBind_Service).setOnClickListener(listener);
        findViewById(R.id.outBind_Service).setOnClickListener(listener);
        conn = new ReceiveServiceMessage();
    }

    class ReceiveServiceMessage implements ServiceConnection{

        //绑定回调方法
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            RandomService.myBinder Binder = (RandomService.myBinder)service;
            Log.i("MainActivity","服务已经连接 传递信息" + Binder.getNumber());

        }

        //解绑回调方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("MainActivity","服务断开连接");
        }
    }


    class onClickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();//添加action意图
            intent.setAction("www.lyd.random");
            intent.setPackage(MainActivity.this.getPackageName());//兼容Android 5.0
            switch (v.getId()){
                case R.id.start_Service:
                    //显示意图启动Service
                    /**
                     * Intent intent = new Intent(com.example.myservice.RandomService.class);
                     * context.startService(intent);
                     **/
                    startService(intent);//启动service
                    break;
                case R.id.stop_Service:
                    stopService(intent);//销毁服务,未开启时不会销毁
                    break;
                case R.id.upBind_Service:
                    bindService(intent,conn, Service.BIND_AUTO_CREATE);//绑定服务只执行一次
                    break;
                case R.id.outBind_Service:
                    Boolean isBind = bindService(intent, conn, Context.BIND_AUTO_CREATE);
                    if(isBind){
                        unbindService(conn);
                        isBind = false;
                    }
                    break;
            }
        }
    }
}

RandomService.java

package com.example.myservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class RandomService extends Service {

    class myBinder extends Binder{
        int number;

        public int getNumber() {
            return number;
        }

        public void setNumber(int number) {
            this.number = number;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        myBinder MyBinder = new myBinder();
        int number = (int) (Math.random()*100) + 1;
        String str = "onBind通信, 随机信息:" + number;
        Log.i("onBind","绑定了服务 "+str);
        MyBinder.setNumber(number);
        return MyBinder;//要返回一个Binder,返回null,onServiceConnected就不会进行
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("onUnBind","解除绑定服务");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        Log.i("onCreate","服务已经启动");//只会启动一次,在服务没停止之前,不管在启动多少次服务,只运行一次
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int num = (int) (Math.random()*10);
        Log.i("random","num=" + num);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i("onDestroy","服务已经销毁");
        super.onDestroy();
    }
}

谢谢大家的阅读!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的 Android 学习路线: 1. Java基础知识:Android 应用程序是使用 Java 语言编写的,因此你需要学习 Java 编程语言的基础知识。 2. Android基础知识:你需要学习 Android 平台的基本架构、应用程序组件(例如 Activity、Service、BroadcastReceiver 和 ContentProvider)以及如何将它们组合在一起构建应用程序。 3. 用户界面设计:这是一个重要的方面,因为应用程序的用户界面是用户与应用程序交互的关键部分。你需要学习如何设计用户友好的界面,如何处理用户输入和如何响应不同的用户事件。 4. 数据库操作:许多 Android 应用程序都需要使用数据库来存储和检索数据。你需要学习如何在 Android 应用程序使用 SQLite 数据库。 5. 网络编程:许多 Android 应用程序需要与网络进行通信,例如下载数据、上传数据和与远程服务器进行通信。你需要学习如何在 Android 应用程序进行网络编程。 6. 多媒体处理:许多 Android 应用程序需要处理音频、视频和图像等媒体,你需要学习如何在 Android 应用程序处理这些媒体。 7. 第三方库:为了简化开发过程,你可以使用第三方库,例如 Retrofit、Glide 和 EventBus 等,来实现常见的功能。 8. Android Studio:Android Studio 是 Android 应用程序开发的官方 IDE,你需要学习如何使用它来构建应用程序。 以上是一个简单的 Android 学习路线,你可以根据自己的需求和兴趣来进行深入学习

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个有梦有戏的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值