我遇到了这个错误:
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
MainActivity:
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));
}
}
感谢您的帮助。
答案 0 :(得分:1)
根据documentation,getCellLocation()
将返回
设备的当前位置;如果不可用,则为null。
它还需要以下权限。
Manifest.permission.ACCESS_FINE_LOCATION
此外,可能是由于LTE引起的问题。根据文档,
如果设备中只有一个无线电并且该无线电具有LTE连接,则此方法将返回null。
此外,您需要使用getAllCellInfo()
,因为API级别26中不推荐使用另一个。