下面列出了android.app.usage.NetworkStatsManager#android.telephony.TelephonyManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public JSONObject dumpInfo (Context context) {
JSONObject properties = new JSONObject ();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
properties.put("phone_number", telephonyManager.getLine1Number());
properties.put("mobile_operator", telephonyManager.getNetworkOperatorName());
properties.put("device_model", Build.MODEL);
properties.put("android_version", Build.VERSION.RELEASE);
properties.put("android_version_codename", Build.VERSION.RELEASE);
} catch (Exception e) {
Log.e ("Get Information Error", e.getMessage());
}
return properties;
}
private void initializeMapboxTelemetry() {
Context mockedContext = mock(Context.class, RETURNS_DEEP_STUBS);
TelephonyManager mockedTelephonyManager = mock(TelephonyManager.class, RETURNS_DEEP_STUBS);
when(mockedContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mockedTelephonyManager);
WindowManager mockedWindowManager = mock(WindowManager.class, RETURNS_DEEP_STUBS);
when(mockedContext.getSystemService(Context.WINDOW_SERVICE)).thenReturn(mockedWindowManager);
AlarmManager mockedAlarmManager = mock(AlarmManager.class, RETURNS_DEEP_STUBS);
when(mockedContext.getSystemService(Context.ALARM_SERVICE)).thenReturn(mockedAlarmManager);
MapboxTelemetry.applicationContext = mockedContext;
String aValidAccessToken = "validAccessToken";
String aValidUserAgent = "MapboxTelemetryAndroid/";
EventsQueue mockedEventsQueue = mock(EventsQueue.class);
TelemetryClient mockedTelemetryClient = mock(TelemetryClient.class);
Callback mockedHttpCallback = mock(Callback.class);
SchedulerFlusher mockedSchedulerFlusher = mock(SchedulerFlusher.class);
Clock mockedClock = mock(Clock.class);
TelemetryEnabler telemetryEnabler = new TelemetryEnabler(false);
new MapboxTelemetry(mockedContext, aValidAccessToken, aValidUserAgent,
mockedEventsQueue, mockedTelemetryClient, mockedHttpCallback, mockedSchedulerFlusher, mockedClock,
telemetryEnabler, mock(ExecutorService.class));
}
@Override
public void show() {
if (!isEnabled() || (mCallState != TelephonyManager.CALL_STATE_IDLE)) return;
// If we've been told to hide, we'll do it.
if (null != mLastVolumeChange && mLastVolumeChange.mStreamType ==
STREAM_MUSIC && hideFullscreen && fullscreen) {
LOGI("VolumePanel", "Not showing panel, hiding for fullscreen media.");
return;
}
// Only show the panel if the screen is on.
if (null != pWindowManager && pWindowManager.isScreenOn()) {
if (null != mMediaProviderDelegate)
mMediaProviderDelegate.acquire(getWindowWidth(), getWindowHeight());
super.show();
// NOTE: snapshots can be taken here, each time the panel is shown.
// snapshot();
}
}
public boolean isNetworkRoaming() {
ConnectivityManager connectivity =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Log.w(Constants.TAG, "couldn't get connectivity manager");
return false;
}
NetworkInfo info = connectivity.getActiveNetworkInfo();
boolean isMobile = (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE);
TelephonyManager tm = (TelephonyManager) mContext
.getSystemService(Context.TELEPHONY_SERVICE);
if (null == tm) {
Log.w(Constants.TAG, "couldn't get telephony manager");
return false;
}
boolean isRoaming = isMobile && tm.isNetworkRoaming();
if (Constants.LOGVV && isRoaming) {
Log.v(Constants.TAG, "network is roaming");
}
return isRoaming;
}
@Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
//receive_incoming_call
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("receive_incoming_call").putExtra("state",1));
}
//EXTRA_STATE_OFFHOOK
if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("EXTRA_STATE_OFFHOOK").putExtra("state",3));
}
//rejected_incoming_call
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("rejected_incoming_call").putExtra("state",2));
}
}
catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onCreate() {
super.onCreate();
mTelephonyManager = ((TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE));
alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
try {
mWifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "SCAN_LOCK");
if (!mWifiLock.isHeld()) {
mWifiLock.acquire();
}
} catch (UnsupportedOperationException uoe) {
appendLog(getBaseContext(), TAG,
"Unable to acquire wifi lock.", uoe);
}
registerReceiver(mReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
public DeviceUuidFactory(Context context) {
if (uuid == null) {
synchronized (DeviceUuidFactory.class) {
if (uuid == null) {
{
final String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
try {
// 刷机
// 都可以被hook
if (!"9774d56d682e549c".equals(androidId)) {
uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
} else {
final String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
uuid = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// Write the value out to the prefs file
}
}
}
}
}
private void w() {
TelephonyManager telephonyManager = (TelephonyManager) hn.a().c().getSystemService("phone");
if (telephonyManager != null) {
String deviceId = telephonyManager.getDeviceId();
if (deviceId != null && deviceId.trim().length() > 0) {
try {
byte[] f = jn.f(deviceId);
if (f == null || f.length != 20) {
ib.a(6, a, "sha1 is not " + 20 + " bytes long: " + Arrays.toString(f));
} else {
this.i = f;
}
} catch (Exception e) {
ib.a(6, a, "Exception in generateHashedImei()");
}
}
}
}
/**
* 获取手机网络运营商类型
*
* @param context
* @return
*/
public static String getPhoneISP(Context context) {
if (context == null) {
return "";
}
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String teleCompany = "";
String np = manager.getNetworkOperator();
if (np != null) {
if (np.equals(CMCC_ISP) || np.equals(CMCC2_ISP)) {
teleCompany = "中国移动";
} else if (np.startsWith(CU_ISP)) {
teleCompany = "中国联通";
} else if (np.startsWith(CT_ISP)) {
teleCompany = "中国电信";
}
}
return teleCompany;
}
private List<IIconListAdapterItem> getSubItemList(final SubType subType) {
List<IIconListAdapterItem> list = new ArrayList<>();
if (subType == SubType.VOICE) {
list.add(new SubListItem(null));
final TelecomManager telecomManager =
(TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
final TelephonyManager telephonyManager =
(TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
final Iterator<PhoneAccountHandle> phoneAccounts =
telecomManager.getCallCapablePhoneAccounts().listIterator();
while (phoneAccounts.hasNext()) {
final PhoneAccount phoneAccount =
telecomManager.getPhoneAccount(phoneAccounts.next());
int subId = getSubIdForPhoneAccount(telephonyManager, phoneAccount);
if (subId != -1) {
list.add(new SubListItem(mSubMgr.getActiveSubscriptionInfo(subId)));
}
}
} else {
for (SubscriptionInfo si : mSubMgr.getActiveSubscriptionInfoList())
if (si != null)
list.add(new SubListItem(si));
}
return list;
}
public static void cancelCall(Context context) {
try {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
Object telephonyService = m.invoke(tm); // Get the internal ITelephony object
c = Class.forName(telephonyService.getClass().getName()); // Get its class
m = c.getDeclaredMethod("endCall"); // Get the "endCall()" method
m.setAccessible(true); // Make it accessible
m.invoke(telephonyService); // invoke endCall()
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* @param context
* @param
* @return
* @description 判断网络是否是漫游
* @date 2014-12-5
* @author 史永飞
*/
public boolean isNetworkRoaming(Context context) {
if (conManager != null) {
NetworkInfo info = conManager.getActiveNetworkInfo();
if (info != null
&& info.getType() == ConnectivityManager.TYPE_MOBILE) {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
if (tm != null && tm.isNetworkRoaming()) {
Log.d("Tag", "network is roaming");
return true;
} else {
Log.d("Tag", "network is not roaming");
}
}
}
return false;
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE: // 挂机状态
if(phoneState){
play(currentMusic);
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK: //通话状态
case TelephonyManager.CALL_STATE_RINGING: //响铃状态
if(musicBinder.isPlaying()){ //判断歌曲是否在播放
musicBinder.stopPlay();
phoneState = true;
}
break;
default:
break;
}
}
public static boolean hasSimCard(Context context) {
boolean result = true;
try {
TelephonyManager telMgr = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
int simState = telMgr.getSimState();
switch (simState) {
case TelephonyManager.SIM_STATE_ABSENT:
result = false;
break;
case TelephonyManager.SIM_STATE_UNKNOWN:
result = false;
break;
default:
break;
}
} catch (Exception e) {
//ignore
}
return result;
}
public boolean isNetworkRoaming() {
ConnectivityManager connectivity =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Log.w(Constants.TAG, "couldn't get connectivity manager");
return false;
}
NetworkInfo info = connectivity.getActiveNetworkInfo();
boolean isMobile = (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE);
TelephonyManager tm = (TelephonyManager) mContext
.getSystemService(Context.TELEPHONY_SERVICE);
if (null == tm) {
Log.w(Constants.TAG, "couldn't get telephony manager");
return false;
}
boolean isRoaming = isMobile && tm.isNetworkRoaming();
if (Constants.LOGVV && isRoaming) {
Log.v(Constants.TAG, "network is roaming");
}
return isRoaming;
}
public int getCountryZipCode() {
String CountryID = "";
String CountryZipCode = "";
int code = 0;
TelephonyManager manager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
//getNetworkCountryIso
CountryID = manager.getSimCountryIso().toUpperCase();
String[] rl = this.getResources().getStringArray(R.array.spinnerCountryCodes);
for (int i = 0; i < rl.length; i++) {
String[] g = rl[i].split(",");
if (g[1].trim().equals(CountryID.trim())) {
CountryZipCode = g[0];
code = i;
break;
}
}
return code;
}
public static String[] getCarrierInfo(){
TelephonyManager tm=(TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
if(Build.VERSION.SDK_INT>=24){
tm=tm.createForSubscriptionId(SubscriptionManager.getDefaultDataSubscriptionId());
}
if(!TextUtils.isEmpty(tm.getNetworkOperatorName())){
String mnc="", mcc="";
String carrierID=tm.getNetworkOperator();
if(carrierID!=null && carrierID.length()>3){
mcc=carrierID.substring(0, 3);
mnc=carrierID.substring(3);
}
return new String[]{tm.getNetworkOperatorName(), tm.getNetworkCountryIso().toUpperCase(), mcc, mnc};
}
return null;
}
/**
* 获取手机网络运营商类型
*
* @param context
* @return
*/
public static String getPhoneISP(Context context) {
if (context == null) {
return "";
}
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String teleCompany = "";
String np = manager.getNetworkOperator();
if (np != null) {
if (np.equals(CMCC_ISP) || np.equals(CMCC2_ISP)) {
teleCompany = "中国移动";
} else if (np.startsWith(CU_ISP)) {
teleCompany = "中国联通";
} else if (np.startsWith(CT_ISP)) {
teleCompany = "中国电信";
}
}
return teleCompany;
}
private static Cell.CellType getCellType(int networkType) {
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
return Cell.CellType.GSM;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return Cell.CellType.UMTS;
case TelephonyManager.NETWORK_TYPE_LTE:
return Cell.CellType.LTE;
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_IDEN:
return Cell.CellType.CDMA;
}
return null;
}
/**
* 判断移动数据是否打开
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean getDataEnabled() {
try {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
Method getMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("getDataEnabled");
if (null != getMobileDataEnabledMethod) {
return (boolean) getMobileDataEnabledMethod.invoke(tm);
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 获取 IMEI
*/
public static String getIMEI(Context context) {
try {
if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
TelephonyManager telephonyMgr =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyMgr != null) {
return telephonyMgr.getDeviceId();
}
}
} catch (Throwable ignore) {
ExceptionUtil.exceptionThrow(ignore);
}
return Constants.EMPTY;
}
@Override
public void onReceive(Context context, Intent intent) {
if (!TalkBackService.isServiceActive()) {
LogUtils.w(TAG, "Service not initialized during " + "broadcast.");
return;
}
int oldState = lastCallState;
int newState;
final String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
newState = TelephonyManager.CALL_STATE_IDLE;
} else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
newState = TelephonyManager.CALL_STATE_OFFHOOK;
} else if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
newState = TelephonyManager.CALL_STATE_RINGING;
} else {
return;
}
if (newState != oldState) {
LogUtils.v(
TAG,
"Call state changed: %s -> %s",
callStateToString(lastCallState),
callStateToString(newState));
lastCallState = newState;
for (CallStateChangedListener listener : callStateChangedListeners) {
listener.onCallStateChanged(oldState, newState);
}
}
}
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;
}
/**
* Return the country by sim card.
*
* @return the country
*/
public static String getCountryBySim() {
TelephonyManager manager = (TelephonyManager) Utils.getApp().getSystemService(Context.TELEPHONY_SERVICE);
if (manager != null) {
return manager.getSimCountryIso().toUpperCase();
}
return "";
}
/**
* @return The ISO country code for the user's home country, or an empty string if not
* available or privacy-enabled.
*/
String getHomeCountry(Context context) {
if (ContextualSearchFieldTrial.isSendHomeCountryDisabled()) return "";
TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager == null) return "";
String simCountryIso = telephonyManager.getSimCountryIso();
if (TextUtils.isEmpty(simCountryIso)) return "";
return simCountryIso;
}
public String getDeviceCode() {
String deviceId = ((TelephonyManager) getOnlyContext().getSystemService("phone")).getDeviceId();
if ("000000000000000".equals(deviceId) || deviceId == null) {
return "ThisIsaEmulator";
}
return deviceId;
}
public boolean hasEarpiece() {
if(USE_CONNECTION_SERVICE){
if(systemCallConnection!=null && systemCallConnection.getCallAudioState()!=null){
int routeMask=systemCallConnection.getCallAudioState().getSupportedRouteMask();
return (routeMask & (CallAudioState.ROUTE_EARPIECE | CallAudioState.ROUTE_WIRED_HEADSET))!=0;
}
}
if(((TelephonyManager)getSystemService(TELEPHONY_SERVICE)).getPhoneType()!=TelephonyManager.PHONE_TYPE_NONE)
return true;
if (mHasEarpiece != null) {
return mHasEarpiece;
}
// not calculated yet, do it now
try {
AudioManager am=(AudioManager)getSystemService(AUDIO_SERVICE);
Method method = AudioManager.class.getMethod("getDevicesForStream", Integer.TYPE);
Field field = AudioManager.class.getField("DEVICE_OUT_EARPIECE");
int earpieceFlag = field.getInt(null);
int bitmaskResult = (int) method.invoke(am, AudioManager.STREAM_VOICE_CALL);
// check if masked by the earpiece flag
if ((bitmaskResult & earpieceFlag) == earpieceFlag) {
mHasEarpiece = Boolean.TRUE;
} else {
mHasEarpiece = Boolean.FALSE;
}
} catch (Throwable error) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("Error while checking earpiece! ", error);
}
mHasEarpiece = Boolean.TRUE;
}
return mHasEarpiece;
}
@Override
public void onCallStateChanged(int state, final String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
// state is not CALL_STATE_RINGING
if(TelephonyManager.CALL_STATE_RINGING != state) {
return;
}
// check whether in blacklist
BlacklistDao dao = new BlacklistDao(BlacklistInterceptService.this);
BlacklistBean bean = dao.selectByPhone(incomingNumber);
if(null == bean) {// not in blacklist
return;
}
// check mode whether has call
int mode = bean.getMode();
if((BlacklistDb.MODE_CALL & mode) != 0) {// has call mode, need intercept
// register call database data change listener
getContentResolver().registerContentObserver(Uri.parse(URI_CALL),
true, new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
// unregister listener, just delete once
getContentResolver().unregisterContentObserver(this);
// delete the current call record
int count = CallUtils.deleteLatestCall(BlacklistInterceptService.this, incomingNumber);
System.out.println("delete count = " + count);
}
});
if (CallUtils.endCall()) {
System.out.println("call from " + incomingNumber + " was intercepted");
} else {
System.out.println("call from " + incomingNumber + " was failed to intercepted");
}
}
}
public static String h(Context context) {
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
if (telephonyManager == null) {
return "";
}
return telephonyManager.getNetworkOperatorName();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/** Returns "GSM", "CDMA". */
private String getTelephonyPhoneType() {
switch (telephonyManager.getPhoneType()) {
case TelephonyManager.PHONE_TYPE_CDMA:
return "CDMA";
case TelephonyManager.PHONE_TYPE_GSM:
return "GSM";
case TelephonyManager.PHONE_TYPE_NONE:
return "None";
}
return "Unknown";
}