从后台服务检索手机信号塔信息

时间:2019-03-14 05:54:35

标签: android

  1. 我一直在尝试使用TelephonyManager来获取手机信号塔 位置,当 I时,电话管理器对象返回 null 关闭我的应用。
  2. 关闭应用程序后,当后台服务运行时,cellInformation对象为null。

代码为(每10分钟调用一次服务以查找位置):

public class LocationDetector extends Service {

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("Location", "Location detector started");
    getCellDetails();

    return START_STICKY;
}

private void getCellDetails() {
    TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    try {
        List<CellInfo> cellInformation = tm.getAllCellInfo();
        // get the list of the cell location for the top 3 in the list
        for (int iCounter = 0; iCounter < 3; iCounter++) {
            CellInfo info = cellInformation.get(iCounter);

            if (info instanceof CellInfoGsm) {
                CellIdentityGsm identity = ((CellInfoGsm) info).getCellIdentity();
                Log.i("Location ", "Cell id: " + identity.getCid() + " Cell Location code: " + identity.getLac() + "Cell Operator: ");

            } else if (info instanceof CellInfoWcdma) {
                CellIdentityWcdma identity = ((CellInfoWcdma) info).getCellIdentity();
                Log.i("Location ", "Cell id: " + identity.getCid() + " Cell Location code: " + identity.getLac() + " MCC:" + identity.getMcc() + " MNC:" + identity.getMnc());

            } else if (info instanceof CellInfoLte) {
                CellIdentityLte identity = ((CellInfoLte) info).getCellIdentity();
                Log.i("Location ", "Cell id: " + identity.getCi() + " Cell Location code: " + identity.getTac() + "Cell Operator: " + identity.getMobileNetworkOperator());
            }
        }
    } catch (NullPointerException e) {
        Log.e("Location", "Telephony object is null" + e.toString());
    } catch (Exception e) {
        Log.e("Location", "Error: " + e.toString());
    }
}

}

权限如下:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

运行时权限:

@TargetApi(23)
    private void askPermissions() {
        String[] permissions = {
                "android.permission.WRITE_EXTERNAL_STORAGE",
                "android.permission.ACCESS_FINE_LOCATION",
                "android.permission.ACCESS_COARSE_LOCATION"
        };
        int requestCode = 200;
        requestPermissions(permissions, requestCode);
    }

2 个答案:

答案 0 :(得分:0)

您需要在API级别26或更高级别(Android 8.0或更高版本)中启用Location Services,才能从后台访问单元格信息。

答案 1 :(得分:0)

我遇到了类似的问题。我发现的解决方案只是确保应用程序具有在后台获取位置的权限。 “android.permission.ACCESS_BACKGROUND_LOCATION” 当用户允许位置为“一直允许”时,我会填充 cellinfo 对象。 未经许可,前台有数据,后台返回NULL。