Android:SIM信息获取

77 篇文章 0 订阅
判断SIM卡属于哪个移动运营商

在文件AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

第一种方法:

获取手机的IMSI码,并判断是中国移动\中国联通\中国电信

TelephonyManager telManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

        /** 获取SIM卡的IMSI码

         * SIM卡唯一标识:IMSI 国际移动用户识别码(IMSI:InternationalMobile Subscriber Identification Number)是区别移动用户的标志,

         * 储存在SIM卡中,可用于区别移动用户的有效信息。IMSI由MCC、MNC、MSIN组成,其中MCC为移动国家号码,由3位数字组成,

         *唯一地识别移动客户所属的国家,我国为460;MNC为网络id,由2位数字组成,

         *用于识别移动客户所归属的移动网络,中国移动为00,中国联通为01,中国电信为03;MSIN为移动客户识别码,采用等长11位数字构成。

         * 唯一地识别国内GSM移动通信网中移动客户。所以要区分是移动还是联通,只需取得SIM卡中的MNC字段即可

         */

        Stringimsi = telManager.getSubscriberId();

 if(imsi!=null){

       if(imsi.startsWith("46000") ||imsi.startsWith("46002")){//因为移动网络编号46000下的IMSI已经用完,所以虚拟了一个46002编号,134/159号段使用了此编号

         //中国移动

        }elseif(imsi.startsWith("46001")){

         //中国联通

        }elseif(imsi.startsWith("46003")){

         //中国电信

        }

}

第二种方法

TelephonyManager telManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

        Stringoperator = telManager.getSimOperator();

 if(operator!=null){

       if(operator.equals("46000") ||operator.equals("46002")){

         //中国移动

        }elseif(operator.equals("46001")){

         //中国联通

        }elseif(operator.equals("46003")){

         //中国电信

        }

}

从SIM卡中获取联系人信息

在文件AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Uri uri = Uri.parse("content://icc/adn");

String[] projection = {"_id","name", "number"};

Cursor cursor = managedQuery(uri, projection, null, null,"name");

if(cursor!=null){

     while(cursor.moveToNext()){

  Stringname = cursor.getString(cursor.getColumnIndex("name"));

  Stringphone = cursor.getString(cursor.getColumnIndex("number"));

       }

}

Android系统内部通过Contentprovider对外共享Sim卡存放的联系人等信息,你可以通过操作Contentprovider来实现Sim卡信息的添删改查操作。下方是源码:


public class IccProvider extends ContentProvider {

    private staticfinal String TAG = "IccProvider";

    private staticfinal boolean DBG = false;

    private staticfinal String[] ADDRESS_BOOK_COLUMN_NAMES = new String[] {

       "name",

       "number"

    };

    private staticfinal int ADN = 1;

    private staticfinal int FDN = 2;

    private staticfinal int SDN = 3;

    private staticfinal String STR_TAG = "tag";

    private staticfinal String STR_NUMBER = "number";

    private staticfinal String STR_PIN2 = "pin2";

    private staticfinal UriMatcher URL_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    static {

       URL_MATCHER.addURI("icc", "adn", ADN);

       URL_MATCHER.addURI("icc", "fdn", FDN);

       URL_MATCHER.addURI("icc", "sdn", SDN);

    }

    privateboolean mSimulator;

    @Override

    public booleanonCreate() {

        Stringdevice = SystemProperties.get("ro.product.device");

        if(!TextUtils.isEmpty(device)) {

           mSimulator = false;

        } else {

            //simulator

           mSimulator = true;

        }

        returntrue;

    }

    @Override

    public Cursorquery(Uri url, String[] projection, String selection,

           String[] selectionArgs, String sort) {

       ArrayList<ArrayList> results;

        if(!mSimulator) {

            switch(URL_MATCHER.match(url)) {

               case ADN:

                   results = loadFromEf(IccConstants.EF_ADN);

                   break;

               case FDN:

                   results = loadFromEf(IccConstants.EF_FDN);

                   break;

               case SDN:

                   results = loadFromEf(IccConstants.EF_SDN);

                   break;

               default:

                   throw new IllegalArgumentException("Unknown URL " + url);

            }

        } else {

            //Fake up some data for the simulator

           results = new ArrayList<ArrayList>(4);

           ArrayList<String> contact;

           contact = new ArrayList<String>();

           contact.add("Ron Stevens/H");

           contact.add("512-555-5038");

           results.add(contact);

           contact = new ArrayList<String>();

           contact.add("Ron Stevens/M");

           contact.add("512-555-8305");

           results.add(contact);

           contact = new ArrayList<String>();

           contact.add("Melissa Owens");

           contact.add("512-555-8305");

           results.add(contact);

           contact = new ArrayList<String>();

           contact.add("Directory Assistence");

           contact.add("411");

           results.add(contact);

        }

        return newArrayListCursor(ADDRESS_BOOK_COLUMN_NAMES, results);

    }

