Lấy Cell Location (Vị trí trạm phát) trong Android
Hướng dẫn sử dụng TelephonyManager.getCellLocation() để lấy vị trí đại lược dựa trên trạm phát (cell tower). Lưu ý: Phương thức này deprecated từ API 29 (Android 10), thay thế bằng getAllCellInfo().
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Bước 3: Code logic (java/MainActivity.java)
package com.example.myapplication;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.telephony.cdma.CdmaCellLocation;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 100;
TextView textView;
TelephonyManager telephonyManager;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (!hasPermissions()) {
requestPermissions();
} else {
showCellLocation();
}
}
private boolean hasPermissions() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSION_REQUEST_CODE);
}
@RequiresApi(api = Build.VERSION_CODES.P)
private void showCellLocation() {
// DEPRECATED API 29+
CellLocation location = telephonyManager.getCellLocation();
StringBuilder sb = new StringBuilder();
if (location != null) {
sb.append("CellLocation class: ").append(location.getClass().getSimpleName()).append("\n\n");
if (location instanceof GsmCellLocation) {
GsmCellLocation gsm = (GsmCellLocation) location;
sb.append("GSM Cell Info:\n");
sb.append(" CID (Cell ID): ").append(gsm.getCid()).append("\n");
sb.append(" LAC (Location Area Code): ").append(gsm.getLac()).append("\n");
sb.append(" PSC (Primary Scrambling Code): ").append(gsm.getPsc()).append("\n");
} else if (location instanceof CdmaCellLocation) {
CdmaCellLocation cdma = (CdmaCellLocation) location;
sb.append("CDMA Cell Info:\n");
sb.append(" Base Station ID: ").append(cdma.getBaseStationId()).append("\n");
sb.append(" Network ID: ").append(cdma.getNetworkId()).append("\n");
sb.append(" System ID: ").append(cdma.getSystemId()).append("\n");
sb.append(" Longitude: ").append(cdma.getBaseStationLongitude()).append("\n");
sb.append(" Latitude: ").append(cdma.getBaseStationLatitude()).append("\n");
}
} else {
sb.append("CellLocation is null (cần quyền hoặc không có dịch vụ)");
}
sb.append("\n\n⚠️ DEPRECATED từ Android 10 (API 29).");
sb.append("\nDùng TelephonyManager.getAllCellInfo() hoặc CellInfo API thay thế.");
textView.setText(sb.toString());
}
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE && hasPermissions()) {
showCellLocation();
}
}
}
Bước 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application ...>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
⚠️ Quan trọng: Thay thế bằng CellInfo API (API 17+)
// Cách hiện đại (API 17+)
List<CellInfo> cellInfos = telephonyManager.getAllCellInfo();
if (cellInfos != null) {
for (CellInfo info : cellInfos) {
if (info instanceof CellInfoGsm) {
CellIdentityGsm id = ((CellInfoGsm) info).getCellIdentity();
// id.getCid(), id.getLac(), id.getMcc(), id.getMnc()...
} else if (info instanceof CellInfoLte) {
CellIdentityLte id = ((CellInfoLte) info).getCellIdentity();
// id.getCi(), id.getTac(), id.getPci()...
}
// Signal strength: info.getCellSignalStrength().getDbm()
}
}
Chạy ứng dụng
Cấp quyền → TextView hiển thị Cell ID, LAC (GSM) hoặc Base Station ID (CDMA). Trên Android 10+ thường trả về null.
