狂刷Android范例之5:ApiDemos主程序框架分析

狂刷Android范例之5:ApiDemos主程序框架分析说明

狂刷Android范例系列文章开张了。每篇学习一个Android范例,将一个范例单独生成一个可运行的app,并对重点源代码进行简要分析。然后提供打包好的源代码下载。

功能

这篇文章分析ApiDemos的主程序框架,ApiDemos是Google提供的Android范例,也许是最著名的Android范例,本系列文章都是分析ApiDemos中的各个demo。它的主程序框架也是一篇很好的源代码范例,值得仔细分析。 本文没有代码包,代码包可直接下载Android提供的Apidemos。

来源

本文例子来自于Android-20的com.example.android.apis.ApiDemos。

环境

代码运行环境: 1.ADT2014版本; 2.android:minSdkVersion=”8”;android:targetSdkVersion=”20” 3.workspace中已经生成了appcompatv7,它的版本是android-22;

代码

本文有如下几个知识点,详细的解释在代码注释中: 第一个知识点,在ApiDemos中可以通过点击列表项再次启动下一个层次的ApiDemos Activity; 第二个知识点,使用PackageManager的queryIntentActivities方法可以过滤出过滤出AndroidManifest.xml配置文件中,类似下面描述的Activity

==”android.intent.category.SAMPLE_CODE” /></intent-filter>

第三个知识点,构建一个多层次的data数据。 对所有使用queryIntentActivities方法过滤出来的Activity进行检查,可以启动的demo通过activityIntent方法生成intent,并加入data。含有下一层级的Activity,通过browseIntent方法生成一个可以启动ApiDemos的intent,,并装入data。这样就形成了一个多层次的data文件,对于叶子节点,点击即可启动相应demo程序,例如app/HelloWorld;对于其他节点,点击则再启动一个下一层级的ApiDemos,并将nextLabel作为path参数传入。

第四个知识点,使用java的Comparator类对任意Collection对象进行泛型排序。

具体分析请看例子代码及注释

/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the “License”); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an “AS IS” BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.example.android.apis;import android.app.ListActivity;import android.content.Intent;import android.content.pm.PackageManager;import android.content.pm.ResolveInfo;import android.os.Bundle;import android.view.View;import android.widget.ListView;import android.widget.SimpleAdapter;import java.text.Collator;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;{(Bundle savedInstanceState) {super.onCreate(savedInstanceState);Intent intent = getIntent();String path = intent.getStringExtra(“com.example.android.apis.Path”);if (path == null) {path = “”;}//创建一个SimpleAdapter来适配ListActivity,使用getData方法得到一个List<Map<String, Object>>对象//使用该对象来初始化列表项setListAdapter(new SimpleAdapter(this, getData(path),android.R.layout.simple_list_item_1, new String[] { “title” },new int[] { android.R.id.text1 }));getListView().setTextFilterEnabled(true);}protected List<Map<String, Object>> getData(String prefix) {List<Map<String, Object>> myData = new ArrayList<Map<String, Object>>();Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);mainIntent.addCategory(Intent.CATEGORY_SAMPLE_CODE);PackageManager pm = getPackageManager();List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);if (null == list)return myData;//定义上层前缀prefix,对于app/accessibility,它的前缀就是app,对于app,它的前缀就是nullString[] prefixPath;String prefixWithSlash = prefix;if (prefix.equals(“”)) {prefixPath = null;} else {prefixPath = prefix.split(“/”);prefixWithSlash = prefix + “/”;}int len = list.size();//用来存储已经扫描过的demo的MapMap<String, Boolean> entries = new HashMap<String, Boolean>();(int i = 0; i < len; i++) {ResolveInfo info = list.get(i);CharSequence labelSeq = info.loadLabel(pm);String label = labelSeq != null? labelSeq.toString(): info.activityInfo.name;if (prefixWithSlash.length() == 0 || label.startsWith(prefixWithSlash)) {String[] labelPath = label.split(“/”);String nextLabel = prefixPath == null ? labelPath[0] : labelPath[prefixPath.length];if ((prefixPath != null ? prefixPath.length : 0) == labelPath.length – 1) {addItem(myData, nextLabel, activityIntent(info.activityInfo.applicationInfo.packageName,info.activityInfo.name));} else {if (entries.get(nextLabel) == null) {addItem(myData, nextLabel, browseIntent(prefix.equals(“”) ? nextLabel : prefix + “/” + nextLabel));entries.put(nextLabel, true);}}}}//对生成的myData对象进行排序,其中使用到了Comparator<Map<String, Object>>的实例Collections.sort(myData, sDisplayNameComparator);return myData;}Comparator<Map<String, Object>> sDisplayNameComparator =new Comparator<Map<String, Object>>() {private final Collator collator = Collator.getInstance();(Map<String, Object> map1, Map<String, Object> map2) {return collator.compare(map1.get(“title”), map2.get(“title”));}};//将可以启动的Demo生成一个intentprotected Intent activityIntent(String pkg, String componentName) {Intent result = new Intent();result.setClassName(pkg, componentName);return result;}//生成一个Intent,用来在内部跳转到另一个ApiDemos Activity,带有path参数protected Intent browseIntent(String path) {Intent result = new Intent();result.setClass(this, ApiDemos.class);result.putExtra(“com.example.android.apis.Path”, path);return result;}(List<Map<String, Object>> data, String name, Intent intent) {Map<String, Object> temp = new HashMap<String, Object>();temp.put(“title”, name);temp.put(“intent”, intent);data.add(temp);}(“unchecked”)(ListView l, View v, int position, long id) {Map<String, Object> map = (Map<String, Object>)l.getItemAtPosition(position);Intent intent = (Intent) map.get(“intent”);startActivity(intent);}}

就会犯错误,就会有无数次让自己跌倒的机会出现,

狂刷Android范例之5:ApiDemos主程序框架分析

相关文章:

你感兴趣的文章:

标签云: