LoaderManager使用详解(一)---没有Loader之前的世界

第一部分 没有Loader之前的世界

这一部分将对Loaders和LoaderManager做一个简短的介绍。第一节将在Android3.0之前如何载入数据,指出其缺陷。第二节讲述每个类的目的,以及它们异步载入数据的能力。
这篇文章是有关Loaders和LoaderManager一系列文章的开篇,该系列如下:

一:Loaders之前世界
二:了解LoaderManager
三:实现Loaders
四:实例:AppListLoader

如果你对Loaders和LoaderManager完全不了解,在继续阅读之前,强烈建议你读一下Loaders向导。

以前情况
在Android3.0之前,很多应用程序响应性能方面有缺陷。UI切换之间的小故障、activity切换延迟、ANR问题。响应性能方面的故障大多数来源于此事实----大多数开发者在UI线程中执行了查询操作---用这种方式载入数据是最差的选择。

在这篇文章强调及时反馈的同时,Android3.0之前的APIs似乎并没有支持该特性。在Loaders之前,cursors主要通过两个Activity方法(现在已经过时deprecated)来进行管理和查询:

public void startManagingCursor(Cursor)
告诉activity根据自己的生命周期来管理cursor的生命周期。cursor会被自动deactivate()当活动stopped时。会自动close()当活动摧毁的时候。当活动stopped之后重新restarted,cursor会re-queried(requery())重新查询最新的数据。

public Cursor managedQuery(Uri, String, String, String, String)
该函数是对ContentResolver的query()方法的包装。除了执行query之外,在它返回之前还会将调用startManagingCursor(cursor)。也就是说将这个query的cursor放入了activity生命周期管理了。

用起来很方便的同时,上面的方法在UI线程中执行查询操作时,会导致严重的延迟问题。而且该“managed cursors”方式在activity配置变化(configuration changed,横竖屏切换、键盘弹出等)时,并不会保持数据。在这些情况下会重新requry()数据,但是实际上是没有必要、低效,而且会导致方向切换呆滞和卡顿。

Managed Cursors的问题
让我们在一个简单的代码里面模拟managed cursors的问题。下面提供的代码是在一个ListActivity里面载入数据使用的是Android3.0之前的APIs。该活动从ContentProvider里面查询数据,并且管理返回的cursor。查询结果用SimpleCursorAdapter包装,并且显示在listview中。代码精炼如下:
public class SampleListActivity extends ListActivity {  
  
  private static final String[] PROJECTION = new String[] {"_id", "text_column"};  
  
  @Override  
  protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
  
    // Performs a "managed query" to the ContentProvider. The Activity   
    // will handle closing and requerying the cursor.  
    //  
    // WARNING!! This query (and any subsequent re-queries) will be  
    // performed on the UI Thread!!  
    Cursor cursor = managedQuery(  
        CONTENT_URI,  // The Uri constant in your ContentProvider class  
        PROJECTION,   // The columns to return for each data row  
        null,         // No where clause  
        null,         // No where clause  
        null);        // No sort order  
  
    String[] dataColumns = { "text_column" };  
    int[] viewIDs = { R.id.text_view };  
   
    // Create the backing adapter for the ListView.  
    //  
    // WARNING!! While not readily obvious, using this constructor will   
    // tell the CursorAdapter to register a ContentObserver that will  
    // monitor the underlying data source. As part of the monitoring  
    // process, the ContentObserver will call requery() on the cursor   
    // each time the data is updated. Since Cursor#requery() is performed   
    // on the UI thread, this constructor should be avoided at all costs!  
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(  
        this,                // The Activity context  
        R.layout.list_item,  // Points to the XML for a list item  
        cursor,              // Cursor that contains the data to display  
        dataColumns,         // Bind the data in column "text_column"...  
        viewIDs);            // ...to the TextView with id "R.id.text_view"  
  
    // Sets the ListView's adapter to be the cursor adapter that was   
    // just created.  
    setListAdapter(adapter);  
  }  
}

上面的代码有3个问题。如果你读懂了上面讲的内容,那么开始两个问题不难读懂。

1. managedQuery在Ui线程中执行了一个查询操作,这将导致应用无响应,这种方法不应该再使用。
2. 通过查看Activity.java源码,可以知道managedQuery也顺便调用了startManagingCursor来管理查询到的数据。看起来很简便,因为我们不用考虑cursor后续的关闭、requery等。但是使用这种方式导致每次activity的状态从stopped返回时都需要重新查询数据,这通常会导致UI线程卡顿。让activity替我们管理cursor所冒的风险大于便捷性。
3. 32行的SimpleCursorAdapter构造方法过时了,不应该再使用。该构造方法问题是,当有改变时,将导致SimpleCursorAdapter自动查询。更具体来说,CursorAdapter会在数据上注册一个ContentObserver监听器,当监听的数据变化时会requery数据。我们应该使用标准的构造函数(如果你尝试使用CursorLoader来载入适配器数据,确保最后一个参数传入值为0)。如果你不能理解第三条,没有关系,这仅仅只是个小错误。

Android平板设备的发布,应该加强UI友好性(反应更快)。更大的设备,7~10寸的平板的应用更复杂、交互更多、有更多的界面布局。后续将介绍Fragment,fragment使应用更动态化,更多的事件驱动。一个简单的,单线程的方法来载入数据显然已经不再合适。所以这就是Loader和LoaderManager在Android3.0诞生的背景。

Android3.0,Loaders, LoaderManager
在Honeycomb之前,很难管理cursors的操作,比如,在UI线程中正常同步,确保所有查询适时在后台线程中执行。Android3.0引入了Loader和LoaderManager类来简化该过程。可以通过使用ASL(Android Support Library),在Android1.6以上的系统实现这两个类。
新的Loader API是一个巨大的进步,是用户体验的巨大进步。Loaders确保所有的cursor操作是异步的,从而排除了UI线程中堵塞的可能性。而且,当通过LoaderManager来管理,Loaders还可以在activity实例中保持当前的cursor数据,也就是不需要重新查询(比如,当因为横竖屏切换需要重新启动activity时)。还有额外的好处,当数据改变时,Loaders可以很聪明的自动检测底层数据的更新和重新检索。

总结
自从有了Honeycomb的Loaders以及其实现库,Android应用变得更好了。现在还使用startManagingCursor和managedQuery是非常不合适的,不仅仅将你的程序变慢,而且存在程序卡死的潜在地可能性。另一方面,Loaders可以通过将数据载入工作交给单独的后台进程,将明显的提高用户体验。

猜你喜欢

转载自iaiai.iteye.com/blog/2276257
今日推荐