(8)服务


服务是一个长期运行在后台的用户组件,没有用户界面,可以在后台执行很多任务,例如下载文件,播放音乐

8.1 服务概述

Service是Android的四大组件之一,能能够在后台长时间执行操作,且没有用户界面,服务可以去其他组件进行交互,一般由Activity启动,但是它不依赖于Activity,Activity的生命周期结束时,自己的服务也不会停止

服务的应用场景主要有两个,分别是后台运行和跨进程访问

后台运行

顾名思义,可以常驻后台运行,不用提供界面信息,只有当系统回收内存资源的时候才会被销毁

跨进程访问

服务被其他应用组件启动时,即使用户切换到其他应用程序,服务依然会在后台运行,服务时运行在主线程中,不是子线程,它要处理的耗时操作需要开启子线程进行处理,否则会出现ANR(程序没有响应)异常

8.2 服务的创建

与创建广播类似

image-20220510132444015

自动创建继承于Service的类

package cn.itcast.testandroid;

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

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {//子类必须实现的方法,可以通过返回的LBinder对象与服务通信
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");//默认抛出的异常,后续可删除
    }
}

自动在清单文件中注册服务

<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>

第二三属性分别表示是否允许被实例化和是否能够被其他应用程序中的组件调用或者进行交互

8.3 服务的生命周期

服务的生命周期与启动服务方式有关,服务的启动方式有两种

  • startService()启动
  • bindService()启动

生命周期的方法

  1. onCreat():第一次创建服务的方法
  2. onStartCommand():startService()方法启动服务
  3. onBind():bindService()方法启动服务
  4. onUnbind():调用unBindService()方法断开服务绑定时执行的方法
  5. onDestory():销毁服务执行的方法
  • startService()方式启动服务包括1,2,5
  • bindService()方式启动服务包括1,3,4,5

8.4 服务的启动方式

8.4.1 调用startService()方法启动服务

这种方法启动的服务会在后台长期运行

实例

目标:采用startService()启动服务,并利用广播在界面上显示操作

效果图:

image-20220510171836797

Mainactivity.java

package cn.itcast.testandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button mbtn_ser;
    private Button mbtn_dis;
    private TextView mtv_dis;
    private MyReceiver myReceiver;
    private boolean status;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mbtn_ser = findViewById(R.id.btn_send);
        mbtn_dis = findViewById(R.id.dis);
        mtv_dis = findViewById(R.id.tv_dis);
        myReceiver = new MyReceiver();//实例化广播接收者
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("创建服务...");
        intentFilter.addAction("执行onStartCommand()方法...");
        intentFilter.addAction("销毁服务");//设置过滤器
        registerReceiver(myReceiver,intentFilter);
        status = true;//默认开灯状态
        mbtn_ser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!status) {
                    mbtn_ser.setText("关灯");
                    mbtn_dis.setBackgroundColor(getResources().getColor(R.color.white));
                    Intent intent = new Intent(MainActivity.this,MyService.class);//关闭服务
                    status = !status;//开关灯状态取反
                    stopService(intent);
                }
                else {
                    mbtn_ser.setText("开灯");
                    mbtn_dis.setBackgroundColor(getResources().getColor(R.color.black));
                    Intent intent = new Intent(MainActivity.this,MyService.class);//开启服务
                    status = !status;
                    startService(intent);
                }
            }
        });
    }
    class MyReceiver extends BroadcastReceiver {//内嵌内实现广播接收响应

        @Override
        public void onReceive(Context context, Intent intent) {
            mtv_dis.append('\n'+intent.getAction());
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }
}

Myservice.java

package cn.itcast.testandroid;

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

