Android学习之Service(服务)的使用

  Service是Android系统中的四大组件之一,它与Activity不同,它是不能与用户交互的。它是一种长生命周期的,没有可视化界面,运行于后台的一种服务程序。

  1. 两种启动方式:
  1.1 Started(启动):
  应用程序组件通过startService()方法启动服务,一旦启动,服务能在后台无限期运行,即使启动的服务已销毁。
  启动时,startService –> onCreate() –> onStart();
  停止时,stopService –> onDestroy()。
  1.2 Bound(绑定):
  应用程序组件通过bindService()方法绑定到服务,绑定服务提供客户端-服务器接口,运行组件与之交互,仅当绑定时服务运行,一个服务可以绑定多个组件,当所有组件都解绑时,服务被销毁。
  绑定时,bindService -> onCreate() –> onBind();
  解绑定,unbindService –>onUnbind() –> onDestory()。

  2. 生命周期:
  Service生命周期一般有两种运行模式,这两种模式并不是完全分离的:
  (1)在程序没有停止Service或者Service自己停止的情况下,Service将一直在后台运行。该模式下,Service是通过startService()方法开始,以stopService()方法停止。
  (2)可以通过接口被外部程序调用。外部程序建立一个到Service的连接,通过这个连接来操作Service。建立连接开始于bindService(),结束于unbindService()。多个客户端可以绑定到同一个Service,如果Service没有启动,可以通过bindService()启动它。
在这里插入图片描述

  3. service中的重要方法:
  创建服务,需要创建Service类(或子类)来实现。
  Android提供了两个可以提供Started服务的类:

    1.Service//所有服务的基类
    //当继承该类时,创建新线程来执行服务的全部工作,避免服务使用默认的主线程
    2.IntentService //一个Service的子类
    //每次使用一个工作线程来处理全部启动请求,是不需要处理多个请求时的最佳选择
    //进需要实现onHandleIntent()方法即可创建服务,该方法接收每次请求的Intent以完成后台任务

  在实现类中,可根据需要重写一些回调方法:

    onStartCommand()//其他组件使用startService()请求服务时调用
    //使用该方法后,服务启动并在后台无限期运行,必要时,使用stopself()或stopService()方法停止服务
    onBind()//其他组件使用bindService()请求服务时调用
    //必须通过返回Ibinder来提供通信接口,是服务必须要实现的方法,保证服务能够被绑定
    onCreate()//当服务第一次创建时,调用该方法执行创建过程
    onDestroy()//当服务被销毁时,调用该方法

  started服务的终止方式:服务自身通过stopSelf()来停止,其他应用通过stopService()来停止。
  service的声明:
  需要在应用程序配置文件中声明Service才能使用,声明方法:在标签中,添加子标签。

<service
    android:name=".MyService">
    <intent-filter>
        <action android:name="com.example.androidservice.MyService"/>
    </intent-filter>
</service>

  ☆☆☆Android Studio实现Service的创建和使用
  创建一个start类的服务,在服务中启动音乐播放功能,播放程序的背景音乐,同时实现绑定类服务,通过一个Activity以绑定的方式启动该服务,验证两种服务方式是否会随着Activity的终止而终止。

  1.打开Android Studio,新建工程后,在res中添加Android resource directory,名称为raw,放进一首音乐,在activity_main.xml中,在activity_main.xml中添加三个按钮。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidservice.MainActivity">
    
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/darker_gray"
        android:backgroundTint="@android:color/holo_green_dark">
        
        <Button
            android:text="播放"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            android:background="@android:color/holo_orange_dark"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="20sp" />
            
        <Button
            android:text="停止"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button2"
            android:background="@android:color/holo_purple"
            android:textSize="20sp"
            android:textColor="@android:color/holo_red_dark" />
            
        <Button
            android:text="BindService_start"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAllCaps="false"
            android:id="@+id/button3"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="20sp" />
            
    </LinearLayout>
    
</RelativeLayout>

  2.增加一个服务类,名称为MyService.java,编写代码。

package com.example.androidservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.format.Time;

public class MyService extends Service{
    MediaPlayer mediaPlayer;
    public class LBinder extends Binder{
        MyService getService(){
            return MyService.this;
        }
    }
    
    private final IBinder ibinder=new LBinder();//定义IBinder对象
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return ibinder;//绑定服务时,返回IBinder对象
    }
    public String getCrurentTime(){
        Time t=new Time();
        t.setToNow();
        String ct= t.format("%Y-%m-%d %H:%M:%S");
        return ct;
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer=MediaPlayer.create(this,R.raw.kalimba);
        mediaPlayer.start();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
    }
    
}

  3.在MainActivity.java中,编写代码。

package com.example.androidservice;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    MyService mSvc;//定义服务实例对象
    boolean bound;
    private ServiceConnection sc=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //通过IBinder获取服务实例
            MyService.LBinder mBinder=(MyService.LBinder)service;
            mSvc=mBinder.getService();
            bound=true;
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            bound=false;
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bt1= (Button) findViewById(R.id.button);
        Button bt2= (Button) findViewById(R.id.button2);
        Button bt3= (Button) findViewById(R.id.button3);
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(MainActivity.this,MyService.class));
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(new Intent(MainActivity.this,MyService.class));
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //启动绑定服务
                bindService(new Intent(MainActivity.this,MyService.class),
                        sc, Service.BIND_AUTO_CREATE);
                if (bound){
                    String nowT;
                    nowT=mSvc.getCrurentTime();
                    Toast.makeText(MainActivity.this,nowT, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

  4.在manifests配置文件中,声明Service。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidservice">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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=".MyService">
        </service>
    </application>
</manifest>

  运行结果:
  在这里插入图片描述
  这就是Service(服务)的使用,如果转载以及CV操作,请务必注明出处,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值