My Android Series[1]

2016-03-25  本文已影响36人  Royno7

开始前的话

啃找到的那两本好书,有些收获。不过这周我时间是在太赶,下周的My Android Series系列再开坑写那些安卓底层、开发技巧的东西。

这篇博文,我打算写写多线程、网络和蓝牙,一直以来自己对网络开发和多线程的掌握一直都不太好,也缺少开发实践;蓝牙则是这次写项目要用到,粗略看了下资料发现蓝牙和socket编程十分相似,所以也放到一块来说。

(好像这样的话一篇博文会特别长,我还是分成三篇来写吧——多线程+Service、网络、蓝牙)

Android中的多线程 及 Service(服务)

这里先说一下多线程和异步消息处理机制,因为Service是

Android 多线程 和 异步消息处理机制

多线程

andorid中的多线程和Java十分类似,语法都基本一样。

  1. 继承Thread
class MyThread extends Thread{
   @Override
   public void run(){
    //具体逻辑
   }
}

然后要用的时候 new一个MyThread实例,调用start()方法就ok

new MyThread().start();
  1. 实现Runnable
class MyThread implements Runnable{
   @Override
   public void run(){
    //具体逻辑
   }
}

启动线程的时候要改一下。使用Thread的构造函数接收一个Runnable参数,这里就是new出的MyThread对象;然后再调用Thread的start方法

MyThread myThread = new MyThread();
new Thread(myThread).start();
  1. anroid 中一些需要注意的东西

这个部分我会在之后的深入研究Android机制中进行更为详细的学习分析,这里做个标记~

异步消息处理

之所以会有异步消息处理机制,就我个人的理解,是由于耗时操作虽然可以新开一个线程来处理,不过如果处理的结果对UI更新这样的操作,就会阻塞主线程。
根据操作系统的知识,异步机制就意味着我们不用阻塞在那些耗时的操作上,只需要发出一个耗时操作的请求就可以做接下来的事情,这样,就不会发生进程的阻塞。等到耗时操作完成之后会用特定的方式来通知我们,已经完成

  1. Android中的异步消息处理主要包括四个部分:
    Message, Handler, MessageQueue, Looper
    之前看的Android面试题目也有很多问道这部分的,足见重要性,继续说。
Android_异步消息处理 .jpg

这张图片摘自郭霖大神的第一行代码第九章
这个部分我的理解还不够深刻,之后有空可以重新填一下这个坑

  1. 总结一下异步消息处理机制的过程。
  1. 当子线程中需要进行UI操作,就创建一个Message对象,并通过Handler将这条消息发送出去。

  2. 之后,指条消息就被添加到MessageQueue的队列中等待被处理,而Looper则会一直尝试从MessageQueue中取出待处理的消息,最后分发回Handler的handlerMessage()方法。

  3. 由于Handler是在主线程中创建的,所以此时handleMessage()方法中的代码也会在主线程中运行,也就可以进行UI操作了。

  4. 使用AsyncTask

这个部分我先跳过,创新杯回来再写

Service

什么是服务

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

15:20 这个部分先写到这里,先去写会儿代码

上一篇 下一篇

猜你喜欢

热点阅读