Android开发网上的一些重要知识点[经验分享]

文章分类:公司动态 发布时间:2013-07-27 原文作者:admin 阅读( )

1. android单实例运行方法

我们都知道Android平台没有任务管理器,而内部App维护者一个Activity history stack来实现窗口显示和销毁,对于常规从快捷方式运行来看都是startActivity可能会使用FLAG_ACTIVITY_NEW_TASK标记来打开一个新窗口,比如Launcher,所以考虑单任务的实现方法比较简单,首先Android123纠正下大家一种错误的方法就是直接在androidmanifest.xml的application节点中加入android:launchMode="singleInstance"这句,其实这样将不会起到任何作用,Apps内部维护的历史栈作用于Activity,我们必须在activity节点中加入android:launchMode="singleInstance" 这句才能保证单实例,当然一般均加在主程序启动窗口的Activity。

2. px像素如何转为dip设备独立像素

最近有网友问如何将px像素转为dip独立设备像素,由于Android的设备分辨率众多,目前主流的为wvga,而很多老的设备为hvga甚至低端的qvga,对于兼容性来说使用dip无非是比较方便的,由于他和分辨率无关和屏幕的密度大小有关,所以推荐使用。  px= (int) (dip*density+0.5f) //这里android开发网提示大家很多网友获取density(密度)的方法存在问题,从资源中获取的是静态定义的,一般为1.0对于HVGA是正好的,而对于wvga这样的应该从WindowsManager中获取,WVGA为1.5 这里可以再补充一下dip,sip的知识

3. Android中动态改变ImageView大小

很多网友可能发现在layout.xml文件中定义了ImageView的绝对大小后,无法动态修改以后的大小显示,其实Android平台在设计UI控件时考虑到这个问题,为了适应不同的Drawable可以通过在xml的相关ImageView中加入android:scaleType="fitXY" 这行即可,但因为使用了缩放可能会造成当前UI有所变形。使用的前提是限制ImageView所在的层,可以使用一个内嵌的方法限制显示。

4. 如何判断Android手机当前是否联网?

如果拟开发一个网络应用的程序,首先考虑是否接入网络,在Android手机中判断是否联网可以通过 ConnectivityManager 类的isAvailable()方法判断,首先获取网络通讯类的实例 ConnectivityManager cwjManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); ,使用cwjManager.getActiveNetworkInfo().isAvailable(); 来返回是否有效,如果为True则表示当前Android手机已经联网,可能是WiFi或GPRS、HSDPA等等,具体的可以通过ConnectivityManager 类的getActiveNetworkInfo() 方法判断详细的接入方式,需要注意的是有关调用需要加入<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> 这个权限,android开发网提醒大家在真机上Market和Browser程序都使用了这个方法,来判断是否继续,同时在一些网络超时的时候也可以检查下网络连接是否存在,以免浪费手机上的电力资源。

5. Drawable、Bitmap、Canvas和Paint的关系

很多网友刚刚开始学习Android平台,对于Drawable、Bitmap、Canvas和Paint它们之间的概念不是很清楚,其实它们除了Drawable外早在Sun的J2ME中就已经出现了,但是在Android平台中,Bitmap、Canvas相关的都有所变化。   首先让我们理解下Android平台中的显示类是View,但是还提供了底层图形类android.graphics,今天所说的这些均为graphics底层图形接口。   Bitmap - 称作位图,一般位图的文件格式后缀为bmp,当然编码器也有很多如RGB565、RGB888。作为一种逐像素的显示对象执行效率高,但是缺点也很明显存储效率低。我们理解为一种存储对象比较好。   Drawable - 作为Android平下通用的图形对象,它可以装载常用格式的图像,比如GIF、PNG、JPG,当然也支持BMP,当然还提供一些高级的可视化对象,比如渐变、图形等。   Canvas - 名为画布,我们可以看作是一种处理过程,使用各种方法来管理Bitmap、GL或者Path路径,同时它可以配合Matrix矩阵类给图像做旋转、缩放等操作,同时Canvas类还提供了裁剪、选取等操作。    Paint - 我们可以把它看做一个画图工具,比如画笔、画刷。他管理了每个画图工具的字体、颜色、样式。   如果涉及一些Android游戏开发、显示特效可以通过这些底层图形类来高效实现自己的应用。 

6. Activity切换导致的onCreate重复执行

部分网友会发现Activity在切换到后台或布局从横屏LANDSCAPE切换到PORTRAIT,会重新切换Activity会触发一次onCreate方法,我们可以在androidmanifest.xml中的activit元素加入这个属性android:configChanges="orientation|keyboardHidden" 即可,比如 <activity android:name=".android123" android:configChanges="orientation|keyboardHidden"android:label="@string/app_name">   同时在Activity的Java文件中重载onConfigurationChanged(Configuration newConfig)这个方法,这样就不会在布局切换或窗口切换时重载onCreate等方法。代码如下: @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
     if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
     {
//land
     }
     else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
     {
//port
     }
    }

7. Android的ImageButton问题

很多网友对Android提供的ImageButton有个疑问,当显示Drawable图片时就不会再显示文字了,其实解决的方法有两种,第一种就是图片中就写入文字,但是这样解决会增加程序体积,同时硬编码方式会影响多国语言的发布。第二种解决方法很简单,通过分析可以看到ImageButton的layout,我们可以直接直接继承,添加一个TextView,对齐方式为右侧即可实现ImageButton支持文字右侧显示。

8. Android代码优化技术

1.Java内存控制   对于字符串操作而言如果需要连加这样的操作建议使用StringBuilder,经过调试不难发现如果你的字符串每次连加,使用String需要的内存开销会远大于StringBuilder,然后Android手机常规的运行内存大约在128MB左右,对于运行多任务就需要考虑了,Android开发网提示因为Java有GC不需要手动释放那么分配的时候就要格外的小心,频繁的GC操作仍然是很影响性能的,在调试时我们可以通过logcat查看内存释放情况。   2.循环使用   平时在访问一个属性的时候效率远比一个固定变量低,如果你的循环估计次数常常大于5,假设xxx.GetLength()方法的值一般大于5,推荐这样写,比如   for(int i=0;i<xxx.GetLength();i++)   这里xxx.GetLength在每次循环都要调用,必然会影响程序效率,在游戏开发中显得更为明显,改进的方法应该为   int j=xxx.GetLength()    for(int i=0;i<j;i++)   3.图片的优化   在Android平台中2维图像处理库BitmapFactory做的比较智能,为了减少文件体积和效率,常常不用很多资源文件,而把很多小图片放在一个图片中,有切片的方式来完成,在J2ME中我们这样是为了将少文件头而解决MIDP这些设备的问题,而Android中虽然机型硬件配置都比较高,有关Android G1硬件配置可以参考G1手机参数以及评测,但是当资源多时这样的运行效率还是令人满意的,至少Dalvik优化的还不是很够。

9. Android开发进阶之NIO非阻塞包(一)

对于Android的网络通讯性能的提高,我们可以使用Java上高性能的NIO (New I/O) 技术进行处理,NIO是从JDK 1.4开始引入的,NIO的N我们可以理解为Noblocking即非阻塞的意思,相对应传统的I/O,比如Socket的accpet()、read()这些方法而言都是阻塞的。   NIO主要使用了Channel和Selector来实现,Java的Selector类似Winsock的Select模式,是一种基于事件驱动的,整个处理方法使用了轮训的状态机,如果你过去开发过Symbian应用的话这种方式有点像活动对象,好处就是单线程更节省系统开销,NIO的好处可以很好的处理并发,对于Android网游开发来说比较关键,对于多点Socket连接而言使用NIO可以大大减少线程使用,降低了线程死锁的概率,毕竟手机游戏有UI线程,音乐线程,网络线程,管理的难度可想而知,同时I/O这种低速设备将影响游戏的体验。   NIO作为一种中高负载的I/O模型,相对于传统的BIO (Blocking I/O)来说有了很大的提高,处理并发不用太多的线程,省去了创建销毁的时间,如果线程过多调度是问题,同时很多线程可能处于空闲状态,大大浪费了CPU时间,同时过多的线程可能是性能大幅下降,一般的解决方案中可能使用线程池来管理调度但这种方法治标不治本。使用NIO可以使并发的效率大大提高。当然NIO和JDK 7中的AIO还存在一些区别,AIO作为一种更新的当然这是对于Java而言,如果你开发过Winsock服务器,那么IOCP这样的I/O完成端口可以解决更高级的负载,当然了今天Android123主要给大家讲解下为什么使用NIO在Android中有哪些用处。    NIO我们分为几个类型分别描述,作为Java的特性之一,我们需要了解一些新的概念,比如ByteBuffer类,Channel,SocketChannel,ServerSocketChannel,Selector和SelectionKey。有关具体的使用,Android开发网将在明天详细讲解。网友可以在Android SDK文档中看下java.nio和java.nio.channels两个包了解。http://www.android123.com.cn/androidkaifa/695.html
了解下这种技术,看看在马上要做的项目中是否用得到

10. Android Theme和Styles内部定义解析

昨天我们讲到的有关在AndroidManifest.xml中定义Activity的theme方法来实现无标题的方法,在使用xml让你的Activity无标题方法 一文中讲到的,很多网友不明白为什么这样做,其实在Android123以前的文章中多次提到了styles样式定义方法,今天Android开发网再次把一些网友回顾了解下android样式的内部定义。在一个工程的res/values/theme.xml中我们可以方便的定义自己的风格主题,比如下面的cwjTheme中我们使用了基于android内部的白色调的背景Theme.Light,设置windowsNoTitle为true代表没有标题,背景颜色我们使用了android内部定义的透明,同时设置listView控件的样式为cwjListView,xml样式代码如下:   <?xml version="1.0" encoding="utf-8"?> 
<resources> 
<style name="cwjTheme" parent="android:Theme.Light"> 
   <item name="android:windowNoTitle">true</item> 
   <item name="android:windowBackground">@android:color/transparent</item> 
   <item name="android:listViewStyle">@style/cwjListView</item> 
</style>  有关ListView控件我们自定义的风格就是修改下系统listview这个控件的每行分隔符样式,这里我们在工程下res/drawable文件夹下放一个图片名为list_selector图片,这样我们的cwjListView的代码可以这样写   <style name="cwjListView" parent="@android:style/Widget.ListView"> 
     <item name="android:listSelector">@drawable/list_selector</item> 
   </style> 
</resources>   通过定义style可以设置更多,比如让cwjListView的字体颜色就加入textAppearance属性,比如 <item name="textAppearance">@android:style/TextAppearance</item> 等等。

11.Android JSON解析示例代码

