下面列出了android.telephony.CellSignalStrengthCdma#android.telephony.gsm.GsmCellLocation 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Parses data from PhoneStateListener.LISTEN_CELL_LOCATION.onCellLocationChanged
* http://developer.android.com/reference/android/telephony/cdma/CdmaCellLocation.html
* @param location GsmCellLocation
* @return JSON
*/
public static String gsmCellLocationJSON(GsmCellLocation location){
final Calendar calendar = Calendar.getInstance();
final JSONObject json = new JSONObject();
if(location != null){
try {
json.put("provider", CELLLOCATION_PROVIDER);
json.put("type", GSM);
json.put("timestamp", calendar.getTimeInMillis());
json.put("cid", location.getCid());
json.put("lac", location.getLac());
json.put("psc", location.getPsc());
}
catch(JSONException exc) {
logJSONException(exc);
}
}
return json.toString();
}
private boolean isCellLocationEqual(CellLocation cl1, CellLocation cl2) {
boolean result;
if (cl1 instanceof GsmCellLocation && cl2 instanceof GsmCellLocation) {
GsmCellLocation gsm1 = (GsmCellLocation) cl1;
GsmCellLocation gsm2 = (GsmCellLocation) cl2;
result = (gsm1.getCid() == gsm2.getCid()
&& gsm1.getLac() == gsm2.getLac()
&& gsm1.getPsc() == gsm2.getPsc());
Timber.d("isCellLocationEqual(): GSM equals = %s", result);
} else if (cl1 instanceof CdmaCellLocation && cl2 instanceof CdmaCellLocation) {
CdmaCellLocation cdma1 = (CdmaCellLocation) cl1;
CdmaCellLocation cdma2 = (CdmaCellLocation) cl2;
result = (cdma1.getBaseStationId() == cdma2.getBaseStationId()
&& cdma1.getNetworkId() == cdma2.getNetworkId()
&& cdma1.getSystemId() == cdma2.getSystemId());
Timber.d("isCellLocationEqual(): CDMA equal = %s", result);
} else {
// different types or nulls
result = false;
Timber.d("isCellLocationEqual(): Different types or nulls");
}
return result;
}
@Nullable
static CellLocationSingleData fromCellLocation(@Nullable CellLocation location) {
int cid, lac;
if (location != null) {
if (location instanceof GsmCellLocation) {
cid = ((GsmCellLocation) location).getCid();
lac = ((GsmCellLocation) location).getLac();
}
else if (location instanceof CdmaCellLocation) {
cid = ((CdmaCellLocation) location).getBaseStationId();
lac = ((CdmaCellLocation) location).getSystemId();
} else {
//TODO: More
return null;
}
return new CellLocationSingleData(cid, lac);
}
return null;
}
ay(CellLocation celllocation)
{
a = 0x7fffffff;
b = 0x7fffffff;
c = 0x7fffffff;
d = 0x7fffffff;
e = 0x7fffffff;
if (celllocation != null)
{
if (celllocation instanceof GsmCellLocation)
{
GsmCellLocation gsmcelllocation = (GsmCellLocation)celllocation;
e = gsmcelllocation.getCid();
d = gsmcelllocation.getLac();
} else
if (celllocation instanceof CdmaCellLocation)
{
CdmaCellLocation cdmacelllocation = (CdmaCellLocation)celllocation;
c = cdmacelllocation.getBaseStationId();
b = cdmacelllocation.getNetworkId();
a = cdmacelllocation.getSystemId();
return;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GsmCellLocation cl = (GsmCellLocation) CellLocation.getEmpty();
CellLocation.requestLocationUpdate();
System.out.println("GsmCellLocation " + cl.toString());
MainActivity.context = getApplicationContext();
setContentView(R.layout.activity_dual_sim_card_main);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
clockwise(findViewById(R.id.listView));
//readSims();
}
/**
* Handle a modem event by trying to pull all information. The parameter inc defines if the
* measurement counter should be increased on success.
* @param inc True if the measurement counter should be increased.
*/
private void handle(boolean inc) {
if (telephonyManager == null) return;
final List<android.telephony.CellInfo> cellInfos = telephonyManager.getAllCellInfo();
final List<NeighboringCellInfo> neighbours = telephonyManager.getNeighboringCellInfo();
final CellLocation cellLocation = telephonyManager.getCellLocation();
if (cellInfos == null || cellInfos.isEmpty()) {
if (neighbours == null || neighbours.isEmpty()) {
if (cellLocation == null || !(cellLocation instanceof GsmCellLocation)) return;
}
}
if (inc) measurement.getAndIncrement();
add(cellLocation);
addNeighbours(neighbours);
addCells(cellInfos);
synchronized (recentCells) {
cleanup();
}
}
/**
* Called from native code to request reference location info
*/
private void requestRefLocation() {
TelephonyManager phone = (TelephonyManager)
mContext.getSystemService(Context.TELEPHONY_SERVICE);
final int phoneType = phone.getPhoneType();
if (phoneType == TelephonyManager.PHONE_TYPE_GSM) {
GsmCellLocation gsm_cell = (GsmCellLocation) phone.getCellLocation();
if ((gsm_cell != null) && (phone.getNetworkOperator() != null)
&& (phone.getNetworkOperator().length() > 3)) {
int type;
int mcc = Integer.parseInt(phone.getNetworkOperator().substring(0, 3));
int mnc = Integer.parseInt(phone.getNetworkOperator().substring(3));
int networkType = phone.getNetworkType();
if (networkType == TelephonyManager.NETWORK_TYPE_UMTS
|| networkType == TelephonyManager.NETWORK_TYPE_HSDPA
|| networkType == TelephonyManager.NETWORK_TYPE_HSUPA
|| networkType == TelephonyManager.NETWORK_TYPE_HSPA
|| networkType == TelephonyManager.NETWORK_TYPE_HSPAP) {
type = AGPS_REF_LOCATION_TYPE_UMTS_CELLID;
} else {
type = AGPS_REF_LOCATION_TYPE_GSM_CELLID;
}
native_agps_set_ref_location_cellid(type, mcc, mnc,
gsm_cell.getLac(), gsm_cell.getCid());
} else {
Log.e(TAG, "Error getting cell location info.");
}
} else if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
Log.e(TAG, "CDMA not supported.");
}
}
@Override
public Object onInvoke(Object originObject, Object proxyObject, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
if (!GpsMockManager.getInstance().isMocking()) {
return method.invoke(originObject, args);
}
return new GsmCellLocation();
}
public static GSMInfo getGSMInfo(Context context) {
try {
GSMInfo info = new GSMInfo();
TelephonyManager manager = (TelephonyManager) context.getSystemService("phone");
if (manager != null) {
CellLocation cellLocation = manager.getCellLocation();
int lac = 0;
int cellid = 0;
if (cellLocation != null) {
if (cellLocation instanceof GsmCellLocation) {
lac = ((GsmCellLocation) cellLocation).getLac();
cellid = ((GsmCellLocation) cellLocation).getCid();
} else if (cellLocation instanceof CdmaCellLocation) {
cellid = ((CdmaCellLocation) cellLocation).getNetworkId();
lac = ((CdmaCellLocation) cellLocation).getBaseStationId();
}
}
info.lac = lac;
info.cid = cellid;
}
AMapLocation location = AMapLocationTool.getInstance().location();
if (location != null) {
info.latitude = location.getLatitude();
info.longitude = location.getLongitude();
return info;
}
info.latitude = Double.parseDouble(PreferencesManager.getInstance().getLocationLongitude());
info.longitude = Double.parseDouble(PreferencesManager.getInstance().getLocationLatitude());
return info;
} catch (Exception e) {
LogInfo.log("ZSM++ ==== GSM exception e == " + e.getMessage());
e.printStackTrace();
return null;
}
}
public boolean isValid(GsmCellLocation cell, int mcc, int mnc) {
boolean valid = isValid(cell.getCid(), cell.getLac(), mnc, mcc, cell.getPsc());
if (!valid) {
Timber.w("isValid(): Invalid GsmCellLocation [mcc=%s, mnc =%s, lac=%s, cid=%s, psc=%s]", mcc, mnc, cell.getLac(), cell.getCid(), cell.getPsc());
Timber.w("isValid(): Invalid GsmCellLocation %s", cell);
}
return valid;
}
public boolean isValid(CellLocation cellLocation, int mcc, int mnc) {
if (cellLocation instanceof GsmCellLocation) {
GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
return getGsmValidator().isValid(gsmCellLocation, mcc, mnc);
}
if (cellLocation instanceof CdmaCellLocation) {
CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cellLocation;
return getCdmaValidator().isValid(cdmaCellLocation);
}
throw new UnsupportedOperationException("Cell location type not supported `" + cellLocation.getClass().getName() + "`");
}
public Cell convert(CellLocation cellLocation, int mcc, int mnc, NetworkGroup networkType) {
Cell cell = new Cell();
if (cellLocation instanceof GsmCellLocation) {
GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
if (gsmCellLocation.getCid() <= 65535 && gsmCellLocation.getPsc() == NeighboringCellInfo.UNKNOWN_CID) {
cell.setGsmCellLocation(mcc, mnc, gsmCellLocation.getLac(), gsmCellLocation.getCid(), NetworkGroup.Gsm);
} else {
// fix invalid network types (unfortunately not possible to distinguish between UMTS and LTE)
if (networkType == NetworkGroup.Gsm || networkType == NetworkGroup.Cdma)
networkType = NetworkGroup.Unknown;
int psc = gsmCellLocation.getPsc();
if (psc == NeighboringCellInfo.UNKNOWN_CID || psc == Cell.UNKNOWN_CID) {
psc = Cell.UNKNOWN_CID;
} else if (psc >= 504) {
// only UMTS networks support larger PSC
networkType = NetworkGroup.Wcdma;
}
cell.setGsmCellLocation(mcc, mnc, gsmCellLocation.getLac(), gsmCellLocation.getCid(), psc, networkType);
}
} else if (cellLocation instanceof CdmaCellLocation) {
CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cellLocation;
cell.setCdmaCellLocation(cdmaCellLocation.getSystemId(), cdmaCellLocation.getNetworkId(), cdmaCellLocation.getBaseStationId());
} else {
throw new UnsupportedOperationException("Cell location type not supported `" + cellLocation.getClass().getName() + "`");
}
return cell;
}
public static CellInfo getCellInfo(Context context) {
CellInfo cellInfo = new CellInfo();
TelephonyManager manager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
String netOperator = manager.getNetworkOperator();
// Fix crash when not connected to network (airplane mode, underground,
// etc)
if (netOperator == null || netOperator.length() < 3) {
return cellInfo;
}
/*
* FIXME: Actually check for mobile network status == connected before
* doing this stuff.
*/
if (Phone.getType(context).equals(PHONE_TYPE_CDMA)) {
CdmaCellLocation cdmaLocation = (CdmaCellLocation) manager.getCellLocation();
cellInfo.cid = cdmaLocation.getBaseStationId();
cellInfo.lac = cdmaLocation.getNetworkId();
cellInfo.mnc = cdmaLocation.getSystemId();
cellInfo.mcc = Integer.parseInt(netOperator.substring(0, 3));
cellInfo.radioType = Network.getMobileNetworkType(context);
} else if (Phone.getType(context).equals(PHONE_TYPE_GSM)) {
GsmCellLocation gsmLocation = (GsmCellLocation) manager.getCellLocation();
cellInfo.mcc = Integer.parseInt(netOperator.substring(0, 3));
cellInfo.mnc = Integer.parseInt(netOperator.substring(3));
cellInfo.lac = gsmLocation.getLac();
cellInfo.cid = gsmLocation.getCid();
cellInfo.radioType = Network.getMobileNetworkType(context);
}
return cellInfo;
}
/**
* Add a CellLocation, usually called if the phone switched to a new tower.
* @param icell The new cell location.
*/
public void add(CellLocation icell) {
if (icell == null) {
return;
}
if (!(icell instanceof GsmCellLocation)) {
return;
}
GsmCellLocation cell = (GsmCellLocation) icell;
List<CellInfo> cellInfos = db.query(cell.getCid(), cell.getLac());
if (cellInfos != null && !cellInfos.isEmpty()) {
long measurement = this.measurement.get();
for (CellInfo cellInfo : cellInfos) {
cellInfo.measurement = measurement;
cellInfo.seen = System.currentTimeMillis();
pushRecentCells(cellInfo);
}
} else {
CellInfo ci = new CellInfo();
ci.measurement = this.measurement.get();
ci.lng = 0d;
ci.lat = 0d;
ci.CID = ((GsmCellLocation) icell).getCid();
ci.LAC = ((GsmCellLocation) icell).getLac();
ci.MCC = -1;
ci.MNC = -1;
pushUnusedCells(ci);
}
}
private String getJsonCellPos() throws JSONException {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation location = (GsmCellLocation) tm.getCellLocation();
if (location == null) {
return null;
}
int cid = location.getCid();
int lac = location.getLac();
String netOperator = tm.getNetworkOperator();
int mcc = Integer.valueOf(netOperator.substring(0, 3));
int mnc = Integer.valueOf(netOperator.substring(3, 5));
System.out.println("cid" + cid + ",lac" + lac + ",mcc" + mcc + "" + ",mnc" + mnc);
JSONObject jsonCellPos = new JSONObject();
jsonCellPos.put("version", "1.1.0");
jsonCellPos.put("host", "maps.google.com");
JSONArray array = new JSONArray();
JSONObject json1 = new JSONObject();
json1.put("location_area_code", "" + lac + "");
json1.put("mobile_country_code", "" + mcc + "");
json1.put("mobile_network_code", "" + mnc + "");
json1.put("age", 0);
json1.put("cell_id", "" + cid + "");
array.put(json1);
jsonCellPos.put("cell_towers", array);
return jsonCellPos.toString();
}
public String getJsonCellPos1() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation location = (GsmCellLocation) tm.getCellLocation();
if (location == null) {
return null;
}
int cid = location.getCid();
int lac = location.getLac();
String netOperator = tm.getNetworkOperator();
int mcc = Integer.valueOf(netOperator.substring(0, 3));
int mnc = Integer.valueOf(netOperator.substring(3, 5));
System.out.println("cid" + cid + ",lac" + lac + ",mcc" + mcc + "" + ",mnc" + mnc);
holder = new JSONObject();
JSONArray array = new JSONArray();
JSONObject data = new JSONObject();
try {
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
holder.put("address_language", "zh_CN");
holder.put("request_address", true);
holder.put("radio_type", "gsm");
holder.put("carrier", "HTC");
data.put("cell_id", cid);
data.put("location_area_code", lac);
data.put("mobile_countyr_code", mcc);
data.put("mobile_network_code", mnc);
array.put(data);
holder.put("cell_towers", array);
Log.i(TAG, "JSON��Ϣ��" + holder.toString());
return holder.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Adds or updates a cell tower.
* <p>
* If the cell tower is already in the list, its data is updated; if not, a
* new entry is created.
* <p>
* This method will set the cell's identity data. After this call,
* {@link #isServing()} will return {@code true} for this cell.
* @param networkOperator The network operator, as returned by {@link android.telephony.TelephonyManager#getNetworkOperator()}.
* @param location The {@link android.telephony.GsmCellLocation}, as returned by {@link android.telephony.TelephonyManager#getCellLocation()}.
* @return The new or updated entry.
*/
public CellTowerLte update(String networkOperator, GsmCellLocation location) {
int mcc = CellTower.UNKNOWN;
int mnc = CellTower.UNKNOWN;
if (networkOperator.length() > 3) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
}
CellTowerLte result = null;
CellTowerLte cand = this.get(mcc, mnc, location.getLac(), location.getCid());
if ((cand != null) && CellTower.matches(location.getPsc(), cand.getPci()))
result = cand;
if (result == null) {
cand = this.get(location.getPsc());
if ((cand != null)
&& CellTower.matches(mcc, cand.getMcc())
&& CellTower.matches(mnc, cand.getMnc())
&& CellTower.matches(location.getLac(), cand.getTac())
&& CellTower.matches(location.getCid(), cand.getCi()))
result = cand;
}
if (result == null)
result = new CellTowerLte(mcc, mnc, location.getLac(), location.getCid(), location.getPsc());
if (result.getMcc() == CellTower.UNKNOWN)
result.setMcc(mcc);
if (result.getMnc() == CellTower.UNKNOWN)
result.setMnc(mnc);
if (result.getTac() == CellTower.UNKNOWN)
result.setTac(location.getLac());
if (result.getCi() == CellTower.UNKNOWN)
result.setCi(location.getCid());
if (result.getPci() == CellTower.UNKNOWN)
result.setPci(location.getPsc());
this.put(result.getText(), result);
this.put(result.getAltText(), result);
result.setCellLocation(true);
Log.d(this.getClass().getSimpleName(), String.format("Added GsmCellLocation for %s, %d G", result.getText(), result.getGeneration()));
return result;
}
/**
* Adds or updates a cell tower.
* <p>
* If the cell tower is already in the list, its data is updated; if not, a
* new entry is created.
* <p>
* This method will set the cell's identity data. After this call,
* {@link #isServing()} will return {@code true} for this cell.
* @param networkOperator The network operator, as returned by {@link android.telephony.TelephonyManager#getNetworkOperator()}.
* @param location The {@link android.telephony.GsmCellLocation}, as returned by {@link android.telephony.TelephonyManager#getCellLocation()}.
* @return The new or updated entry.
*/
public CellTowerGsm update(String networkOperator, GsmCellLocation location) {
int mcc = CellTower.UNKNOWN;
int mnc = CellTower.UNKNOWN;
if (networkOperator.length() > 3) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
}
CellTowerGsm result = null;
CellTowerGsm cand = this.get(mcc, mnc, location.getLac(), location.getCid());
if ((cand != null) && CellTower.matches(location.getPsc(), cand.getPsc()))
result = cand;
if (result == null) {
cand = this.get(location.getPsc());
if ((cand != null)
&& CellTower.matches(mcc, cand.getMcc())
&& CellTower.matches(mnc, cand.getMnc())
&& CellTower.matches(location.getLac(), cand.getLac())
&& CellTower.matches(location.getCid(), cand.getCid()))
result = cand;
}
if (result == null)
result = new CellTowerGsm(mcc, mnc, location.getLac(), location.getCid(), location.getPsc());
if (result.getMcc() == CellTower.UNKNOWN)
result.setMcc(mcc);
if (result.getMnc() == CellTower.UNKNOWN)
result.setMnc(mnc);
if (result.getLac() == CellTower.UNKNOWN)
result.setLac(location.getLac());
if (result.getCid() == CellTower.UNKNOWN)
result.setCid(location.getCid());
if (result.getPsc() == CellTower.UNKNOWN)
result.setPsc(location.getPsc());
this.put(result.getText(), result);
this.put(result.getAltText(), result);
if ((result.getText() == null) && (result.getAltText() == null))
Log.d(this.getClass().getSimpleName(), String.format("Added %d G cell with no data from GsmCellLocation", result.getGeneration()));
result.setCellLocation(true);
return result;
}
private String getLAC() {
try {
if(tm.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
GsmCellLocation gLoc = (GsmCellLocation) tm.getCellLocation();
if(gLoc != null) {
return Integer.toString(gLoc.getLac());
}
}
} catch(NullPointerException e) {
Logger.e(LOG, e);
}
return null;
}
private String getCellId() {
try {
String out = "";
if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
final GsmCellLocation gLoc = (GsmCellLocation) tm.getCellLocation();
out = Integer.toString(gLoc.getCid());
} else if(tm.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
final CdmaCellLocation cLoc = (CdmaCellLocation) tm.getCellLocation();
out = Integer.toString(cLoc.getBaseStationId());
}
return out;
} catch(NullPointerException e) {
return null;
}
}
private static CellLocation getDefacedCellLocation(int uid) {
int cid = (Integer) PrivacyManager.getDefacedProp(uid, "CID");
int lac = (Integer) PrivacyManager.getDefacedProp(uid, "LAC");
if (cid > 0 && lac > 0) {
GsmCellLocation cellLocation = new GsmCellLocation();
cellLocation.setLacAndCid(lac, cid);
return cellLocation;
} else
return CellLocation.getEmpty();
}
private String getCellInfoString(SignalStrength signalStrength) {
// Timestamp in system nanoseconds since boot, including time spent in sleep.
long nanoTime = SystemClock.elapsedRealtimeNanos() + mNanosOffset;
// System local time in millis
long currentMillis = (new Date()).getTime();
String message = String.format("%s", currentMillis) + ";"
+ String.format("%s", nanoTime) + ";"
+ String.format("%s", mNanosOffset) + ";";
CellLocation cell = mTelephonyManager.getCellLocation();
if (cell instanceof GsmCellLocation) {
int lac, cid, dbm;
lac = ((GsmCellLocation) cell).getLac();
cid = ((GsmCellLocation) cell).getCid();
String generalNetworkType = networkTypeGeneral(mTelephonyManager.getNetworkType());
// "SignalStrength: mGsmSignalStrength mGsmBitErrorRate mCdmaDbm mCdmaEcio mEvdoDbm
// mEvdoEcio mEvdoSnr mLteSignalStrength mLteRsrp mLteRsrq mLteRssnr mLteCqi
// (isGsm ? "gsm|lte" : "cdma"));
String ssignal = signalStrength.toString();
String[] parts = ssignal.split(" ");
// If the signal is not the right signal in db (a signal below -2) fallback
// Fallbacks will be triggered whenever generalNetworkType changes
if (generalNetworkType.equals("4G")) {
dbm = Integer.parseInt(parts[11]);
if (dbm >= -2) {
if (Integer.parseInt(parts[3]) < -2) {
dbm = Integer.parseInt(parts[3]);
} else {
dbm = signalStrength.getGsmSignalStrength();
}
}
} else if (generalNetworkType.equals("3G")) {
dbm = Integer.parseInt(parts[3]);
if (dbm >= -2) {
if (Integer.parseInt(parts[11]) < -2) {
dbm = Integer.parseInt(parts[11]);
} else {
dbm = signalStrength.getGsmSignalStrength();
}
}
} else {
dbm = signalStrength.getGsmSignalStrength();
if (dbm >= -2) {
if (Integer.parseInt(parts[3]) < -2) {
dbm = Integer.parseInt(parts[3]);
} else {
dbm = Integer.parseInt(parts[11]);
}
}
}
// Returns the numeric name (MCC+MNC) of current registered operator.
String mccMnc = mTelephonyManager.getNetworkOperator();
String mcc, mnc;
if (mccMnc != null && mccMnc.length() >= 4) {
mcc = mccMnc.substring(0, 3);
mnc = mccMnc.substring(3);
} else {
mcc = "NaN";
mnc = "NaN";
}
if (dbm < -2) {
message += mTelephonyManager.getNetworkType() + ";" + cid + ";" + lac + ";" + dbm + ";" + mcc + ";" + mnc;
} else {
message += mTelephonyManager.getNetworkType() + ";" + cid + ";" + lac + ";" + "NaN" + ";" + mcc + ";" + mnc;
}
}
// // Deprecated behavior, not collecting data
// List<NeighboringCellInfo> neighboringCellInfoList = mTelephonyManager.getNeighboringCellInfo();
// for (NeighboringCellInfo neighboringCellInfo : neighboringCellInfoList){
// }
return message;
}
public void onCellLocationChanged(CellLocation location) {
checkForNeighbourCount(location);
compareLac(location);
refreshDevice();
mDevice.setNetID(tm);
mDevice.getNetworkTypeName();
switch (mDevice.getPhoneID()) {
case TelephonyManager.PHONE_TYPE_NONE:
case TelephonyManager.PHONE_TYPE_SIP:
case TelephonyManager.PHONE_TYPE_GSM:
GsmCellLocation gsmCellLocation = (GsmCellLocation) location;
if (gsmCellLocation != null) {
//TODO @EVA where are we sending this setCellInfo data?
//TODO
/*@EVA
Is it a good idea to dump all cells to db because if we spot a known cell
with different lac then this will also be dump to db.
*/
mDevice.setCellInfo(
gsmCellLocation.toString() + // ??
mDevice.getDataActivityTypeShort() + "|" + // No,In,Ou,IO,Do
mDevice.getDataStateShort() + "|" + // Di,Ct,Cd,Su
mDevice.getNetworkTypeName() + "|" // HSPA,LTE etc
);
mDevice.mCell.setLAC(gsmCellLocation.getLac()); // LAC
mDevice.mCell.setCID(gsmCellLocation.getCid()); // CID
if (gsmCellLocation.getPsc() != -1) {
mDevice.mCell.setPSC(gsmCellLocation.getPsc()); // PSC
}
/*
Add cell if gps is not enabled
when gps enabled lat lon will be updated
by function below
*/
}
break;
case TelephonyManager.PHONE_TYPE_CDMA:
CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) location;
if (cdmaCellLocation != null) {
mDevice.setCellInfo(
cdmaCellLocation.toString() + // ??
mDevice.getDataActivityTypeShort() + "|" + // No,In,Ou,IO,Do
mDevice.getDataStateShort() + "|" + // Di,Ct,Cd,Su
mDevice.getNetworkTypeName() + "|" // HSPA,LTE etc
);
mDevice.mCell.setLAC(cdmaCellLocation.getNetworkId()); // NID
mDevice.mCell.setCID(cdmaCellLocation.getBaseStationId()); // BID
mDevice.mCell.setSID(cdmaCellLocation.getSystemId()); // SID
mDevice.mCell.setMNC(cdmaCellLocation.getSystemId()); // MNC <== BUG!??
mDevice.setNetworkName(tm.getNetworkOperatorName()); // ??
}
}
}
/**
* Description: Add entries to the "DBi_measure" DB table
*
* Issues:
* [ ]
*
* Notes: (a)
*
*
* TODO: Remove OLD notes below, once we have new ones relevant to our new table
*
* From "locationinfo":
*
* $ sqlite3.exe -header aimsicd.db 'select * from locationinfo;'
* _id|Lac|CellID|Net|Lat|Lng|Signal|Connection|Timestamp
* 1|10401|6828xxx|10|54.67874392|25.28693531|24|[10401,6828320,126]No|Di|HSPA||2015-01-21 20:45:10
*
* From "cellinfo":
*
* $ sqlite3.exe -header aimsicd.db 'select * from cellinfo;'
* _id|Lac|CellID|Net|Lat|Lng|Signal|Mcc|Mnc|Accuracy|Speed|Direction|NetworkType|MeasurementTaken|OCID_SUBMITTED|Timestamp
* 1|10401|6828xxx|10|54.67874392|25.28693531|24|246|2|69.0|0.0|0.0|HSPA|82964|0|2015-01-21 20:45:10
*
* Issues:
*
*/
public void onLocationChanged(Location loc) {
DeviceApi18.loadCellInfo(tm, mDevice);
if (!mDevice.mCell.isValid()) {
CellLocation cellLocation = tm.getCellLocation();
if (cellLocation != null) {
switch (mDevice.getPhoneID()) {
case TelephonyManager.PHONE_TYPE_NONE:
case TelephonyManager.PHONE_TYPE_SIP:
case TelephonyManager.PHONE_TYPE_GSM:
GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
mDevice.mCell.setCID(gsmCellLocation.getCid()); // CID
mDevice.mCell.setLAC(gsmCellLocation.getLac()); // LAC
mDevice.mCell.setPSC(gsmCellLocation.getPsc()); // PSC
break;
case TelephonyManager.PHONE_TYPE_CDMA:
CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cellLocation;
mDevice.mCell.setCID(cdmaCellLocation.getBaseStationId()); // BSID ??
mDevice.mCell.setLAC(cdmaCellLocation.getNetworkId()); // NID
mDevice.mCell.setSID(cdmaCellLocation.getSystemId()); // SID
mDevice.mCell.setMNC(cdmaCellLocation.getSystemId()); // MNC <== BUG!??
break;
}
}
}
if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0 && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {
mDevice.mCell.setLon(loc.getLongitude()); // gpsd_lon
mDevice.mCell.setLat(loc.getLatitude()); // gpsd_lat
mDevice.mCell.setSpeed(loc.getSpeed()); // speed // TODO: Remove, we're not using it!
mDevice.mCell.setAccuracy(loc.getAccuracy()); // gpsd_accu
mDevice.mCell.setBearing(loc.getBearing()); // -- [deg]?? // TODO: Remove, we're not using it!
mDevice.setLastLocation(loc); //
// Store last known location in preference
SharedPreferences.Editor prefsEditor;
prefsEditor = prefs.edit();
prefsEditor.putString(context.getString(R.string.data_last_lat_lon),
String.valueOf(loc.getLatitude()) + ":" + String.valueOf(loc.getLongitude()));
prefsEditor.apply();
// This only logs a BTS if we have GPS lock
// Test: ~~Is correct behaviour? We should consider logging all cells, even without GPS.~~
//if (mTrackingCell) {
// This also checks that the lac are cid are not in DB before inserting
dbHelper.insertBTS(mDevice.mCell);
//}
}
}
private void setPhoneStateListener(){
if(_returnSignalStrength){
_signalStrengthListener = new SignalStrengthListener();
_signalStrengthListener.setListener(new StrengthChange() {
@Override
public SignalStrength onSignalStrengthChanged(SignalStrength signalStrength) {
if(!Thread.currentThread().isInterrupted()){
sendCallback(PluginResult.Status.OK,
JSONHelper.signalStrengthJSON(signalStrength));
}
return null;
}
});
_telephonyManager.listen(_signalStrengthListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
_phoneStateListener = new PhoneStateListener(){
@Override
public void onCellLocationChanged(CellLocation location){
if(!Thread.currentThread().isInterrupted()){
if(location instanceof CdmaCellLocation){
final CdmaCellLocation cellLocationCdma = (CdmaCellLocation) location;
sendCallback(PluginResult.Status.OK,
JSONHelper.cdmaCellLocationJSON(cellLocationCdma));
}
if(location instanceof GsmCellLocation){
final GsmCellLocation cellLocationGsm = (GsmCellLocation) location;
sendCallback(PluginResult.Status.OK,
JSONHelper.gsmCellLocationJSON(cellLocationGsm));
}
}
}
@Override
public void onCellInfoChanged(List<CellInfo> cellInfo){
if(!Thread.currentThread().isInterrupted()){
processCellInfos(cellInfo);
}
}
};
_telephonyManager.listen(_phoneStateListener, PhoneStateListener.LISTEN_CELL_LOCATION);
}
/**
* 获取手机基站的LAC (Location Aera Code)
*/
public static int getCellLocationLac(Activity activity) {
TelephonyManager telephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation location = (GsmCellLocation) telephonyManager.getCellLocation();
return location.getLac();
}
/**
* 获取手机基站的CID (Cell Tower ID)
*/
public static int getCellLocationCid(Activity activity) {
TelephonyManager telephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation location = (GsmCellLocation) telephonyManager.getCellLocation();
return location.getCid();
}
/**
* 获取手机基站的LAC (Location Aera Code)
*/
public static int getCellLocationLac(Activity activity) {
TelephonyManager telephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation location = (GsmCellLocation) telephonyManager.getCellLocation();
return location.getLac();
}
/**
* 获取手机基站的CID (Cell Tower ID)
*/
public static int getCellLocationCid(Activity activity) {
TelephonyManager telephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation location = (GsmCellLocation) telephonyManager.getCellLocation();
return location.getCid();
}
private ParseResult parse(Location location, CellLocation cellLocation, SignalStrength signalStrength,
NetworkGroup networkType, String operatorCode, String operatorName, List<NeighboringCellInfo> neighboringCells,
long timestamp, int minDistance) {
// if required accuracy was achieved
if (!locationValidator.isValid(location)) {
Timber.d("parse(): Required accuracy not achieved: %s", location.getAccuracy());
return ParseResult.AccuracyNotAchieved;
}
Timber.d("parse(): Required accuracy achieved: %s", location.getAccuracy());
// get last location
getAndSetLastLocation();
// operator name may be unreliable for CDMA
Timber.d("parse(): Operator name = '%s'", operatorName);
// get operator codes
int mcc = Cell.UNKNOWN_CID;
int mnc = Cell.UNKNOWN_CID;
if (cellLocation instanceof GsmCellLocation) {
int[] mccMncPair = MobileUtils.getMccMncPair(operatorCode);
if (mccMncPair != null) {
mcc = mccMncPair[0];
mnc = mccMncPair[1];
} else {
Timber.d("parseLocation(): Network operator unknown: %s", operatorCode);
}
}
// validate cell
if (!cellLocationValidator.isValid(cellLocation, mcc, mnc)) {
Timber.d("parse(): Cell invalid");
return ParseResult.NoNetworkSignal;
}
// create measurement with basic data
Measurement measurement = new Measurement();
measurement.setMeasuredAt(System.currentTimeMillis());
Cell mainCell = cellLocationConverter.convert(cellLocation, mcc, mnc, networkType);
measurement.addCell(mainCell);
// fix time if incorrect
fixMeasurementTimestamp(measurement, location);
// if the same cell check distance condition, otherwise accept
if (lastSavedMeasurement != null && lastSavedLocation != null && !conditionsValidator.isMinDistanceSatisfied(lastSavedLocation, location, minDistance)) {
List<String> lastMeasurementsCellKeys = new ArrayList<>();
for (Cell lastCell : lastSavedMeasurement.getCells()) {
lastMeasurementsCellKeys.add(createCellKey(lastCell));
}
boolean mainCellChanged = !lastMeasurementsCellKeys.contains(createCellKey(mainCell));
if (mainCellChanged) {
Timber.d("parse(): Distance condition not achieved but cell changed");
} else {
Timber.d("parse(): Distance condition not achieved");
return ParseResult.DistanceNotAchieved;
}
}
// check if location has been obtained recently
if (!locationValidator.isUpToDate(timestamp, System.currentTimeMillis())) {
Timber.d("parse(): Location too old");
return ParseResult.LocationTooOld;
}
Timber.d("parse(): Destination and time conditions achieved");
// update measurement with location
updateMeasurementWithLocation(measurement, location);
// update measurement with signal strength
if (signalStrength != null) {
cellSignalConverter.update(mainCell, signalStrength);
}
if (collectNeighboringCells) {
// remove duplicated neighboring cells
removeDuplicatedNeighbors(neighboringCells, mainCell);
// process neighboring cells
for (NeighboringCellInfo neighboringCell : neighboringCells) {
// validate cell
if (cellLocationValidator.isValid(neighboringCell, mcc, mnc)) {
// set values
Cell tempCell = cellLocationConverter.convert(neighboringCell, mcc, mnc, mainCell.getLac(), mainCell.getCid());
// update measurement with signal strength
cellSignalConverter.update(tempCell, neighboringCell.getRssi());
// save
measurement.addCell(tempCell);
Timber.d("parse(): Neighboring cell valid: %s", neighboringCell);
} else {
Timber.d("parse(): Neighboring cell invalid: %s", neighboringCell);
}
}
}
// write to database
Timber.d("parse(): Measurement: %s", measurement);
boolean inserted = MeasurementsDatabase.getInstance(MyApplication.getApplication()).insertMeasurement(measurement);
if (inserted) {
lastSavedLocation = location;
lastSavedMeasurement = measurement;
Timber.d("parse(): Measurement saved");
// broadcast information to main activity
Statistics stats = MeasurementsDatabase.getInstance(MyApplication.getApplication()).getMeasurementsStatistics();
EventBus.getDefault().post(new MeasurementSavedEvent(measurement, stats));
EventBus.getDefault().post(new MeasurementsCollectedEvent(measurement));
Timber.d("parse(): Notification updated and measurement broadcasted");
return ParseResult.Saved;
} else {
return ParseResult.SaveFailed;
}
}