DialogFragment调用getUniqueIMEIId获取IMEI时上下文传参报错问题
解决DialogFragment中获取IMEI时的上下文传递错误
嘿,我一眼就看到你在onCreateDialog方法里的问题啦——你调用getUniqueIMEIId(getContext(this))时的上下文传递写法错了,这就是导致错误的根源。
问题出在哪?
getContext()是DialogFragment(它继承自Fragment)的内置方法,完全不需要传入任何参数,你写成getContext(this)属于错误的调用方式,自然没法正确传递上下文。
修正后的完整代码
我帮你把代码调整好了,还加了空指针防护,避免不必要的崩溃:
@NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.layout_reg_dialog, null); TextView tvIMEI = view.findViewById(R.id.tvIMEI); builder.setView(view) .setTitle("Activer la Version"); registerKey = view.findViewById(R.id.regiter_key); String sIMEI = null; Context context = getContext(); // 先判空,避免上下文为空时调用方法引发崩溃 if (context != null) { sIMEI = getUniqueIMEIId(context); } // 给个默认文本,防止空字符串显示 tvIMEI.setText(sIMEI != null ? sIMEI : "无法获取IMEI信息"); return builder.create(); }
额外要注意的点
权限必须到位:获取IMEI需要在
AndroidManifest.xml中声明权限:<uses-permission android:name="android.permission.READ_PHONE_STATE"/>而且Android 6.0(API 23)及以上版本,还得动态申请这个权限,不然会直接抛出权限异常。
API版本兼容问题:
TelephonyManager.getDeviceId()在API 26已经被废弃了,如果要适配更高版本的Android,建议改用更针对性的方法:public static String getUniqueIMEIId(Context context) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String imei = null; if (telephonyManager != null) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { imei = telephonyManager.getImei(); // GSM设备用这个 // 如果是CDMA设备,可以用telephonyManager.getMeid() } else { imei = telephonyManager.getDeviceId(); } } catch (SecurityException e) { // 权限未授权时的异常处理 e.printStackTrace(); } } return imei; }
内容的提问来源于stack exchange,提问作者Amor Laamayad
相关产品推荐
相关产品推荐