    @Override

    public StringgetType(Uri url) {

        switch(URL_MATCHER.match(url)) {

            caseADN:

            caseFDN:

            caseSDN:

               return "vnd.android.cursor.dir/sim-contact";

           default:

               throw new IllegalArgumentException("Unknown URL " + url);

        }

    }

    @Override

    public Uriinsert(Uri url, ContentValues initialValues) {

        UriresultUri;

        intefType;

        Stringpin2 = null;

        if (DBG)log("insert");

        int match= URL_MATCHER.match(url);

        switch(match) {

            caseADN:

               efType = IccConstants.EF_ADN;

               break;

            caseFDN:

               efType = IccConstants.EF_FDN;

               pin2 = initialValues.getAsString("pin2");

               break;

           default:

               throw new UnsupportedOperationException(

                       "Cannot insert into URL: " + url);

        }

        String tag= initialValues.getAsString("tag");

        Stringnumber = initialValues.getAsString("number");

        booleansuccess = addIccRecordToEf(efType, tag, number, pin2);

        if(!success) {

            returnnull;

        }

       StringBuilder buf = new StringBuilder("content://im/");

        switch(match) {

            caseADN:

               buf.append("adn/");

               break;

            caseFDN:

               buf.append("fdn/");

               break;

        }

        // TODO:we need to find out the rowId for the newly added record

       buf.append(0);

        resultUri= Uri.parse(buf.toString());

        /*

        // notifyinterested parties that an insertion happened

       getContext().getContentResolver().notifyInsert(

               resultUri, rowID, null);

        */

        returnresultUri;

    }

    private StringnormalizeValue(String inVal) {

        int len =inVal.length();

        StringretVal = inVal;

        if(inVal.charAt(0) == '\'' && inVal.charAt(len-1) == '\'') {

            retVal= inVal.substring(1, len-1);

        }

        returnretVal;

    }

    @Override

    public intdelete(Uri url, String where, String[] whereArgs) {

        intefType;

        if (DBG)log("delete");

        int match= URL_MATCHER.match(url);

        switch(match) {

            caseADN:

               efType = IccConstants.EF_ADN;

               break;

            caseFDN:

               efType = IccConstants.EF_FDN;

               break;

           default:

               throw new UnsupportedOperationException(

                       "Cannot insert into URL: " + url);

        }

        // parsewhere clause

        String tag= null;

        Stringnumber = null;

        Stringpin2 = null;

        String[]tokens = where.split("AND");

        int n =tokens.length;

        while (--n>= 0) {

            Stringparam = tokens[n];

            if(DBG) log("parsing '" + param + "'");

           String[] pair = param.split("=");

            if(pair.length != 2) {

               Log.e(TAG, "resolve: bad whereClause parameter: " + param);

               continue;

            }

            Stringkey = pair[0].trim();

            Stringval = pair[1].trim();

            if(STR_TAG.equals(key)) {

               tag = normalizeValue(val);

            } elseif (STR_NUMBER.equals(key)) {

               number = normalizeValue(val);

            } elseif (STR_PIN2.equals(key)) {

               pin2 = normalizeValue(val);

            }

        }

        if(TextUtils.isEmpty(tag)) {

            return0;

        }

        if (efType== FDN && TextUtils.isEmpty(pin2)) {

            return0;

        }

        booleansuccess = deleteIccRecordFromEf(efType, tag, number, pin2);

        if(!success) {

            return0;

        }

        return 1;

    }

    @Override

    public intupdate(Uri url, ContentValues values, String where, String[] whereArgs) {

        intefType;

        Stringpin2 = null;

        if (DBG)log("update");

        int match= URL_MATCHER.match(url);

        switch(match) {

            caseADN:

               efType = IccConstants.EF_ADN;

               break;

            caseFDN:

               efType = IccConstants.EF_FDN;

               pin2 = values.getAsString("pin2");

               break;

           default:

               throw new UnsupportedOperationException(

                       "Cannot insert into URL: " + url);

        }

        String tag= values.getAsString("tag");

        Stringnumber = values.getAsString("number");

        StringnewTag = values.getAsString("newTag");

        StringnewNumber = values.getAsString("newNumber");

        booleansuccess = updateIccRecordInEf(efType, tag, number,

               newTag, newNumber, pin2);

        if(!success) {

            return0;

        }

        return 1;

    }

