getSystemService方法的调用

本文介绍了一种解决Android应用程序中获取手机信息时遇到的进程关闭问题的方法。通过为`BasicInfo`类添加一个接收`Context`参数的构造函数,并在获取电话号码的方法中使用传入的`Context`,成功解决了此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  在android 获取手机信息的时候用到这样一段代码:

 

 

public class BasicInfo {

 

 

public String getPhoneNumber()

{

// 获取手机号 MSISDN,很可能为空

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

StringBuffer inf = new StringBuffer();

switch(tm.getSimState()){ //getSimState()取得sim的状态  有下面6中状态  

        case TelephonyManager.SIM_STATE_ABSENT :inf.append("无卡");return inf.toString();   

        case TelephonyManager.SIM_STATE_UNKNOWN :inf.append("未知状态");return inf.toString();  

        case TelephonyManager.SIM_STATE_NETWORK_LOCKED :inf.append("需要NetworkPIN解锁");return inf.toString();  

        case TelephonyManager.SIM_STATE_PIN_REQUIRED :inf.append("需要PIN解锁");return inf.toString();  

        case TelephonyManager.SIM_STATE_PUK_REQUIRED :inf.append("需要PUK解锁");return inf.toString();  

        case TelephonyManager.SIM_STATE_READY :break;  

        }

 

String phoneNumber = tm.getLine1Number();

return phoneNumber;

}

 

 

......

 

}

 

在另外一个activity类里面调用的时候 总是出现进程关闭 无法获取手机信息。

 

后来发现

getSystemService这个方法基于context,只有存在TextView控件的窗体中这个方法才会被激活~

 

于是:

1.

给BasicInfo 添加一个带参数Context的构造函数:

public BasicInfo (Context context)

{

this.context = context;

}

 

2.

getPhoneNumber()函数里面改成:

context.getSystemService(Context.TELEPHONY_SERVIC);

 

3.

在调用类里面 BasicInfo bi = new BasicInfo(this);

bi.getPhoneNumber();

 

问题解决。。。

`getSystemService` 是 Android 应用程序中的一个方法,它允许你通过传入特定的服务标识符从当前运行的应用上下文 (`Context`) 中获取系统级别的服务。然而,由于静态方法不具备访问实例化成员(如 `Context`)的能力,所以在静态方法中直接使用 `getSystemService` 是不允许的,因为它需要一个关联的 `Context` 实例来工作。 如果你想在静态方法中使用类似的功能,你需要确保有一个可以提供 `Context` 的地方。常见的做法是创建一个单例或者持有全局 `Context` 的静态变量。以下是一个例子,展示了在一个单例类中使用 `getSystemService`: ```java public class AppSingleton { private static final AppSingleton INSTANCE = new AppSingleton(); private AppSingleton() {} public static synchronized AppSingleton getInstance() { return INSTANCE; } public Context getContext() { // 获取应用程序的实际上下文 return YourApplicationContext.getInstance(); } // 现在可以在静态方法中这样使用 public static boolean isBluetoothEnabled() { Context appContext = getInstance().getContext(); BluetoothManager bluetoothManager = (BluetoothManager) appContext.getSystemService(Context.BLUETOOTH_SERVICE); return bluetoothManager.isDiscovering(); } } // 在静态方法调用: boolean isBluetoothDiscovering = AppSingleton.isBluetoothEnabled(); ``` 请注意,这只是一个示例,实际应用可能需要根据你们的应用结构和设计进行调整。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值