public class MyService extends Service {
    public MyService() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
        Intent intent = new Intent();
        intent.setAction("创建服务...");
        sendBroadcast(intent);
        Toast.makeText(this, "创建服务", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent intent1 = new Intent();
        intent.setAction("执行onStartCommand()方法...");
        sendBroadcast(intent1);
        Toast.makeText(this, "执行onStartCommand()方法...", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Intent intent = new Intent();
        intent.setAction("销毁服务");
        sendBroadcast(intent);
        Toast.makeText(this, "销毁服务", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

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

activity_main.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"
    android:layout_margin="20dp"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="关灯"/>
    <Button
        android:id="@+id/dis"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@color/white"/>
    <TextView
        android:id="@+id/tv_dis"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="hello world"
        android:textSize="20sp"/>

</LinearLayout>

8.4.2 调用bindService()方法启动服务

此种方法启动服务的时候,服务会与组件绑定,程序允许组件与服务交互,组件一旦退出或者调用unbindService()方法解绑服务,服务就会被销毁,多个组件可以绑定一个服务,绑定的语法如下

bindService(Intent service, ServiceConnection conn, int flags);//绑定服务,用unbindService()解绑
  • service:指定要启动的服务
  • conn:用于监听调用者(服务绑定的组件)与service之间的连接状态,连接成功会调用调用者的onServiceConnected()方法,断开连接的时候会调用调用者的onServiceDisconnnected()方法
  • flags:表四组件绑定服务的时候是否自动创建Service(如果service还未创建),该参数可以设置为0,表示不自动创建Service

8.5 服务的通信

通过bindService()方法开启服务后,服务与绑定服务的组件之间是可以进行通讯的

8.5.1 本地服务通信与远程服务通信

本地服务通信

本地服务通信表示应用程序内部的通信,服务在进行通信的时候使用的是IBinder对象,在ServiceConnection类中得到IBinder对象,通过该对象可以获得服务中自定义的方法,执行具体的操作

远程服务通信

远程服务通信用在应用程序之间的通信,远程服务通信通过AIDL实现,是一种接口语言【具体…】

8.6 实战演练-音乐播放器

目标:通过服务播放音乐,绑定组件实现与组件之间的通信,控制服务

演示图:

image-20220511223012351

MainActivity.java

package cn.itcast.music;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.TintTypedArray;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private static SeekBar bar;
    private static TextView tv_progress, tv_total;
    private ObjectAnimator animator;
    private MusicService.MusicControl musicControl;
    MyServiceConn conn;
    Intent intent;
    private boolean isunbind = false;//记录服务是否解绑

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    void init() {
        tv_progress = findViewById(R.id.time_start);
        tv_total = findViewById(R.id.time_sum);
        bar = findViewById(R.id.music_bar);
        findViewById(R.id.btn_continue).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);
        findViewById(R.id.btn_pause).setOnClickListener(this);
        findViewById(R.id.btn_play).setOnClickListener(this);
        intent = new Intent(this, MusicService.class);
        conn = new MyServiceConn();//实现连接服务,实现监听者,当连接状态发生变化的时候起作用
        bindService(intent, conn, BIND_AUTO_CREATE);//绑定服务
        bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {//滑动条添加事件监听
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {//滑动条进度改变时会调用此方法
                if (i == seekBar.getMax()) {//当滑动到尾端的时候暂停播放动画
                    animator.pause();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {//滑动条开始滑动的时候调用

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {//滑动条停止滑动的时候调用
                int progress = seekBar.getProgress();//获取进度
                musicControl.seekTo(progress);//设置播放进度
            }
        });
        ImageView iv_music = findViewById(R.id.music_img);
        animator = ObjectAnimator.ofFloat(iv_music,"rotation",0f,360.0f);//设置旋转动画
        animator.setDuration(1000);//旋转一周一秒
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);//-1表示动画无限循环
    }

    @Override
    public void onClick(View view) {//按钮监听事件
        switch (view.getId()) {
            case R.id.btn_play:
                musicControl.play();//控制音乐
                animator.start();//动画开始
                break;
            case R.id.btn_pause:
                musicControl.pausePlay();
                animator.pause();
                break;
            case R.id.btn_continue:
                musicControl.continuePlay();
                animator.start();
                break;
            case R.id.btn_exit:
                unbind(isunbind);
                isunbind = true;
                finish();
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    public static Handler handler = new Handler() {//创建消息处理对象,从主线程中处理子线程中发来的消息
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle = msg.getData();//获取音乐播放进度
            int duration = bundle.getInt("duration");//总时长
            int currentPositon = bundle.getInt("currentPosition");//当前播放进度
            bar.setMax(duration);//设置进度条最大值
            bar.setProgress(currentPositon);//设置进度条当前值
            //获取歌曲的总时长
            int minute = duration / 1000 /60;
            int second = duration / 1000 % 60;
            String strMinute = null;
            String strSecond = null;
            if(minute < 10) {//若为单位数,前面添加0
                strMinute = "0" + minute;
            } else {
                strMinute = minute + "";
            }
            if(second < 10) {
                strSecond = "0" + second;
            } else {
                strSecond = second + "";
            }
            tv_total.setText(strMinute + ":" + strSecond);
            //获取歌曲当前时长
            minute = currentPositon / 1000 / 60;
            second = currentPositon / 1000 % 60;
            if(minute < 10) {
                strMinute = "0" + minute;
            } else {
                strMinute = minute + "";
            }
            if(second < 10) {
                strSecond = "0" + second;
            } else {
                strSecond = second + "";
            }
            tv_progress.setText(strMinute + ":" + strSecond);
        }
    };
    class MyServiceConn implements ServiceConnection {//实现连接服务

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {//绑定服务调用
            musicControl = (MusicService.MusicControl) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }
    private void unbind(boolean isunbind) {//解绑调用
        if(!isunbind) {
            musicControl.pausePlay();
            unbindService(conn);
            stopService(intent);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbind(isunbind);
    }
}

MusicService.java

package cn.itcast.music;

import android.app.Service;
import android.content.Intent;
import android.media.MediaParser;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {
    private MediaPlayer player;
    private Timer timer;

    public MusicService() { }

    @Override
    public IBinder onBind(Intent intent) {
        return new MusicControl();//返回音乐控制服务
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();//创建音乐播放器对象
    }
    public void addTimer() {//计时器用于动态设置进度条
        if(timer == null) {
            timer = new Timer();//创建计时器
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    if(player == null) return;
                    int duration = player.getDuration();//获取歌曲总时长
                    int currentPostion = player.getCurrentPosition();//获取播放进度
                    Message msg = MainActivity.handler.obtainMessage();//创建消息对象
                    Bundle bundle = new Bundle();//存入数据,发回MainActivity
                    bundle.putInt("duration",duration);
                    bundle.putInt("currentPosition",currentPostion);
                    msg.setData(bundle);
                    MainActivity.handler.sendMessage(msg);
                }
            };
            timer.schedule(timerTask,5,500);//5毫秒后执行任务,每500ms执行一次
        }
    }
    class MusicControl extends Binder {
        public void play() {
            try {
                player.reset();//重置播放器
                player = MediaPlayer.create(getApplicationContext(),R.raw.test);//获取音乐源
                player.start();//开始播放
                addTimer();//设置定时器
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        public void pausePlay() {
            player.pause();
        }
        public void continuePlay() {
            player.start();
        }
        public void seekTo(int progress) {
            player.seekTo(progress);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(player == null) return;
        if(player.isPlaying()) player.stop();
        player.release();
        player = null;
    }
}

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"
    android:orientation="vertical"
    android:background="@color/white"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/li_music"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="15dp">
        <ImageView
            android:src="@drawable/img"
            android:id="@+id/music_img"
            android:layout_width="100dp"
            android:layout_height="100dp"/>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">
            <TextView
                android:layout_marginLeft="10dp"
                android:textSize="20sp"
                android:textColor="#008c8c"
                android:id="@+id/music_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="音乐名"/>
            <RelativeLayout
                android:layout_margin="15dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/time_start"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="00:00"/>
                <TextView
                    android:id="@+id/time_sum"
                    android:layout_alignParentRight="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="00:00"/>
            </RelativeLayout>
            <SeekBar
                android:id="@+id/music_bar"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"/>
        </LinearLayout>


    </LinearLayout>

    <LinearLayout
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@id/li_music">
        <Button
            android:id="@+id/btn_play"
            android:text="播放"
            style="@style/Mybuttonstyle"/>
        <Button
            android:text="暂停"
            android:id="@+id/btn_pause"
            style="@style/Mybuttonstyle"/>
        <Button
            android:text="继续"
            android:id="@+id/btn_continue"
            style="@style/Mybuttonstyle"/>
        <Button
            android:text="退出"
            android:id="@+id/btn_exit"
            style="@style/Mybuttonstyle"/>

    </LinearLayout>

</RelativeLayout>

@style/Mybuttonstyle

<style name="Mybuttonstyle">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_weight">1</item>
    <item name="android:layout_margin">5dp</item>
    <item name="android:background">@drawable/mybtn</item>
</style>

@drawable/mybtn

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <corners android:radius="150dp"/>
            <solid android:color="#008c8c"/>
        </shape>
    </item>
    <item android:state_pressed="false">
        <shape android:shape="rectangle">
            <corners android:radius="150dp"/>
            <solid android:color="#A0DFDF"/>
        </shape>
    </item>
</selector>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值