Android入门之bindService的用法详解

目录
  • 介绍
  • 来看例子
  • 全代码
    • Service注册
    • Service类(坑来了)
    • 主运行类-MainActivity.java
  • 运行效果

介绍

在前一天我们介绍了Android中有两种启动Service的方法。并擅述了startService和bindService的区别。同时我们着重讲了startService。

因此今天我们就来讲bindService。bindService大家可以认为它是和Android的一个共生体。即这个service所属的activity如果消亡那么bindService也会消亡。

因此今天我们以一个比较复杂的例子,activity<->service间互相传值来讲透这个bindService的使用,同时我们在这个例子中故意留下一个坑即:在Service里使用Thread处理大事务是不是就一定安全呢?也不安全,它也会引起ANR即:Application Not Responding-安卓崩溃。从而以这个坑来引出IntentService的使用。

来看例子

我们设有三个按钮:

  • 【BIND SERVICE】-点击后运行Service
  • 【STOP BINDING】-点击后结束Service
  • 【GET VALUE FROM BINDER】-通过Activity获取正在BINDING的Service内的值,此处我们留下了一个ANR的坑,即获取Service内的值时我们留了一个Thread.Sleep(30000)的长事务,来观察ANR;

此处记得按钮的点击顺序为:先点【BIND SERVICE】->再点【GET VALUE FROM BINDER】->再点【STOP BINDING】不过此处你没有机会点这个【STOP BINDING】按钮,因为在GET时你已经ANR(崩溃)了。

来看全代码展示。

全代码

Service注册

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.DemoBindService"
        tools:targetApi="31">
        <service
            android:name=".SampleBindService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action
                    android:name="org.mk.android.demo.SampleBindService"/>
            </intent-filter>

        </service>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

Service类(坑来了)

package org.mk.android.demo;

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

public class SampleBindService extends Service {
    private final String TAG = "SimpleBindService";
    private int count;
    private boolean quit;
    private CountNumBinder countNumBinder = new CountNumBinder();

    public SampleBindService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.i(TAG, ">>>>>>onBind方法被调用");
        return countNumBinder;
    }

    //Service被关闭前回调
    @Override
    public void onDestroy() {
        super.onDestroy();
        this.quit = true;
        Log.i(TAG, ">>>>>>onDestroyed方法被调用!");
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, ">>>>>>onRebind方法被调用!");
        super.onRebind(intent);
    }

    //Service被创建时调用
    @Override
    public void onCreate() {
        Log.i(TAG, ">>>>>>onCreate方法被调用");
        super.onCreate();
        //创建一个线程动态地修改count的值
        new Thread() {
            public void run() {
                while (!quit) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }

            ;
        }.start();
    }

    //Service断开连接时回调
    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, ">>>>>>onUnbind方法被调用!");
        return true;
    }

    //Service被启动时调用
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, ">>>>>>onStartCommand方法被调用");
        return super.onStartCommand(intent, flags, startId);
    }

    public class CountNumBinder extends Binder {
        public int getCount() {
            Log.i(TAG, ">>>>>>into long waiting");

            try {
                Thread.sleep(300000);
            } catch (Exception e) {
            }

            return -1;
        }
    }
}

我们可以看到,这个Service以每秒对着count+1.

然后通过bindService的onBind生命体里以一个CountNumBinder暴露出去,给到外部可以通过一个getCount方法来调用获取Service里当前count的值,但是这个值在获取前我们会使用Thread.sleep(30000)-30秒来模拟ANR。

主运行类-MainActivity.java

在调用Service的activity里我们使用bindService(intent, conn, Service.BIND_AUTO_CREATE);来启动。

这边这个conn是一个ServiceConnection类,new出一个ServiceConnection类并覆盖里面的

  • onServiceConnected方法,用于接受bindService返回的对象;
  • onServiceDisconnected方法,用于在这个bindService被销毁时作处理;

具体代码如下:

package org.mk.android.demo;

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;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "SimpleBindService";
    private Button buttonBindService;
    private Button buttonStopBinding;
    private Button buttonGetValueFromBinder;
    private Context ctx;
    private Intent intent;
    private SampleBindService.CountNumBinder countNumBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonBindService = (Button) findViewById(R.id.buttonBindService);
        buttonStopBinding = (Button) findViewById(R.id.buttonStopBinding);
        buttonGetValueFromBinder = (Button) findViewById(R.id.buttonGetValueFromBinder);
        ctx = MainActivity.this;
        intent = new Intent(ctx, SampleBindService.class);
        buttonBindService.setOnClickListener(new OnClickListener());
        buttonStopBinding.setOnClickListener(new OnClickListener());
        buttonGetValueFromBinder.setOnClickListener(new OnClickListener());
    }

    private ServiceConnection conn = new ServiceConnection() {

        //Activity与Service断开连接时回调该方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, ">>>>>>Service DisConnected");
        }

        //Activity与Service连接成功时回调该方法
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, ">>>>>>Service Connected");
            countNumBinder = (SampleBindService.CountNumBinder) service;
        }
    };

    class OnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            Intent eIntent;
            switch (view.getId()) {
                case R.id.buttonBindService:
                    bindService(intent, conn, Service.BIND_AUTO_CREATE);
                    break;
                case R.id.buttonStopBinding:
                    unbindService(conn);
                    break;
                case R.id.buttonGetValueFromBinder:
                    Toast.makeText(getApplicationContext(), "Service的count" + "的值为:" + countNumBinder.getCount(), Toast.LENGTH_LONG).show();
                    break;
            }
        }
    }
}

运行效果

  • 先点【BIND SERVICE】;
  • 再点【GET VALUE FROM BINDER】;

看,ANR出现了。

这就是我说的坑,怎么解决这个坑,请听下回分解。

到此这篇关于Android入门之bindService的用法详解的文章就介绍到这了,更多相关Android bindService内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Android bindservice失败解决方法

    Android bindservice失败解决方法 现象: this.bindService(bindIntent, conn, Context.BIND_AUTO_CREATE); 相同的代码以前使用一直很正常,但最近在项目中使用却一直绑定失败,bindservice返回false. 原因: 使用了TabActivity, TabActivity里的子Activity调用this.bindservice,导致失败.该问题属于Google Android的缺陷,由于TabActivity已经被弃

  • Android BindService使用案例讲解

    最近学习了一下Android里面的Service的应用,在BindService部分小卡了一下,主要是开始没有彻底理解为什么要这么实现. BindService和Started Service都是Service,有什么地方不一样呢: 1. Started Service中使用StartService()方法来进行方法的调用,调用者和服务之间没有联系,即使调用者退出了,服务依然在进行[onCreate()-  >onStartCommand()->startService()->onDes

  • Android中bindService基本使用方法概述

    Android中有两种主要方式使用Service,通过调用Context的startService方法或调用Context的bindService方法,本文只探讨纯bindService的使用,不涉及任何startService方法调用的情况.如果想了解startService相关的使用,请参见<Android中startService基本使用方法概述>. bindService启动服务的特点 相比于用startService启动的Service,bindService启动的服务具有如下特点:

  • Android 启动 Service(startservice和bindservice) 两种方式的区别

    Android Service 生命周期可以促使移动设备的创新,让用户体验到最优越的移动服务,只有broadcast receivers执行此方法的时候才是激活的,当 onReceive()返回的时候,它就是非激活状态. 如果没有程序停止它或者它自己停止,service将一直运行.在这种模式下,service开始于调用Context.startService() ,停止于Context.stopService(). service可以通过调用Android Service 生命周期() 或 Se

  • Android bindService的使用与Service生命周期案例详解

    Android中有两种主要方式使用Service,通过调用Context的startService方法或调用Context的bindService方法,本文只探讨纯bindService的使用,不涉及任何startService方法调用的情况.如果想了解startService相关的使用,请参见<Android中startService的使用及Service生命周期>. bindService启动服务的特点 相比于用startService启动的Service,bindService启动的服务

  • android之SeekBar控件用法详解

    MainActivity.java package com.example.mars_2400_seekbar; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.app.Activity; import android.os.Bundle; import a

  • android之RatingBar控件用法详解

    MainActivity.java package com.example.mars_2500_ratingbar; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.app.Activity; import android.os.Bundle; import

  • Android AlertDialog的几种用法详解

    AlertDialog的几种用法 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="

  • Python入门基本操作列表排序用法详解

    目录 列表的举例 1.访问python列表中的元素 2.python列表的切片 3.python列表的排序 4.Python列表元素的添加 5.Python列表元素的删除 列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现.列表的数据项可以是不同的类型,可以是字符串,可以是数字类型,甚至是列表,元组,只要用","逗号分隔开,就是一个元素. 列表的举例 1.访问python列表中的元素 通过索引直接访问元素,访问单个元素的基本格式为: 列表名[索引值]:访问多个元

  • Android开发之Notification通知用法详解

    本文实例讲述了Android开发之Notification通知用法.分享给大家供大家参考,具体如下: 根据activity的生命周期,在activity不显示时,会执行onStop函数(比如按下home键),所以你在onStop函数(按退出键除外)里面把notification放在通知栏里,再此显示时,把notification从通知栏里去掉.或者,只要程序在运行就一直显示通知栏图标. 下面对Notification类中的一些常量,字段,方法简单介绍一下: 常量: DEFAULT_ALL 使用所

  • Android编程开发之NotiFication用法详解

    本文实例讲述了Android编程开发之NotiFication用法.分享给大家供大家参考,具体如下: notification就是通知的意思,安卓中指通知栏,一般用在电话,短信,邮件,闹钟铃声,在手机的状态栏上就会出现一个小图标,提示用户处理这个快讯,这时手从上方滑动状态栏就可以展开并处理这个快讯. 在帮助文档中,是这么说的, notification类表示一个持久的通知,将提交给用户使用NotificationManager.已添加的Notification.Builder,使其更容易构建通知

  • Android中的Selector的用法详解及实例

    Android中的Selector的用法 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_pressed="true" android:drawable="@drawable/b

  • Android编程中HTTP服务用法详解

    本文实例讲述了Android编程中HTTP服务用法.分享给大家供大家参考,具体如下: 在Android中,除了使用java.net包下的API访问HTTP服务之外,我们还可以换一种途径去完成工作.Android SDK附带了Apache的HttpClient API.Apache HttpClient是一个完善的HTTP客户端,它提供了对HTTP协议的全面支持,可以使用HTTP GET和POST进行访问.下面我们就结合实例,介绍一下HttpClient的使用方法. 我们新建一个http项目,项目

  • Android 中 WebView 的基本用法详解

    加载 URL (网络或者本地 assets 文件夹下的 html 文件) 加载 html 代码 Native 和 JavaScript 相互调用 加载网络 URL webview.loadUrl(https://www.baidu.com/); 加载 assets 下的 html 文件 webview.loadUrl(file:///android_asset/test.html); 加载 html 代码 // 两个代码差不多 // 偶尔出现乱码 webview.loadData(); // 比

  • Android开发之AlarmManager的用法详解

    Android中的AlarmManager实质上是一个全局的定时器,是Android中常用的一种系统级别的提示服务,在指定时间或周期性启动其它组件(包括Activity,Service,BroadcastReceiver). 一.概述: 该类提供一种访问系统闹钟服务的方式,允许你去设置在将来的某个时间点去执行你的应用程序.当你的闹钟响起(时间到)时,在它上面注册的一个意图(Intent)将会被系统以广播发出,然后自动启动目标程序,如果它没有正在运行.注册的闹钟会被保留即使设备处于休眠中(如果闹钟

随机推荐