开发者

Android, how to take phone number?

开发者 https://www.devze.com 2023-04-10 04:22 出处:网络
I my application I have written following code in order to extract phone number. When I run it in emulator, everything is fine but when I run it on a real device, application crashes. what is your sug

I my application I have written following code in order to extract phone number. When I run it in emulator, everything is fine but when I run it on a real device, application crashes. what is your suggestion? I have added <uses-permission android:name="android.permission.READ_PHONE_STATE"/> in manifest file.

public class TestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
TextView phoneNumber = (TextView)findViewById(R.id.tvPhoneNumber);
phoneNumber.setText(getMy10DigitPhoneNumber());
}开发者_JAVA百科
private String getMyPhoneNumber(){
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
        return mTelephonyMgr.getLine1Number();
    }

    private String getMy10DigitPhoneNumber(){
        String s = getMyPhoneNumber();
        return s.substring(2);
    }

}


getLine1Number() will return the phone number string if available and null if not available. So you should check for Null Pointer.

private String getMy10DigitPhoneNumber() {
        String s = getMyPhoneNumber();
        if(s == null) return "";
        else return s.substring(2);
}

Also check the length of the string returned by getLine1Number(). In my phone, i got a ""string. In this case, substring() will throw IndexOutOfBoundsException. So check for length of s also before calling substring().

0

精彩评论

暂无评论...
验证码 换一张
取 消