    privateArrayList<ArrayList> loadFromEf(int efType) {

       ArrayList<ArrayList> results = new ArrayList<ArrayList>();

       List<AdnRecord> adnRecords = null;

        if (DBG)log("loadFromEf: efType=" + efType);

        try {

           IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(

                   ServiceManager.getService("simphonebook"));

            if(iccIpb != null) {

               adnRecords = iccIpb.getAdnRecordsInEf(efType);

            }

        } catch(RemoteException ex) {

            //ignore it

        } catch(SecurityException ex) {

            if(DBG) log(ex.toString());

        }

        if(adnRecords != null) {

            //Load the results

            int N= adnRecords.size();

            if(DBG) log("adnRecords.size=" + N);

            for(int i = 0; i < N ; i++) {

               loadRecord(adnRecords.get(i), results);

            }

        } else {

            // Noresults to load

           Log.w(TAG, "Cannot load ADN records");

           results.clear();

        }

        if (DBG)log("loadFromEf: return results");

        returnresults;

    }

    privateboolean

   addIccRecordToEf(int efType, String name, String number, String pin2) {

        if (DBG)log("addIccRecordToEf: efType=" + efType + ", name=" + name+

               ", number=" + number);

        booleansuccess = false;

        // TODO:do we need to call getAdnRecordsInEf() before calling

        //updateAdnRecordsInEfBySearch()? In any case, we will leave

        // the UIlevel logic to fill that prereq if necessary. But

        //hopefully, we can remove this requirement.

        try {

           IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(

                   ServiceManager.getService("simphonebook"));

            if(iccIpb != null) {

               success = iccIpb.updateAdnRecordsInEfBySearch(efType, "","",

                       name, number, pin2);

            }

        } catch(RemoteException ex) {

            //ignore it

        } catch(SecurityException ex) {

            if(DBG) log(ex.toString());

        }

        if (DBG)log("addIccRecordToEf: " + success);

        returnsuccess;

    }

    privateboolean

   updateIccRecordInEf(int efType, String oldName, String oldNumber,

            StringnewName, String newNumber,String pin2) {

        if (DBG)log("updateIccRecordInEf: efType=" + efType +

               ", oldname=" + oldName + ", oldnumber=" + oldNumber+

               ", newname=" + newName + ", newnumber=" +newNumber);

        booleansuccess = false;

        try {

           IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(

                   ServiceManager.getService("simphonebook"));

            if(iccIpb != null) {

               success = iccIpb.updateAdnRecordsInEfBySearch(efType,

                       oldName, oldNumber, newName, newNumber, pin2);

            }

        } catch(RemoteException ex) {

            //ignore it

        } catch(SecurityException ex) {

            if(DBG) log(ex.toString());

        }

        if (DBG)log("updateIccRecordInEf: " + success);

        returnsuccess;

    }

    privateboolean deleteIccRecordFromEf(int efType, String name, String number, Stringpin2) {

        if (DBG)log("deleteIccRecordFromEf: efType=" + efType +

               ", name=" + name + ", number=" + number + ",pin2=" + pin2);

        booleansuccess = false;

        try {

           IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(

                   ServiceManager.getService("simphonebook"));

            if(iccIpb != null) {

               success = iccIpb.updateAdnRecordsInEfBySearch(efType,

                       name, number, "", "", pin2);

            }

        } catch(RemoteException ex) {

            //ignore it

        } catch(SecurityException ex) {

            if(DBG) log(ex.toString());

        }

        if (DBG)log("deleteIccRecordFromEf: " + success);

        returnsuccess;

    }

    /**

     * Loads anAdnRecord into an ArrayList. Must be called with mLock held.

     *

     * @paramrecord the ADN record to load from

     * @paramresults the array list to put the results in

     */

    private voidloadRecord(AdnRecord record,

           ArrayList<ArrayList> results) {

        if(!record.isEmpty()) {

           ArrayList<String> contact = new ArrayList<String>(2);

            StringalphaTag = record.getAlphaTag();

            Stringnumber = record.getNumber();

            if(DBG) log("loadRecord: " + alphaTag + ", " + number);

           contact.add(alphaTag);

           contact.add(number);

           results.add(contact);

        }

    }

    private voidlog(String msg) {

        Log.d(TAG,"[IccProvider] " + msg);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值