4

Android入门第41天-Android中的Service(bindService)

 1 year ago
source link: https://blog.csdn.net/lifetragedy/article/details/128175329
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Android入门第41天-Android中的Service(bindService)

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

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

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

e19faa78420f43b3aa7b052788d5d1ee.png

我们设有三个按钮:

  • 【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注册



newCodeMoreWhite.png

 Service类(坑来了)



newCodeMoreWhite.png

我们可以看到,这个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被销毁时作处理;

具体代码如下:



newCodeMoreWhite.png
  1. 先点【BIND SERVICE】;
  2. 再点【GET VALUE FROM BINDER】;
bd8760f1b0bd45dd82dd25d341ce7c79.png

看,ANR出现了。

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK