您的位置:首页 > 移动开发 > Android开发

android版本兼容问题

2016-01-08 15:45 417 查看
尽管Android向下兼容不好,但是一个程序还是可以在多个平台上跑的。向下兼容不好,接口改变,新的平台上不能用旧的API,旧的平台更不可能用新的API,不等于一个平台需要一个APK。可以在高SDK上开发,并在程序中作版本判断,低版本运行环境使用旧的API。

例如要开发一个显示通话记录的程序,需要兼容1.6~2.2,我们知道不同的平台SDK level不同,1.5是3,1.6是4,2.2是8。对应的可以使用android.os.Build进行判断。源代码如下:

[code]if(Build.VERSION.SDK_INT <= 4)

        {

        Toast.makeText(this, "version" + Build.VERSION.RELEASE+ " :" + Build.VERSION.SDK_INT, Toast.LENGTH_SHORT).show();

        }

        else

        {

        Toast.makeText(this, "version" + Build.VERSION.RELEASE+ " :" + Build.VERSION.SDK_INT, Toast.LENGTH_SHORT).show();

        }


这样就可以在不同的分支中使用不同的API。下面是一个简单的通讯录示例。其中可以看到在2.2下,1.6的接口Contacts.Phones会被自动划上横线,表示在此版本下已经无效。

[code]if(Build.VERSION.SDK_INT <= 4)

        {

                 Toast.makeText(this, "version" + Build.VERSION.RELEASE+ " :" + Build.VERSION.SDK_INT, Toast.LENGTH_SHORT).show();

                 String[] columns = new String[] {Phones.NAME, Phones.NUMBER};

                 ContentResolver cr = this.getContentResolver();

            Cursor c= cr.query(Contacts.Phones.CONTENT_URI,

                               null, null,null, Contacts.People.DEFAULT_SORT_ORDER);

            c.moveToFirst();

            SimpleCursorAdapter adapter = new SimpleCursorAdapter(

                               this,

                               R.layout.main,

                               c,

                               new String[]{Contacts.Phones.NAME,Contacts.Phones.NUMBER},

                               new int[]{R.id.TextView01,R.id.TextView02});

            this.setListAdapter(adapter);

        }

        else

        {

                 Toast.makeText(this, "version" + Build.VERSION.RELEASE+ " :" + Build.VERSION.SDK_INT, Toast.LENGTH_SHORT).show();

                 ContentResolver cr = this.getContentResolver();

            Cursor c= cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,

                               null, null,null, null);

            SimpleCursorAdapter adapter = new SimpleCursorAdapter(

                               this,

                               R.layout.main,

                               c,

                               new String[]{ ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER},

                               new int[]{R.id.TextView01,R.id.TextView02});

            this.setListAdapter(adapter);

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: