Java 尝试调用虚拟方法';intandroid.telephony.gsm.GsmCellLocation.getCid();关于空对象引用
我面临着这个错误:Java 尝试调用虚拟方法';intandroid.telephony.gsm.GsmCellLocation.getCid();关于空对象引用,java,android,Java,Android,我面临着这个错误: E/AndroidRuntime: FATAL EXCEPTION: main Process: com.kotak.pck.jaimaasaraswati, PID: 8321 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kotak.pck.jaimaasaras
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.kotak.pck.jaimaasaraswati, PID: 8321
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kotak.pck.jaimaasaraswati/com.kotak.pck.jaimaasaraswati.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.telephony.gsm.GsmCellLocation.getCid()' on a null object reference
main活动:
import android.content.Context;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textGsmCellLocation = (TextView) findViewById(R.id.gsmcelllocation);
TextView textCID = (TextView) findViewById(R.id.cid);
TextView textLAC = (TextView) findViewById(R.id.lac);
//retrieve a reference to an instance of TelephonyManager
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = new GsmCellLocation();
cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();
textGsmCellLocation.setText("GSM Cell Location: " + cellLocation.toString());
textCID.setText("GSM Cell id: " + String.valueOf(cid));
textLAC.setText("GSM Location area code: " + String.valueOf(lac));
}
}
谢谢您的帮助。根据,getCellLocation()
将返回
设备的当前位置,如果不可用,则为空
它还需要以下权限
Manifest.permission.ACCESS_FINE_LOCATION
另外,可能是由于LTE造成了问题。根据文件
如果设备中只有一个无线电且该无线电具有LTE连接,则此方法将返回null
此外,您需要使用
getAllCellInfo()
,因为另一个在API级别26中已被弃用。显然telephonyManager.getCellLocation()
正在返回null
。那么我应该如何获取单元格信息呢?还有别的办法吗?或者我犯了一些错误,因为它返回null?如果当前位置不可用,getCellLocation
方法返回null
。这在3年前肯定很有用,但现在有点太晚了……)