【问题标题】:how to get the context in dialogFragment when get imei info获取imei信息时如何在dialogFragment中获取上下文
【发布时间】:2023-03-31 00:52:01
【问题描述】:
@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 = null;

    builder.setView(view)
            .setTitle("Activer la Version");
    registerKey = view.findViewById(R.id.regiter_key);
    tvIMEI = view.findViewById(R.id.tvIMEI);
    String sIMEI;
    sIMEI = getUniqueIMEIId(getContext(this));
    tvIMEI.setText(sIMEI);
    return builder.create();
}

getUniqueIMEIID 不是 abel this context ,当我调用 getContext(this) 时给出错误image from android studio

public static String getUniqueIMEIId(Context context) {
    TelephonyManager telephonyManager = (TelephonyManager) 
     context.getSystemService(Context.TELEPHONY_SERVICE);
     ...
     String imei = telephonyManager.getDeviceId();
    ...
}

【问题讨论】:

  • 你的 getUniqueIMEIId 方法是什么?是你自己的方法还是第三个库?

标签: java android android-studio android-layout contextmenu


【解决方案1】:

如果您使用dialogFragment 创建对话框,而getUniqueIMEIId 是这样的:

public static String getUniqueIMEIId(Context context) {
    try {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {          
            return "";
        }
        String imei = telephonyManager.getDeviceId();
        Log.e("imei", "=" + imei);
        if (imei != null && !imei.isEmpty()) {
            return imei;
        } else {
            return android.os.Build.SERIAL;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "not_found";
}

getContext() 是。

返回此片段当前关联的上下文 但是getUniqueIMEIId 方法需要上下文

getActivity()

返回此片段当前关联的 FragmentActivity。如果片段与上下文相关联,则可能返回 null

在主要情况下它们是相同的。我们只需要context。所以我建议你使用getContext()

【讨论】:

    【解决方案2】:

    究竟是什么错误?是否显示 Context 是预期的,但通过了一个 Dialog?

    如果是,您可以使用上面使用的 getActivity() 方法来访问上下文。

    所以就打个电话

    sIMEI = getUniqueIMEIId(getActivity());
    

    【讨论】:

      【解决方案3】:

      getContext(this) 替换为getActivity().getApplicationContext(),它应该可以工作。

      【讨论】:

        猜你喜欢
        • 2013-03-20
        • 1970-01-01
        • 2020-01-30
        • 2013-05-16
        • 2019-05-19
        • 2021-03-17
        • 2014-10-05
        相关资源
        最近更新 更多