2015年7月22日星期三

Android服务之IntentService

服务中的代码默认运行在主线程当中,如果直接在服务里去处理一些耗时的逻辑,很容易出现ANR--即万恶的Application Not Responding。故此时需要用到Android多线程编程的技术,我们应该在服务的每个具体的方法开启一下子线程,然后再这里去处理那些耗时的逻辑,示例如下:

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
            return null;
    }
    @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
             new Thread(new Runnable() {
                    @Override
                     public void run() {
                     // 处理具体的逻辑
                     }
              }).start();
              return super.onStartCommand(intent, flags, startId);
           }
 }

这种服务一旦启动,就会一直处于运行状态,必须调用stopService()或者stopService()方法才能使其停止,我们可以在run()中“//处理具体的逻辑”后调用 stopSelf()方法来实现服务执行完毕后的自动停止功能。

问题又来了,这样比较繁琐不好记,要么忘记开启线程,要么忘记调用stopService()方法,我们会经常性地忽视之。


为了可以简单地创建一个异步的、会自动停止的服务,IntentService闪亮登场啦。

一、新建MyIntentService类继承自IntentService,如下,

public class MyIntentService extends IntentService {

public MyIntentService() {
super("MyIntentService"); // 调用父类的有参构造函数
// TODO Auto-generated constructor stub
}

@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
// 打印当前线程的id
Log.d("MyIntentService", "Thread id is "
+ Thread.currentThread().getId());
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService", "onDestroy executed");
}


}

可以看到,MyIntentService类分三个部分:

  1. 是一个无参数的构造函数,须在构造函数内部调用父类的有参构造函数。
  2. 实现onHandleIntent()抽象方法,其中处理具体逻辑,且不用担心ANR问题(因为这个方法已经是在子线程中运行的)。为证实,我们Log打印当前线程的id
  3. 重写了onDestroy()方法,其在服务运行结束时运行。 
二、新建Button响应启动MyIntentService服务,并且打印主线程的id,关键代码如下,


@Override
public void onClick(View v) {
switch (v.getId()) {
                .........
case R.id.start_intent_service:
// 打印主线程的id
Log.d("MainActivity", "Thread is " + Thread.currentThread().getId());
Intent intentService = new Intent(this, MyIntentService.class);
startService(intentService);
default:
break;
}


三、很重要一点,切莫忘记在AndroidManifest对我们的MyIntentService服务注册

四、运行。

   点击StartIntentService按钮,LogCat输出如下,
 

 可以看到,MyIntentService和MainActivity所在的线程id是不一样的;onDestroy()方法得到执行,说明MyIntentService服务运行技术后自动停止销毁啦。

这就是,集开启线程和自动停止于一身的,金光闪亮的IntentService。

LOL

2015年7月18日星期六

Service启动流程及生命周期

service启动流程
======== case 1. bind a service ============
TestAidl-Client: ------ =====> bindService()------
TestAidl-Client: ------ <===== bindService()------
TestAidl-Service: ------ service onCreate()------
TestAidl-Service: ------ service onBind()------ :onBind() is only called once, even we call bindService() multiple times, onBind() wont't be invoked.
TestAidl-Client: ------ onServiceConnected()------

======== case 2. unbind a service ============
TestAidl-Client: ------ =====> unbindService()------:if unbindService() is called with an un-bound service, exception will occur : java.lang.IllegalArgumentException: Service not registered
TestAidl-Client: ------ <===== unbindService()------:NOTE: onServiceDisconnected() won't be called due to unbindService(), 只有当servie异常退出时,系统才会调用onServiceDisconnected()
TestAidl-Service: ------ service onUnbind()------:onUnbind() is only called once when the last bound component unbind from the service, usually the service onDestroy() will be called afterwards..
【TestAidl-Service: ------ service onDestroy()------】

======== case 3. start a service ============ 
TestAidl-Client: ------ =====> startService()------
TestAidl-Client: ------ <===== startService()------
TestAidl-Service: ------ service onCreate()------
TestAidl-Client: ------ service onStartCommand()------:You should never call onStartCommand() directly.

======== case 4. stop a service ============ 
TestAidl-Client: ------ =====> stopService()------:stopService() can be called multiple times, nothing happened.
TestAidl-Client: ------ <===== stopService()------
【TestAidl-Service: ------ service onDestroy()------】
所以,在Service,只有onStart( )可被多次调用(通过多次startService调用),其他onCreate( ),onBind( ),onUnbind( ),onDestory( )在一个生命周期中只能被调用一次。

service的生命周期
1. A Started service will be destroyed once stopService() is called, no matter which component calls.
2. A bound service will be destroyed only when the last bound component calls the unbindService().
3. if a service is both started and bound, it will be destroyed when stopService() is called and no one is bound to the service at that time,除此之外,不管是调用unbindService()或者stopService()都是不起作用的。

2015年7月9日星期四

使用容器读取系统联系人

容器,即内容提供器(Content Provider)主要用于在不同的应用程序之间实现数据共享的功能,其提供了一套完整的机制,允许一个程序访问另一个程序中的数据,同时还能保证被访问数据的安全性。

使用内容提供器是Android实现跨程序共享数据的标准方式,不同于文件存储和SharePreferences存储中的两种全局可读写操作模式,内容提供其可以选择只对哪一部分数据进行共享,从而保证了关键,隐私数据的安全。

下面使用现有的内容提供器来读取相应程序中的数据,使用容器来读取系统联系人。

1. 布局文件,使用ListView来显示读取出来的联系人信息

    <ListView 
        android:id="@+id/contacts_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></ListView>

2.MainActivity部分代码

public class MainActivity extends Activity {

ListView contactsView;

ArrayAdapter<String> adapter;

List<String> contactsList = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsView = (ListView) findViewById(R.id.contacts_view);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactsList);
contactsView.setAdapter(adapter);
readContacts();
}

private void readContacts() {
Cursor cursor = null;
try {
// 查询联系人数据
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, // 封装好的CONTENET_URI常量
null, null, null);
while (cursor.moveToNext()) {
// 获取联系人姓名
String displayName = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
// 获取联系人手机号
String number = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(displayName + "\n" + number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close(); // 最后将cursor对象关闭掉
}
}
}

....
}


LOL

2015年6月22日星期一

malloc用法

http://blog.csdn.net/lchunli/article/details/4786663

malloc用法
需要包含头文件:
#include 'stdlib.h'
函数声明(函数原型):
void *malloc(int size);
说明:malloc 向系统申请分配指定size个字节的内存空间。返回类型是 void* 类型。void* 表示未确定类型的指针。C,C++规定,void* 类型可以强制转换为任何其它类型的指针。
从函数声明上可以看出。malloc 和 new 至少有两个不同: new 返回指定类型的指针,并且可以自动计算所需要大小。比如:
int *p;
p = new int;  /返回类型为int* 类型(整数型指针),分配大小为 sizeof(int);
或: 
int* parr;
parr = new int [100];   //返回类型为 int* 类型(整数型指针),分配大小为 sizeof(int) * 100; 
而 malloc 则必须由我们计算要字节数,并且在返回后强行转换为实际类型的指针。 
int* p; 
p = (int *) malloc (sizeof(int)); 
使用事项:
第一、malloc 函数返回的是 void * 类型,如果你写成:p = malloc (sizeof(int)); 则程序无法通过编译,报错:“不能将 void*赋值给 int * 类型变量”。所以必须通过 (int *) 来将强制转换。
第二、函数的实参为 sizeof(int) ,用于指明一个整型数据需要的大小。如果你写成: 
int* p = (int *) malloc (1);
代码也能通过编译,但事实上只分配了1个字节大小的内存空间,当你往里头存入一个整数,就会有3个字节无家可归,而直接“住进邻居家”!造成的结果是后面的内存中原有数据内容全部被清空。
申请出一段连续的内存
malloc 也可以达到 new [] 的效果,申请出一段连续的内存,方法无非是指定你所需要内存大小。比如想分配100个int类型的空间:
int* p = (int *) malloc ( sizeof(int) * 100 ); //分配可以放得下100个整数的内存空间。

另外有一点不能直接看出的区别是,malloc 只管分配内存,并不能对所得的内存进行初始化,所以得到的一片新内存中,其值将是随机的。
除了分配及最后释放的方法不一样以外,通过malloc或new得到指针,在其它操作上保持一致。
free用法
需要包含头文件(和 malloc 一样):
#include 'stdlib.h'
函数声明:
void free(void *block);
即: void free(指针变量);

之所以把形参中的指针声明为 void* ,是因为free必须可以释放任意类型的指针,而任意类型的指针都可以转换为void *。

举例:

int* p = (int *) malloc(4); 

*p = 100;

free(p); //释放 p 所指的内存空间

或者:

int* p = (int *) malloc ( sizeof(int) * 100 ); //分配可以放得下100个整数的内存空间。

……

free(p);

free 不管你的指针指向多大的空间,均可以正确地进行释放,这一点释放比 delete/delete [] 要方便。不过,必须注意,如果你在分配指针时,用的是new或new[],那么抱歉,当你在释放内存时,你并不能图方便而使用free来释放。反过来,你用malloc分配的内存,也不能用delete/delete[] 来释放。一句话,new/delete、new[]/delete[]、malloc/free 三对均需配套使用,不可混用!
int* p = new int[100];
free(p);      //ERROR! p 是由new 所得。

函数malloc()和calloc()都可以用来动态分配内存空间,但两者稍有区别。

malloc()
函数有一个参数,即要分配的内存空间的大小
:
void *malloc(size_t size);

calloc()
函数有两个参数,分别为元素的数目和每个元素的大小,这两个参数的乘积就是要分配的内存空间的大小。

void *calloc(size_t numElements,size_t sizeOfElement);
如果调用成功,函数malloc()和函数calloc()都将返回所分配的内存空间的首地址。

函数malloc()和函数calloc()的主要区别是前者不能初始化所分配的内存空间,而后者能。如果由malloc()函数分配的内存空间原来没有被使用过,则其中的每一位可能都是0;反之,如果这部分内存曾经被分配过,则其中可能遗留有各种各样的数据。也就是说,使用malloc()函数的程序开始时(内存空间还没有被重新分配)能正常进行,但经过一段时间(内存空间还已经被重新分配)可能会出现问题。

函数calloc()会将所分配的内存空间中的每一位都初始化为零,也就是说,如果你是为字符类型或整数类型的元素分配内存,那麽这些元素将保证会被初始化为0;如果你是为指针类型的元素分配内存,那麽这些元素通常会被初始化为空指针;如果你为实型数据分配内存,则这些元素会被初始化为浮点型的零。


需要包含头文件:
 #i nclude <mallco.h>或 #i nclude <stdlib.h>