来自Google官方的有关Android平台的JSON解析示例,如果远程服务器使用了json而不是xml的数据提供,在Android平台上已经内置的org.json包可以很方便的实现手机客户端的解析处理。下面Android123一起分析下这个例子,帮助Android开发者需要有关 HTTP通讯、正则表达式、JSON解析、appWidget开发的一些知识。 public class WordWidget extends AppWidgetProvider { //appWidget
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        context.startService(new Intent(context, UpdateService.class)); //避免ANR,所以Widget中开了个服务
    }     public static class UpdateService extends Service {
        @Override
        public void onStart(Intent intent, int startId) {
            // Build the widget update for today
            RemoteViews updateViews = buildUpdate(this);             ComponentName thisWidget = new ComponentName(this, WordWidget.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(thisWidget, updateViews);
        }         public RemoteViews buildUpdate(Context context) {
            // Pick out month names from resources
            Resources res = context.getResources();
            String[] monthNames = res.getStringArray(R.array.month_names);              Time today = new Time();
            today.setToNow();             String pageName = res.getString(R.string.template_wotd_title,
                    monthNames[today.month], today.monthDay);
            RemoteViews updateViews = null;
            String pageContent = "";             try {
                SimpleWikiHelper.prepareUserAgent(context);
                pageContent = SimpleWikiHelper.getPageContent(pageName, false);
            } catch (ApiException e) {
                Log.e("WordWidget", "Couldn't contact API", e);
            } catch (ParseException e) {
                Log.e("WordWidget", "Couldn't parse API response", e);
            }             Pattern pattern = Pattern.compile(SimpleWikiHelper.WORD_OF_DAY_REGEX); //正则表达式处理,有关定义见下面的SimpleWikiHelper类
            Matcher matcher = pattern.matcher(pageContent);
            if (matcher.find()) {
                updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_word);                 String wordTitle = matcher.group(1);
                updateViews.setTextViewText(R.id.word_title, wordTitle);
                updateViews.setTextViewText(R.id.word_type, matcher.group(2));
                updateViews.setTextViewText(R.id.definition, matcher.group(3).trim());                 String definePage = res.getString(R.string.template_define_url,
                        Uri.encode(wordTitle));
                Intent defineIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(definePage)); //这里是打开相应的网页,所以Uri是http的url,action是view即打开web浏览器
                PendingIntent pendingIntent = PendingIntent.getActivity(context,
                        0 /* no requestCode */, defineIntent, 0 /* no flags */);
                updateViews.setOnClickPendingIntent(R.id.widget, pendingIntent); //单击Widget打开Activity             } else { 
                updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_message);
                CharSequence errorMessage = context.getText(R.string.widget_error);
                updateViews.setTextViewText(R.id.message, errorMessage);
            }
            return updateViews;
        }         @Override
        public IBinder onBind(Intent intent) {
            // We don't need to bind to this service
            return null;
        }
    }
}   有关网络通讯的实体类,以及一些常量定义如下:   public class SimpleWikiHelper {
    private static final String TAG = "SimpleWikiHelper";     public static final String WORD_OF_DAY_REGEX =
            "(?s)\\{\\{wotd\\|(.+?)\\|(.+?)\\|([^#\\|]+).*?\\}\\}";     private static final String WIKTIONARY_PAGE =
            "http://en.wiktionary.org/w/api.php?action=query&prop=revisions&titles=%s&" +
            "rvprop=content&format=json%s";     private static final String WIKTIONARY_EXPAND_TEMPLATES =
            "&rvexpandtemplates=true";     private static final int HTTP_STATUS_OK = 200;     private static byte[] sBuffer = new byte[512];     private static String sUserAgent = null;      public static class ApiException extends Exception {
        public ApiException(String detailMessage, Throwable throwable) {
            super(detailMessage, throwable);
        }         public ApiException(String detailMessage) {
            super(detailMessage);
        }
    }     public static class ParseException extends Exception {
        public ParseException(String detailMessage, Throwable throwable) {
            super(detailMessage, throwable);
        }
    }     public static void prepareUserAgent(Context context) {
        try {
            // Read package name and version number from manifest
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            sUserAgent = String.format(context.getString(R.string.template_user_agent),
                    info.packageName, info.versionName);         } catch(NameNotFoundException e) {
            Log.e(TAG, "Couldn't find package information in PackageManager", e);
        }
    }     public static String getPageContent(String title, boolean expandTemplates)
            throws ApiException, ParseException {
        String encodedTitle = Uri.encode(title);
        String expandClause = expandTemplates ? WIKTIONARY_EXPAND_TEMPLATES : "";         String content = getUrlContent(String.format(WIKTIONARY_PAGE, encodedTitle, expandClause));
        try {
            JSONObject response = new JSONObject(content);
            JSONObject query = response.getJSONObject("query");
            JSONObject pages = query.getJSONObject("pages");
            JSONObject page = pages.getJSONObject((String) pages.keys().next());
            JSONArray revisions = page.getJSONArray("revisions");
            JSONObject revision = revisions.getJSONObject(0);
            return revision.getString("*");
        } catch (JSONException e) {
            throw new ParseException("Problem parsing API response", e);
        }
    }     protected static synchronized String getUrlContent(String url) throws ApiException {
        if (sUserAgent == null) {
            throw new ApiException("User-Agent string must be prepared");
        }         HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        request.setHeader("User-Agent", sUserAgent); //设置客户端标识         try {
            HttpResponse response = client.execute(request);             StatusLine status = response.getStatusLine();
            if (status.getStatusCode() != HTTP_STATUS_OK) {
                throw new ApiException("Invalid response from server: " +
                        status.toString());
            }             HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent(); //获取HTTP返回的数据流             ByteArrayOutputStream content = new ByteArrayOutputStream();             int readBytes = 0;
            while ((readBytes = inputStream.read(sBuffer)) != -1) {
                content.write(sBuffer, 0, readBytes); //转化为字节数组流
            }             return new String(content.toByteArray()); //从字节数组构建String
        } catch (IOException e) {
            throw new ApiException("Problem communicating with API", e);
        }
    }
} 有关整个每日维基的widget例子比较简单,主要是帮助大家积累常用代码,了解Android平台 JSON的处理方式,毕竟很多Server还是Java的。

12.Android中使用定时器TimerTask类介绍

在Android平台中需要反复按周期执行方法可以使用Java上自带的TimerTask类,TimerTask相对于Thread来说对于资源消耗的更低,除了使用Android自带的AlarmManager使用Timer定时器是一种更好的解决方法。 我们需要引入import java.util.Timer; 和 import java.util.TimerTask; private Timer  mTimer = new Timer(true);
private TimerTask mTimerTask;     mTimerTask = new TimerTask()
    {
      public void run()
      {
       Log.v("android123","cwj");
      }        
     };
     mTimer.schedule(mTimerTask, 5000,1000);  //在1秒后每5秒执行一次定时器中的方法,比如本文为调用log.v打印输出。   如果想取消可以调用下面方法,取消定时器的执行    while(!mTimerTask.cancel());
      mTimer.cancel();   最后Android123提示大家,如果处理的东西比较耗时还是开个线程比较好,Timer还是会阻塞主线程的执行,更像是一种消息的执行方式。当然比Handler的postDelay等方法更适合处理计划任务。
原文来自:tbkj