在没有应用程序上下文的情况下获取 IMEI 和电话号码

Getting IMEI and Telephone Number without Application Context

我一直在搜索并发现 this post 对于获取我设备的电话 phone 号码很有用。在我的主服务文件中,我有一个 public 静态变量,该变量设置为使用上述 post.

中的方法找到的 phone 数字
class MyService extends Service implements... {
    //Phone number of the device
    public static String phoneNumber;

    public void onCreate() {
        //Grab phone number of device
        TelephonyManager tMgr = (TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        String mPhoneNumber = tMgr.getLine1Number();

        phoneNumber=mPhoneNumber;
    }
}

我绝不是高级软件开发人员,但我知道使用 public 静态变量不是最佳解决方案,因为它可以从 class 外部进行更改。这个 public 静态 phone 号码正在另一个 class 中访问,它将它发送到服务器。它的访问方式如下:

String devicePhoneNumber;
devicePhoneNumber = MyService.phoneNumber;

如果有一种方法可以在不使用 TelephonyManager 的情况下获取 phone 号码和 IMEI,或者更具体地说,不需要应用程序上下文,我就不必担心这个问题。如果那不可能,也许有使用 public 静态变量的解决方法?

感谢大家的帮助

在没有上下文的情况下没有获得 phone 号码的解决方法,因为上下文是您进入用户 phone 的门户。它使您可以访问存储、位置、显示,几乎所有内容。

如果您经常使用 phone 编号,我认为您应该在 mainActivity 中为它创建一个 getter,无论如何您都可以从那里获取它。在你的 mainActivity onCreate() 方法中初始化

private String phoneNumber;

成为 phone 号码并在您的 mainActivity 中创建一个

public String getPhoneNumber()

要从您的服务访问它,您可以在应用程序的其他部分调用

((MainActivityNameHere) getApplicationContext()).getPhoneNumber()

除非你在静态方法中工作。不过,您仍然需要访问 MainActivity。我通常在 mainActivity 中这样做:

private static MainActivity context;
public void onCreate() {
    context = this;
}

public static getContext() { return context; }

希望语法是正确的,尝试将以上内容合并到您的 mainActivity 中并使用

从您的服务中调用它
MainActivity.getContext().getPhoneNumber()