[Completed] Trouble with string encode after decompile APK file - XDA Assist

Hello,
I have a trouble with a string text encode after decompile an APK file.
I used APK Tool decompile. The origin file http_//file.9app.info/files/tuan/tuan2india/9-apps.apk
The code was encoded here:
Code:
public class API
extends Activity
{
public static String a = "081b11458016006d513b0290cc7be0b39c28626ea506b9ed291b125114f2a38369a42e77a066a7789e5883ed47113fc3";
public static String b = "081b11458016006d513b0290cc7be0b36f01584bcfccde8bd9e2bd628ca804e7056b175ad6a1fa1bf3cf31d8a28b94e9";
public static String c = "081b11458016006d513b0290cc7be0b36f01584bcfccde8bd9e2bd628ca804e7056b175ad6a1fa1bf3cf31d8a28b94e9";
public static JSONObject d = new JSONObject();
public static String e = "";
private static int h = 0;
private boolean f = false;
private ProgressDialog g;
private JSONObject a(JSONObject paramJSONObject)
{
int i = 0;
Iterator localIterator = paramJSONObject.keys();
int[] arrayOfInt = new int[paramJSONObject.length()];
int j = 0;
JSONObject localJSONObject1;
int m;
if (!localIterator.hasNext())
{
Arrays.sort(arrayOfInt);
localJSONObject1 = new JSONObject();
m = arrayOfInt.length;
}
for (;;)
{
if (i >= m)
{
return localJSONObject1;
int k = j + 1;
arrayOfInt[j] = Integer.parseInt(((String)localIterator.next()).toString());
j = k;
break;
}
String str1 = Integer.toString(arrayOfInt[i]);
try
{
JSONObject localJSONObject2 = (JSONObject)paramJSONObject.get(str1);
if (((paramJSONObject.get(str1) instanceof JSONObject)) && (!a(localJSONObject2.get("package").toString())))
{
String str2 = localJSONObject2.get("package").toString();
if (!getApplicationContext().getSharedPreferences("listpacks", 0).getBoolean(str2, false)) {
if (localJSONObject2.get("type").toString().equals("1"))
{
if (!this.f)
{
this.f = true;
d = localJSONObject2;
}
}
else
{
e = e + localJSONObject2.get("package").toString() + "|";
localJSONObject1.put(str1, localJSONObject2);
}
}
}
}
catch (JSONException localJSONException)
{
localJSONException.printStackTrace();
}
i++;
}
}
Anybody can help me decode 3 text string a,b,c please?

Hello,
Try posting your question in the forum linked below.
http://forum.xda-developers.com/android/help
The experts there may be able to help. Good luck.

Hello,
I'm newbie so I don't know where to post right. Thank you for your advice!

Related

source code of StartMenuRebuilder (small stuff for A.I.)

Finally,I have successfully get my PC online,before today only one computer - my friend's PC can online,the lessor of house only provided a port and bind MAC address.
Code:
/*
Author:xiaojin1985[小金]
Version:1.2
Updates:
+ Directories can be removed now.
*/
// StartMenuRebuilder.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <commctrl.h>
BOOL IsFileExist(LPCTSTR lpFileName){
WIN32_FIND_DATA m_data;
HANDLE hFile;
BOOL bFileFound = FALSE;
hFile=FindFirstFile(lpFileName,&m_data);
if(hFile==INVALID_HANDLE_VALUE){
bFileFound = FALSE;
}else{
bFileFound = TRUE;
}
FindClose(hFile);
return bFileFound;
}
BOOL SearchDir(PCTSTR ptzSrc)
{
WIN32_FIND_DATA fd;
TCHAR tzSrc[MAX_PATH];
TCHAR tzFind[MAX_PATH];
wsprintf(tzFind, TEXT("%s\\*"), ptzSrc);
HANDLE hFind = FindFirstFile(tzFind, &fd);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
if (fd.cFileName[0] != '.')
{
wsprintf(tzSrc, TEXT("%s\\%s"), ptzSrc, fd.cFileName);
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
SearchDir(tzSrc);
}
else
{
//_debug(L"%s",tzSrc);
SetFileAttributes(tzSrc,FILE_ATTRIBUTE_NORMAL);
DeleteFile(tzSrc);
}
}
}
while (FindNextFile(hFind, &fd));
FindClose(hFind);
RemoveDirectory(ptzSrc);
}
return TRUE;
}
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR szPath[MAX_PATH];
wchar_t szFileExec[256] = _T("");
wchar_t WorkPath[255];//工作路径
int i;
GetModuleFileName(NULL,WorkPath,255);
i = wcslen(WorkPath)-1;
for(;WorkPath[i]!='\\';i--);
WorkPath[i+1]='\0';
wsprintf(szFileExec,TEXT("%sStartMenu.cab"),WorkPath);
if(IsFileExist(szFileExec)){
SHGetSpecialFolderPath(NULL, szPath, CSIDL_STARTMENU, FALSE);
SearchDir(szPath);
//If you want run it independence,plz remove the comment lines.
/*
PROCESS_INFORMATION pi;
STARTUPINFO si;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
wchar_t szFileArgv[256] = _T("");
wsprintf(szFileArgv,TEXT("/nodelete /noui /silent %s"),szFileExec);
//_debug(L"%s",szFileArgv);
CreateProcess(TEXT("wceload.exe"),szFileArgv,0,0,0,0,0,0,&si,&pi);
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);*/
}else{
MessageBox(NULL,L"StartMenu.cab NOT FOUND!",L"Rebuilder by xiaojin",MB_OK);
}
return 0;
}
ha ha ha ha ha ha
source code of StartMenuRebuilder (small stuff for A.I.)
You're talking about something?

[Q] Stuck very badly

Code:
private static string Post(string url, string data)
{
System.Net.WebRequest request1 = WebRequest.Create(url);
request1.Method = "POST";
request1.ContentType = "application/json";
byte[] byteData = Encoding.UTF8.GetBytes(data);
request1.ContentLength = byteData.Length;
using (Stream s = request1.GetRequestStream())
{
s.Write(byteData, 0, byteData.Length);
s.Close();
}
string replyData;
using (HttpWebResponse response = (HttpWebResponse)request1.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
replyData = reader.ReadToEnd();
}
}
}
I am receiving an error on [request1.ContentLength] and using (Stream s = request1.GetRequestStream())
pls i really need assistance on this

[Q] HELP! HELP!why my backround app can't work!

i has decompile screen_capture_1.03 and i saw these code:
hookThread = new BackgroundWorker();
hookThread.DoWork += delegate (object o, DoWorkEventArgs e) {
while (true)
{
for (int j = 0; j < m_listenFor.Length; j++)
{
if ((DllImportCaller.lib.GetAsyncKeyState7(m_listenFor[j]) != 0) && (OnKeyDown != null))
{
OnKeyDown(null, (PhysicalKeys) m_listenFor[j]);
}
}
Thread.Sleep(500);
}
};
hookThread.RunWorkerAsync();
/////////////////////////////
so i use it and change it to a test code:
BackgroundWorker s=new BackgroundWorker();
S.DoWork+=delegate(object o,DoWorkEventArgs e)
{
while(true)
{
MessageBox.Show(i.ToString());//varible i has been declared before;
i++;
Thread.Sleep(500);
}
};
s.RunWorkAsync();
!!however,we i run it on my hdc device!nothing happened!WHY? AND
I have changed the DehydrateOnPause from 3 to 0.but it still can't work !
who can save me!!!!!!
kissmegodlike said:
i has decompile screen_capture_1.03 and i saw these code:
hookThread = new BackgroundWorker();
hookThread.DoWork += delegate (object o, DoWorkEventArgs e) {
while (true)
{
for (int j = 0; j < m_listenFor.Length; j++)
{
if ((DllImportCaller.lib.GetAsyncKeyState7(m_listenFor[j]) != 0) && (OnKeyDown != null))
{
OnKeyDown(null, (PhysicalKeys) m_listenFor[j]);
}
}
Thread.Sleep(500);
}
};
hookThread.RunWorkerAsync();
/////////////////////////////
so i use it and change it to a test code:
BackgroundWorker s=new BackgroundWorker();
S.DoWork+=delegate(object o,DoWorkEventArgs e)
{
while(true)
{
MessageBox.Show(i.ToString());//varible i has been declared before;
i++;
Thread.Sleep(500);
}
};
s.RunWorkAsync();
!!however,we i run it on my hdc device!nothing happened!WHY? AND
I have changed the DehydrateOnPause from 3 to 0.but it still can't work !
who can save me!!!!!!
Click to expand...
Click to collapse
You have to keep the for int in there, as it is constantly waiting for you to press the button.
TheMrBlue said:
You have to keep the for int in there, as it is constantly waiting for you to press the button.
Click to expand...
Click to collapse
In fact,i mean the backroundworker does't work at all.cound you tell me what errors result in my code's failure.

Need help recompiling settings.apk

I have a modified wifidisplaysettings.java file that enables auto connect to wifi display but i need some help getting it into settings.apk. can anyone help with recompiling?
How did you decompile?
Sent from my Nexus 5 using Tapatalk
i used apk2java. i was also talking to someone on another forum who gave me the modified java file but said that the files I got from decompiling may not be useable for recompiling, so im not really sure how to get this back in to there.
I would recommend decompiling with apk tool, making the mods then recompiling with Apk tool. There are guides on xda
Sent from my Nexus 5 using Tapatalk
i decompiled with apk tool but i got smali files. i dont know how to make the changes i need in smali. the modified file i have is a java file.
Munkee915 said:
ii dont know how to make the changes i need in smali
Click to expand...
Click to collapse
If you're wanting to recompile, you'll need to work that out
Sent from my Nexus 5 using Tapatalk
well here are the steps ive taken so far. Keep in mind im not a programmer. Im doing everything from the seat of my pants and whatever i can find on here and google:
1. I have the modified wifidisplaysettings.java and settings.apk from the original author (JOK on appradio forums, he gave me permission to seek help compiling into something i can use) which is built off of CM 10.2 settings.apk.
2. Tried flashing his file, flash failed
3. Tried modifying his zip file with the META-INF from another mod i have on the phone. flash succeeds, but Settings is missing from my apps. i can see it in system/priv-app but when i click on it it asks to install and then fails.
4. I decompiled my settings.apk (stock kot49h) to java and changed my wifidisplaysettings.java w/ his edits but im told i cant recompile this back to a usable APK.
5. I decompiled his settings.apk and my settings.apk to smali and moved his wfd folder into my decompiled folder, recompiled my settings.apk, signed and flashed to my phone. Phone boots but again Settings is missing from my apps
6. Tried flashing CM 11 nightly and then flashing his settings file, no dice
7. Pulled the stock CM 11 settings.apk, decompiled to smali and swapped the wfd folder, recompiled, signed and flashed. i can open settings now but when i go to cast screen settings crashes.
8. Restored my nandroid backup and now im seeking help
When you recompile, don't forget to replace all the signature files from your original apk.
http://forum.xda-developers.com/showthread.php?t=1989533
Sent from my Nexus 5 using Tapatalk
is that not the same thing as resigning the apk? I've been using signapk for that part and then going to flash after that.
Rule it out
Sent from my Nexus 5 using Tapatalk
rootSU said:
Rule it out
Sent from my Nexus 5 using Tapatalk
Click to expand...
Click to collapse
Same thing. Compiled and pulled the xml files and resources file and put them into the original apk and flashed. Phone boots but settings is nowhere to be found.
Munkee915 said:
Same thing. Compiled and pulled the xml files and resources file and put them into the original apk and flashed. Phone boots but settings is nowhere to be found.
Click to expand...
Click to collapse
You need to decompile and recompile with apktool or any other tool like that mate. You need to edit the smali if you want to make changes. But if i am not wrong you can decompile the settingsprovider and make the changes in bools to enable that option.
Sent from my Nexus 5 using XDA Premium 4 mobile app
maybe (or definitely) i dont understand what im doing. i am decompiling and compiling with apktool. when i decompile i see smali files and i make the changes there. i then recompile with apktool and in the resulting apk i only have xml files, so going with guide rootSU pointed me to i use winrar and pull them from teh new apk and drop them in the original apk along with resources.arsc and flash that. the original author has suggested i build the entire image again from source using his java file and it should work, but taht would mean i have to setup a build environment. i cant even get this right im not sure i can build an image from source lol.
Sometimes it's the modifications that cause the problem.
Is his settings.apk from the same phone? Same ROM? You can't build stock settings from source. Only aosp.
Sent from my Nexus 5 using Tapatalk
his mod was done on CM 10.2 on a GS4. Not the same but when we compared the source they were almost identical so we were hoping it was close enough that they would translate over.
Very doubtful
Sent from my Nexus 5 using Tapatalk
Well that's disappointing. It seems like a really useful mod that a lot of people ask for it's a shame we cant get it going. if anyone wants to take a crack at it here is the java code I was given. Hopefully someone can get this done.
Code:
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.wfd;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.hardware.display.DisplayManager;
import android.hardware.display.IRemoteDisplayAdapter;
import android.hardware.display.WifiDisplay;
import android.hardware.display.WifiDisplayStatus;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.text.Html;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import com.android.settings.ProgressCategory;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
/**
* The Settings screen for WifiDisplay configuration and connection management.
*/
public final class WifiDisplaySettings extends SettingsPreferenceFragment {
private static final String TAG = "WifiDisplaySettings";
private static final int MENU_ID_SCAN = Menu.FIRST;
private DisplayManager mDisplayManager;
private boolean mWifiDisplayOnSetting;
private WifiDisplayStatus mWifiDisplayStatus;
private WifiDisplayStatus mRemoteDisplayStatus;
private IRemoteDisplayAdapter mRemoteDisplayAdapter;
private PreferenceGroup mPairedDevicesCategory;
private ProgressCategory mAvailableDevicesCategory;
private TextView mEmptyView;
private Switch mActionBarSwitch;
private CheckBoxPreference mDisableHDCP;
private static final String DISABLE_HDCP_PREF = "persist.sys.wfd.nohdcp";
public WifiDisplaySettings() {
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mDisplayManager = (DisplayManager)getActivity().getSystemService(Context.DISPLAY_SERVICE);
mRemoteDisplayAdapter = mDisplayManager.getRemoteDisplayAdapter();
addPreferencesFromResource(R.xml.wifi_display_settings);
setHasOptionsMenu(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Activity activity = getActivity();
mActionBarSwitch = new Switch(activity);
mActionBarSwitch.setOnCheckedChangeListener(mSwitchOnCheckedChangedListener​);
final int padding = activity.getResources().getDimensionPixelSize(
R.dimen.action_bar_switch_padding);
mActionBarSwitch.setPaddingRelative(0, 0, padding, 0);
activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
ActionBar.DISPLAY_SHOW_CUSTOM);
activity.getActionBar().setCustomView(mActionBarSwitch,
new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_VERTICAL | Gravity.END));
mEmptyView = (TextView) getView().findViewById(android.R.id.empty);
getListView().setEmptyView(mEmptyView);
update();
// JOK auto connect
autoConnect();
if (mWifiDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_UNAVAILABLE) {
activity.finish();
}
}
@Override
public void onDestroyView() {
getActivity().getActionBar().setCustomView(null);
super.onDestroyView();
}
private void scanRemoteDisplays() {
try {
mRemoteDisplayAdapter.scanRemoteDisplays();
}
catch (RemoteException e) {
}
}
@Override
public void onResume() {
super.onResume();
Context context = getActivity();
IntentFilter filter = new IntentFilter();
filter.addAction(DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED);
filter.addAction(DisplayManager.ACTION_REMOTE_DISPLAY_STATUS_CHANGED);
context.registerReceiver(mReceiver, filter);
getContentResolver().registerContentObserver(Settings.Secure.getUriFor(
Settings.Global.WIFI_DISPLAY_ON), false, mSettingsObserver);
mDisplayManager.scanWifiDisplays();
scanRemoteDisplays();
update();
// JOK auto connect
autoConnect();
}
@Override
public void onPause() {
super.onPause();
Context context = getActivity();
context.unregisterReceiver(mReceiver);
getContentResolver().unregisterContentObserver(mSettingsObserver);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem item = menu.add(Menu.NONE, MENU_ID_SCAN, 0,
mWifiDisplayStatus.getScanState() == WifiDisplayStatus.SCAN_STATE_SCANNING ?
R.string.wifi_display_searching_for_devices :
R.string.wifi_display_search_for_devices);
item.setEnabled(mWifiDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_ON
&& mWifiDisplayStatus.getScanState() == WifiDisplayStatus.SCAN_STATE_NOT_SCANNING);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ID_SCAN:
if (mWifiDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_ON) {
mDisplayManager.scanWifiDisplays();
}
if (mRemoteDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_ON) {
scanRemoteDisplays();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
if (preference instanceof WifiDisplayPreference) {
WifiDisplayPreference p = (WifiDisplayPreference)preference;
WifiDisplay display = p.getDisplay();
boolean isActive = false;
if (p.isRemoteDisplay()) {
isActive = display.equals(mRemoteDisplayStatus.getActiveDisplay());
} else {
isActive = display.equals(mWifiDisplayStatus.getActiveDisplay());
}
if (isActive) {
showDisconnectDialog(display, p.isRemoteDisplay());
} else if (!p.isRemoteDisplay()) {
mDisplayManager.connectWifiDisplay(display.getDeviceAddress());
} else {
try {
mRemoteDisplayAdapter.connectRemoteDisplay(display.getDeviceAddress());
}
catch (RemoteException e) {
}
}
}
else if (preference == mDisableHDCP) {
SystemProperties.set(DISABLE_HDCP_PREF, mDisableHDCP.isChecked() ? "1" : "0");
return true;
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
private void update() {
mWifiDisplayOnSetting = Settings.Global.getInt(getContentResolver(),
Settings.Global.WIFI_DISPLAY_ON, 0) != 0;
mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus();
try {
mRemoteDisplayStatus = mRemoteDisplayAdapter.getRemoteDisplayStatus();
}
catch (RemoteException e) {
}
applyState();
}
private void applyState() {
final int featureState = mWifiDisplayStatus.getFeatureState();
mActionBarSwitch.setEnabled(featureState != WifiDisplayStatus.FEATURE_STATE_DISABLED);
mActionBarSwitch.setChecked(mWifiDisplayOnSetting);
final PreferenceScreen preferenceScreen = getPreferenceScreen();
preferenceScreen.removeAll();
if (featureState == WifiDisplayStatus.FEATURE_STATE_ON) {
final WifiDisplay[] pairedDisplays = mWifiDisplayStatus.getRememberedDisplays();
final WifiDisplay[] availableDisplays = mWifiDisplayStatus.getAvailableDisplays();
final WifiDisplay[] pairedRemoteDisplays = mRemoteDisplayStatus.getRememberedDisplays();
final WifiDisplay[] availableRemoteDisplays = mRemoteDisplayStatus.getAvailableDisplays();
mDisableHDCP = new CheckBoxPreference(getActivity().getApplicationContext());
mDisableHDCP.setTitle(R.string.pref_wifi_disable_hdcp_title);
mDisableHDCP.setSummary(R.string.pref_wifi_disable_hdcp_summary);
mDisableHDCP.setChecked(Integer.parseInt(SystemProperties.get(DISABLE_HDCP_​PREF, "0")) != 0);
mDisableHDCP.setOrder(0);
preferenceScreen.addPreference(mDisableHDCP);
if (mPairedDevicesCategory == null) {
mPairedDevicesCategory = new PreferenceCategory(getActivity());
mPairedDevicesCategory.setTitle(R.string.wifi_display_paired_devices);
} else {
mPairedDevicesCategory.removeAll();
}
mPairedDevicesCategory.setOrder(1);
preferenceScreen.addPreference(mPairedDevicesCategory);
for (WifiDisplay d : pairedDisplays) {
mPairedDevicesCategory.addPreference(createWifiDisplayPreference(d, true, false));
}
for (WifiDisplay d : pairedRemoteDisplays) {
if (d.isHidden()) {
continue;
}
mPairedDevicesCategory.addPreference(createWifiDisplayPreference(d, true, true));
}
if (mPairedDevicesCategory.getPreferenceCount() == 0) {
preferenceScreen.removePreference(mPairedDevicesCategory);
}
if (mAvailableDevicesCategory == null) {
mAvailableDevicesCategory = new ProgressCategory(getActivity(), null,
R.string.wifi_display_no_devices_found);
mAvailableDevicesCategory.setTitle(R.string.wifi_display_available_devices)​;
} else {
mAvailableDevicesCategory.removeAll();
}
mAvailableDevicesCategory.setOrder(2);
preferenceScreen.addPreference(mAvailableDevicesCategory);
for (WifiDisplay d : availableDisplays) {
if (!contains(pairedDisplays, d.getDeviceAddress())) {
mAvailableDevicesCategory.addPreference(createWifiDisplayPreference(d, false, false));
}
}
for (WifiDisplay d : availableRemoteDisplays) {
if (!contains(pairedRemoteDisplays, d.getDeviceAddress())
&& !(d.getDeviceName().startsWith("hidden:"))) {
mAvailableDevicesCategory.addPreference(createWifiDisplayPreference(d, false, true));
}
}
if (mWifiDisplayStatus.getScanState() == WifiDisplayStatus.SCAN_STATE_SCANNING ||
mRemoteDisplayStatus.getScanState() == WifiDisplayStatus.SCAN_STATE_SCANNING) {
mAvailableDevicesCategory.setProgress(true);
} else {
mAvailableDevicesCategory.setProgress(false);
}
} else {
mEmptyView.setText(featureState == WifiDisplayStatus.FEATURE_STATE_OFF ?
R.string.wifi_display_settings_empty_list_wifi_display_off :
R.string.wifi_display_settings_empty_list_wifi_display_disabled);
}
getActivity().invalidateOptionsMenu();
}
private void autoConnect() {
final int featureState = mWifiDisplayStatus.getFeatureState();
/** mActionBarSwitch.setEnabled(featureState != WifiDisplayStatus.FEATURE_STATE_DISABLED);
mActionBarSwitch.setChecked(mWifiDisplayOnSetting);
final PreferenceScreen preferenceScreen = getPreferenceScreen();
preferenceScreen.removeAll(); */
if (featureState == WifiDisplayStatus.FEATURE_STATE_ON) {
final WifiDisplay[] pairedDisplays = mWifiDisplayStatus.getRememberedDisplays();
final WifiDisplay[] availableDisplays = mWifiDisplayStatus.getAvailableDisplays();
final WifiDisplay[] pairedRemoteDisplays = mRemoteDisplayStatus.getRememberedDisplays();
final WifiDisplay[] availableRemoteDisplays = mRemoteDisplayStatus.getAvailableDisplays();
/** mDisableHDCP = new CheckBoxPreference(getActivity().getApplicationContext());
mDisableHDCP.setTitle(R.string.pref_wifi_disable_hdcp_title);
mDisableHDCP.setSummary(R.string.pref_wifi_disable_hdcp_summary);
mDisableHDCP.setChecked(Integer.parseInt(SystemProperties.get(DISABLE_HDCP_​PREF, "0")) != 0);
mDisableHDCP.setOrder(0);
preferenceScreen.addPreference(mDisableHDCP);
if (mPairedDevicesCategory == null) {
mPairedDevicesCategory = new PreferenceCategory(getActivity());
mPairedDevicesCategory.setTitle(R.string.wifi_display_paired_devices);
} else {
mPairedDevicesCategory.removeAll();
}
mPairedDevicesCategory.setOrder(1);
preferenceScreen.addPreference(mPairedDevicesCategory); */
/** for (WifiDisplay d : pairedDisplays) {
mPairedDevicesCategory.addPreference(createWifiDisplayPreference(d, true, false));
}
for (WifiDisplay d : pairedRemoteDisplays) {
if (d.isHidden()) {
continue;
}
mPairedDevicesCategory.addPreference(createWifiDisplayPreference(d, true, true));
}
if (mPairedDevicesCategory.getPreferenceCount() == 0) {
preferenceScreen.removePreference(mPairedDevicesCategory);
}
if (mAvailableDevicesCategory == null) {
mAvailableDevicesCategory = new ProgressCategory(getActivity(), null,
R.string.wifi_display_no_devices_found);
mAvailableDevicesCategory.setTitle(R.string.wifi_display_available_devices)​;
} else {
mAvailableDevicesCategory.removeAll();
}
mAvailableDevicesCategory.setOrder(2);
preferenceScreen.addPreference(mAvailableDevicesCategory); */
for (WifiDisplay d : availableDisplays) {
/** if (!contains(pairedDisplays, d.getDeviceAddress())) {
mAvailableDevicesCategory.addPreference(createWifiDisplayPreference(d, false, false));
} */
// JOK check if there is an existing connection
boolean isActive = false;
isActive = d.equals(mWifiDisplayStatus.getActiveDisplay());
// JOK only connect, if there is no existing connection
if (!isActive) {
mDisplayManager.connectWifiDisplay(d.getDeviceAddress());
}
}
for (WifiDisplay d : availableRemoteDisplays) {
/** if (!contains(pairedRemoteDisplays, d.getDeviceAddress())
&& !(d.getDeviceName().startsWith("hidden:"))) {
mAvailableDevicesCategory.addPreference(createWifiDisplayPreference(d, false, true));
} */
// JOK check if there is an existing connection
boolean isActive = false;
isActive = d.equals(mRemoteDisplayStatus.getActiveDisplay());
// JOK only connect, if there is no existing connection
if (!isActive) {
try {
mRemoteDisplayAdapter.connectRemoteDisplay(d.getDeviceAddress());
}
catch (RemoteException e) {
}
}
}
/** if (mWifiDisplayStatus.getScanState() == WifiDisplayStatus.SCAN_STATE_SCANNING ||
mRemoteDisplayStatus.getScanState() == WifiDisplayStatus.SCAN_STATE_SCANNING) {
mAvailableDevicesCategory.setProgress(true);
} else {
mAvailableDevicesCategory.setProgress(false);
}
} else {
mEmptyView.setText(featureState == WifiDisplayStatus.FEATURE_STATE_OFF ?
R.string.wifi_display_settings_empty_list_wifi_display_off :
R.string.wifi_display_settings_empty_list_wifi_display_disabled); */
}
//getActivity().invalidateOptionsMenu();
}
private Preference createWifiDisplayPreference(final WifiDisplay d, boolean paired, boolean isRemote) {
WifiDisplayPreference p = new WifiDisplayPreference(getActivity(), d, isRemote);
WifiDisplayStatus displayStatus = null;
if (isRemote) {
displayStatus = mRemoteDisplayStatus;
} else {
displayStatus = mWifiDisplayStatus;
}
if (d.equals(displayStatus.getActiveDisplay())) {
switch (displayStatus.getActiveDisplayState()) {
case WifiDisplayStatus.DISPLAY_STATE_CONNECTED:
p.setSummary(R.string.wifi_display_status_connected);
break;
case WifiDisplayStatus.DISPLAY_STATE_CONNECTING:
p.setSummary(R.string.wifi_display_status_connecting);
break;
}
} else if (paired && contains(displayStatus.getAvailableDisplays(),
d.getDeviceAddress())) {
p.setSummary(R.string.wifi_display_status_available);
}
if (paired) {
p.setWidgetLayoutResource(R.layout.wifi_display_preference);
}
return p;
}
private void showDisconnectDialog(final WifiDisplay display, final boolean isRemoteDisplay) {
DialogInterface.OnClickListener ok = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!isRemoteDisplay && display.equals(mWifiDisplayStatus.getActiveDisplay())) {
mDisplayManager.disconnectWifiDisplay();
} else if (isRemoteDisplay && display.equals(mRemoteDisplayStatus.getActiveDisplay())) {
try {
mRemoteDisplayAdapter.disconnectRemoteDisplay();
}
catch (RemoteException e) {
}
}
}
};
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(R.string.wifi_display_disconnect_title)
.setMessage(Html.fromHtml(getResources().getString(
R.string.wifi_display_disconnect_text, display.getFriendlyDisplayName())))
.setPositiveButton(android.R.string.ok, ok)
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.show();
}
private void showOptionsDialog(final WifiDisplay display, final boolean isRemoteDisplay) {
View view = getActivity().getLayoutInflater().inflate(R.layout.wifi_display_options, null);
final EditText nameEditText = (EditText)view.findViewById(R.id.name);
nameEditText.setText(display.getFriendlyDisplayName());
DialogInterface.OnClickListener done = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = nameEditText.getText().toString().trim();
if (name.isEmpty() || name.equals(display.getDeviceName())) {
name = null;
}
if (!isRemoteDisplay) {
mDisplayManager.renameWifiDisplay(display.getDeviceAddress(), name);
} else {
try {
mRemoteDisplayAdapter.renameRemoteDisplay(display.getDeviceAddress(), name);
}
catch (RemoteException e) {
}
}
}
};
DialogInterface.OnClickListener forget = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!isRemoteDisplay) {
mDisplayManager.forgetWifiDisplay(display.getDeviceAddress());
} else {
try {
mRemoteDisplayAdapter.forgetRemoteDisplay(display.getDeviceAddress());
}
catch (RemoteException e) {
}
}
}
};
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(R.string.wifi_display_options_title)
.setView(view)
.setPositiveButton(R.string.wifi_display_options_done, done)
.setNegativeButton(R.string.wifi_display_options_forget, forget)
.create();
dialog.show();
}
private static boolean contains(WifiDisplay[] displays, String address) {
for (WifiDisplay d : displays) {
if (d.getDeviceAddress().equals(address)) {
return true;
}
}
return false;
}
private final CompoundButton.OnCheckedChangeListener mSwitchOnCheckedChangedListener =
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mWifiDisplayOnSetting = isChecked;
Settings.Global.putInt(getContentResolver(),
Settings.Global.WIFI_DISPLAY_ON, isChecked ? 1 : 0);
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED)) {
WifiDisplayStatus status = (WifiDisplayStatus)intent.getParcelableExtra(
DisplayManager.EXTRA_WIFI_DISPLAY_STATUS);
mWifiDisplayStatus = status;
applyState();
// JOK auto connect
autoConnect();
} else if (action.equals(DisplayManager.ACTION_REMOTE_DISPLAY_STATUS_CHANGED)) {
WifiDisplayStatus status = (WifiDisplayStatus)intent.getParcelableExtra(
DisplayManager.EXTRA_REMOTE_DISPLAY_STATUS);
mRemoteDisplayStatus = status;
applyState();
// JOK auto connect
autoConnect();
}
}
};
private final ContentObserver mSettingsObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange, Uri uri) {
update();
}
};
private final class WifiDisplayPreference extends Preference
implements View.OnClickListener {
private final WifiDisplay mDisplay;
private final boolean mIsRemoteDisplay;
public WifiDisplayPreference(Context context,
WifiDisplay display, boolean isRemoteDisplay) {
super(context);
mDisplay = display;
mIsRemoteDisplay = isRemoteDisplay;
setTitle(display.getFriendlyDisplayName());
}
public WifiDisplay getDisplay() {
return mDisplay;
}
public boolean isRemoteDisplay() {
return mIsRemoteDisplay;
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
ImageView deviceDetails = (ImageView) view.findViewById(R.id.deviceDetails);
if (deviceDetails != null) {
deviceDetails.setOnClickListener(this);
if (!isEnabled()) {
TypedValue value = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.disabledAlpha,
value, true);
deviceDetails.setImageAlpha((int)(value.getFloat() * 255));
}
}
}
@Override
public void onClick(View v) {
showOptionsDialog(mDisplay, mIsRemoteDisplay);
}
}
}

Cell Info 5G NR Neighbour Cells Information

Hi all,
I'm developing an application that captures the information of the LTE and 5G NR network information. I have created two different services (Kotlin services that are very similar to pool threads) which captures the information of the LTE and its neighbours in one service and the same for 5G NR in another service. The transformation to obtain the same information is very similar from LTE to 5G, and it is supposed to work. In the LTE service I obtain the information of the LTE serving cell information below (First quote) and the 5G NR service in the other quote. I would like to point out from the 5G service provides me the information of ONLY the serving cell, however, I need the information of all the cells. Does anyone have any clue?
Thanks for anyone who stops for reading this =)
package com.mobilenet.monitoring.services
import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.telephony.*
import android.util.Log
import androidx.core.app.ActivityCompat
import com.mobilenet.monitoring.R
import com.mobilenet.monitoring.app.preferences
import org.json.JSONObject
import java.text.DateFormat
import java.util.*
import kotlin.collections.HashMap
class ServiceLte : Service() {
val TAG = "TESTING"
private var mBinder: IBinder = MyBinder()
private var mHandler = Handler()
/* Lte Parameters */
var mSignalStrength: SignalStrength? = null
var mListSignalStrength: List<CellSignalStrength>? = null
var mSignalStrengthLte: CellSignalStrengthLte? = null
var mManager: TelephonyManager? = null
/* LteConnection */
private var mLteData: JSONObject = JSONObject()
private var mLteNeighbourData: JSONObject = JSONObject()
var infos: MutableList<CellInfo>? = null
private lateinit var mContext:Context
private var jsonObject:JSONObject = JSONObject()
private var dataNeighbour = HashMap< String, String>()
private var lte:CellSignalStrengthLte? = null
private var identityLte:CellIdentityLte? = null
private var ci:Int = -1
private var MCC:String? = ""
private var MNC:String? = ""
private var PLMN:String? = ""
private var cellidHex: String = ""
private var eNBHex:String = ""
private var eNB: Int = -1
override fun onBind(intent: Intent): IBinder? {
return mBinder
}
@SuppressLint("MissingPermission")
override fun onCreate() {
super.onCreate()
Log.d(TAG, "onCreate")
mContext = this
/* LTE */
mManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
//mManager!!.listen( mListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS or PhoneStateListener.LISTEN_CELL_INFO)
update()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(TAG, "onStartCommand")
if(intent?.getStringExtra("action") == "Destroy"){
onDestroy()
}
val CHANNELID = "Foreground Service ID"
val channel = NotificationChannel(
CHANNELID,
CHANNELID,
NotificationManager.IMPORTANCE_LOW
)
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
val notification: Notification.Builder = Notification.Builder(this, CHANNELID)
.setContentText("Monitoring is running")
.setContentTitle("Monitoring enabled")
.setSmallIcon(R.drawable.ic_launcher_background)
startForeground(1001, notification.build())
return super.onStartCommand(intent, flags, startId)
}
fun getLteData(): JSONObject {
return mLteData
}
fun getNeighbourLteData(): JSONObject {
return mLteNeighbourData
}
// Listener for signal strength.
private val mListener: PhoneStateListener = object : PhoneStateListener() {
override fun onSignalStrengthsChanged(sStrength: SignalStrength) {
mSignalStrength = sStrength
Log.d(TAG,"SignalStrength cambia HOLAA")
if (ActivityCompat.checkSelfPermission(mContext,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
infos = mManager!!.allCellInfo
}
}
override fun onCellInfoChanged(cellInfo: MutableList<CellInfo>) {
Log.d(TAG,"CellInfo cambia")
infos = cellInfo
}
}
private fun update() {
val runnable = object : Runnable {
@SuppressLint("MissingPermission", "NewApi")
override fun run() {
mLteData = JSONObject()
mLteNeighbourData = JSONObject()
infos = null
jsonObject = JSONObject()
mManager!!.requestCellInfoUpdate( mContext.mainExecutor,
object : TelephonyManager.CellInfoCallback() {
override fun onCellInfo(cellInfo: MutableList<CellInfo>) {
Log.d(TAG, "Requesting cell update")
getData(cellInfo)
}
})
mHandler.postDelayed(this, 500)//preferences.periodicity.toLong())
}
}
mHandler.postDelayed(runnable, 500)//preferences.periodicity.toLong())
}
@SuppressLint("NewApi")
private fun getData(cellInfo: MutableList<CellInfo>){
try {
mSignalStrengthLte = (cellInfo[0] as CellInfoLte).cellSignalStrength
//LTE connected
if (preferences.LteEnable) {
if (preferences.LteCQI) mLteData.put("LteCqi", "${mSignalStrengthLte!!.cqi}")
if (preferences.LteLevel) mLteData.put("LteLevel","${mSignalStrengthLte!!.level}")
if (preferences.LteRSRP) mLteData.put("LteRSRP", "${mSignalStrengthLte!!.rsrp}")
if (preferences.LteRSRQ) mLteData.put("LteRSRQ", "${mSignalStrengthLte!!.rsrq}")
if (preferences.LteRSSI) mLteData.put("LteRSSI", "${mSignalStrengthLte!!.rssi}")
if (preferences.LteRSSNR) mLteData.put("LteRSSNR","${mSignalStrengthLte!!.rssnr}")
if (preferences.LteTA) mLteData.put("LteTimingAdvance", "${mSignalStrengthLte!!.timingAdvance}")
if (preferences.LteDbm) mLteData.put("LteDbm", "${mSignalStrengthLte!!.dbm}")
if (preferences.LteAsuLevel) mLteData.put("LteAsuLevel", "${mSignalStrengthLte!!.asuLevel}")
}
}catch (ex: Exception) {
Log.i(TAG, ex.message)
}
//LTE neighbours
@SuppressLint("MissingPermission")
infos = mManager!!.allCellInfo
jsonObject = JSONObject()
dataNeighbour = HashMap< String, String>()
if (preferences.NeighbourLteEnable){
jsonObject.put("NumberOfSites", "${infos!!.size}")
}
for (i in infos!!.indices) {
try {
val info = infos!!
if (info is CellInfoLte) //if LTE connection
{
//mManager!!.getNetworkOperator()
lte = info.cellSignalStrength
identityLte = info.cellIdentity
ci = identityLte!!.ci
MCC = identityLte!!.mccString
MNC = identityLte!!.mncString
if(MNC == null || MCC == null) PLMN = "XXXX"
else if (MNC!!.length == 3) {
PLMN = "${MCC!![1]}${MCC!![0]}${MNC!![2]}${MCC!![2]}${MNC!![1]}${MNC!![0]}"
} else {
PLMN = "${MCC!![1]}${MCC!![0]}F${MCC!![2]}${MNC!![1]}${MNC!![0]}"
}
cellidHex = String.format("%x", ci)
eNBHex = cellidHex.substring(0, cellidHex.length - 2)
eNB = Integer.parseInt(eNBHex, 16)
//ECI = 256 * eNBId + Cellid
dataNeighbour["Registered"] = "${info!!.isRegistered()}"
if (preferences.NeighbourLteRsrp) dataNeighbour["RSRP"] = "${lte!!.rsrp}"
if (preferences.NeighbourLteRssi) dataNeighbour["RSSI"] = "${lte!!.rssi}" //Unavailable
if (preferences.NeighbourLteCqi) dataNeighbour["CQI"] = "${lte!!.cqi}" //Unavailable
if (preferences.NeighbourLteDbm) dataNeighbour["Dbm"] = "${lte!!.dbm}"
if (preferences.NeighbourLteLevel) dataNeighbour["LevelSignalStrength"] = "${lte!!.level}"
if (preferences.NeighbourLteRsrq) dataNeighbour["RSRQ"] = "${lte!!.rsrq}"
if (preferences.NeighbourLteRssnr) dataNeighbour["RSSNR"] = "${lte!!.rssnr}"
if (preferences.NeighbourLtePci) dataNeighbour["PCI"] = "${identityLte!!.pci}"
if (preferences.NeighbourLteCi) dataNeighbour["CI"] = "${ci}"
if (preferences.NeighbourLteMnc) dataNeighbour["MNC"] = "${MNC}"
if (preferences.NeighbourLteMcc) dataNeighbour["MCC"] = "${MCC}"
if (preferences.NeighbourLtePlmn) dataNeighbour["PLMN"] = "${PLMN}"
if (preferences.NeighbourLteEnb) dataNeighbour["eNB"] = "${eNB}"
if (preferences.NeighbourLteMobileNetworkOperator) dataNeighbour["MobileNetworkOperatorID"] = "${identityLte!!.mobileNetworkOperator}"
if (preferences.NeighbourLteMobileNetworkOperator) dataNeighbour["MobileNetworkOperatorName"] = "${identityLte!!.operatorAlphaLong}"
if (preferences.NeighbourLteTac) dataNeighbour["TAC"] = "${identityLte!!.tac}"
if (preferences.NeighbourLteBandwith) dataNeighbour["Bandwidth"] = "${identityLte!!.bandwidth}"
if (preferences.NeighbourLteEarfcn){
dataNeighbour["EarFCN"] = "${identityLte!!.earfcn}"
dataNeighbour["Band"] = "${getBand(identityLte!!.earfcn)}"
}
}else{
if (info is CellInfoGsm){
var gsm = info.cellSignalStrength
var identityGsm = info.cellIdentity
Log.d(TAG,gsm.toString())
Log.d(TAG,"identityGsm.cid: ${identityGsm.cid}")
Log.d(TAG,identityGsm.toString())
}else if (info is CellInfoCdma){
var gsm = info.cellSignalStrength
var identityGsm = info.cellIdentity
Log.d(TAG,gsm.toString())
Log.d(TAG,"identityCdma.networkId: ${identityGsm.networkId}, identityCdma.systemId: ${identityGsm.systemId}")
Log.d(TAG,identityGsm.toString())
}else if (info is CellInfoWcdma){
var gsm = info.cellSignalStrength
var identityGsm = info.cellIdentity
Log.d(TAG,gsm.toString())
Log.d(TAG,"identityWcdma.cid: ${identityGsm.cid}")
Log.d(TAG,identityGsm.toString())
}else if (info is CellInfoTdscdma){
var gsm = info.cellSignalStrength
var identityGsm = info.cellIdentity
Log.d(TAG,gsm.toString())
Log.d(TAG,"identityTdscdma.cid: ${identityGsm.cid}")
Log.d(TAG,identityGsm.toString())
}
}
} catch (ex: Exception) {
Log.i("TESTING: ", ex.message)
}
jsonObject.putOpt("Site$i", JSONObject(dataNeighbour as Map<*, *>))
}
mLteNeighbourData = jsonObject
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
stopSelf() //a hard stop for the service (si no queremos que siga en funcionamiento al cerrar)
}
override fun onDestroy() {
Log.d(TAG, "onDestroy")
super.onDestroy()
}
inner class MyBinder : Binder() {
fun getService(): ServiceLte? {
return [email protected]
}
}
private fun getBand(arfcn:Int):Int{
when {
arfcn<600 -> return 1
arfcn<1200 -> return 2
arfcn<1950 -> return 3
arfcn<2400 -> return 4
arfcn<2650 -> return 5
arfcn<2750 -> return 6
arfcn<3450 -> return 7
arfcn<3800 -> return 8
arfcn<4150 -> return 9
arfcn<4750 -> return 10
arfcn<5010 -> return 11
arfcn<5180 -> return 12
arfcn<5280 -> return 13
arfcn<5380 -> return 14
arfcn<5730 -> return -1
arfcn<5850 -> return 17
arfcn<6000 -> return 18
arfcn<6150 -> return 19
arfcn<6450 -> return 20
arfcn<6600 -> return 21
arfcn<7500 -> return 22
arfcn<7700 -> return 23
arfcn<8040 -> return 24
arfcn<8690 -> return 25
arfcn<9040 -> return 26
arfcn<9210 -> return 27
arfcn<9660 -> return 28
arfcn<9770 -> return 29
arfcn<9870 -> return 30
arfcn<9920 -> return 31
else -> return 9999
}
}
}
Click to expand...
Click to collapse
Here I also post the 5G NR service to obtain the information:
package com.mobilenet.monitoring.services
import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.telephony.*
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import com.mobilenet.monitoring.R
import com.mobilenet.monitoring.app.preferences
import org.json.JSONObject
class ServiceNr : Service() {
val TAG = "TESTING"
private var mBinder: IBinder = MyBinder()
private var mHandler = Handler()
/* Lte Parameters */
var mSignalStrength: SignalStrength? = null
var mListSignalStrength: List<CellSignalStrength>? = null
var mSignalStrengthNr: CellSignalStrengthNr? = null
var mManager: TelephonyManager? = null
/* LteConnection */
private var mNrData: JSONObject = JSONObject()
private var mNrNeighbourData: JSONObject = JSONObject()
var infos: MutableList<CellInfo>? = null
private lateinit var mContext:Context
private var jsonObject:JSONObject = JSONObject()
private var dataNeighbour = HashMap<String, String>()
private var nr:CellSignalStrengthNr? = null
private var identityNr:CellIdentityNr? = null
private var ci:Int = -1
private var MCC:String? = ""
private var MNC:String? = ""
private var PLMN:String? = ""
private var cellidHex: String = ""
private var eNBHex:String = ""
private var eNB: Int = -1
override fun onBind(intent: Intent): IBinder? {
return mBinder
}
@RequiresApi(Build.VERSION_CODES.Q)
@SuppressLint("MissingPermission")
override fun onCreate() {
super.onCreate()
Log.d(TAG, "onCreate")
mContext = this
/* NR */
mManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
// Register the listener with the telephony manager
// mManager!!.listen( mListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS or PhoneStateListener.LISTEN_CELL_LOCATION)
/*
SSB es el beam
*/
update()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if(intent?.getStringExtra("action") == "Destroy"){
onDestroy()
}
val CHANNELID = "Foreground Service ID"
val channel = NotificationChannel(
CHANNELID,
CHANNELID,
NotificationManager.IMPORTANCE_LOW
)
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
val notification: Notification.Builder = Notification.Builder(this, CHANNELID)
.setContentText("Monitoring is running")
.setContentTitle("Monitoring enabled")
.setSmallIcon(R.drawable.ic_launcher_background)
startForeground(1001, notification.build())
return super.onStartCommand(intent, flags, startId)
}
fun getNrData(): JSONObject {
return mNrData
}
fun getNeighbourNrData(): JSONObject {
return mNrNeighbourData
}
fun destroy(){
stopSelf();
}
// Listener for signal strength.
private val mListener: PhoneStateListener = object : PhoneStateListener() {
override fun onSignalStrengthsChanged(sStrength: SignalStrength) {
mSignalStrength = sStrength
if (ActivityCompat.checkSelfPermission(
mContext,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED) {
infos = mManager!!.allCellInfo
}
}
override fun onCellInfoChanged(cellInfo: MutableList<CellInfo>) {
infos = cellInfo
}
}
private fun update() {
val runnable = object : Runnable {
@SuppressLint("MissingPermission", "NewApi")
override fun run() {
mManager!!.requestCellInfoUpdate( mContext.mainExecutor,
object : TelephonyManager.CellInfoCallback() {
override fun onCellInfo(cellInfo: MutableList<CellInfo>) {
mNrData = JSONObject()
mNrNeighbourData = JSONObject()
infos = null
jsonObject = JSONObject()
getData(cellInfo)
}
})
mHandler.postDelayed(this, 500)//preferences.periodicity.toLong())
}
}
mHandler.postDelayed(runnable, 500)//preferences.periodicity.toLong())
}
@SuppressLint("MissingPermission")
@RequiresApi(Build.VERSION_CODES.Q)
private fun getData(cellInfo: MutableList<CellInfo>){
try {
// Log.d(TAG, "$cellInfo") //Pondría esto para ver qué obtengo a ver si hay aquí algo mal
mSignalStrengthNr = (cellInfo[0] as CellInfoNr).cellSignalStrength as CellSignalStrengthNr
//Nr connected
if (preferences.NeighbourNrEnable) {
if (preferences.NeighbourNrRsrp) mNrData.put(
"NrRsrp",
"${mSignalStrengthNr!!.ssRsrp}"
)
if (preferences.NeighbourNrRsrq) mNrData.put(
"NrRsrq",
"${mSignalStrengthNr!!.ssRsrq}"
)
if (preferences.NeighbourNrSinr) mNrData.put(
"NrSinr",
"${mSignalStrengthNr!!.ssSinr}"
)
if (preferences.NeighbourNrAsulevel) mNrData.put(
"NrAsulevel",
"${mSignalStrengthNr!!.asuLevel}"
)
if (preferences.NeighbourNrDbm) mNrData.put(
"NrDbm",
"${mSignalStrengthNr!!.dbm}"
)
if (preferences.NeighbourNrLevel) mNrData.put(
"NrLevel",
"${mSignalStrengthNr!!.level}"
)
}
}catch (ex: Exception) {
Log.i(TAG, ex.message)
}
infos = mManager!!.allCellInfo
// Log.d(TAG, "$infos") //Pondría esto para ver qué obtengo a ver si hay aquí algo mal
jsonObject = JSONObject()
dataNeighbour = HashMap<String, String>()
if (preferences.NeighbourNrEnable){
jsonObject.put("NumberOfSites", "${infos!!.size}")
}
for (i in infos!!.indices) {
try {
val cell = infos!!
nr = (cell as CellInfoNr).cellSignalStrength as CellSignalStrengthNr
identityNr = (cell as CellInfoNr).cellIdentity as CellIdentityNr
// nr = (cellInfo[0] as CellInfoNr).cellSignalStrength as CellSignalStrengthNr
// identityNr = (cellInfo[0] as CellInfoNr).cellIdentity as CellIdentityNr
// Log.d(TAG,"${infos!!.indices}")
// Log.d(TAG,nr.toString())
// Log.d(TAG,identityNr.toString())
ci = identityNr!!.pci
MCC = identityNr!!.mccString
MNC = identityNr!!.mncString
if(MNC == null || MCC == null)
{
PLMN = "XXXX"
}
else if (MNC!!.length == 3) {
PLMN = "${MCC!![1]}${MCC!![0]}${MNC!![2]}${MCC!![2]}${MNC!![1]}${MNC!![0]}"
} else {
PLMN = "${MCC!![1]}${MCC!![0]}F${MCC!![2]}${MNC!![1]}${MNC!![0]}"
}
if (preferences.NeighbourNrRsrp){
var rsrp = nr!!.ssRsrp
dataNeighbour["RSRP"] = "${rsrp}"
}
if (preferences.NeighbourNrRsrq){
var rsrq = nr!!.ssRsrq
dataNeighbour["RSRP"] = "${rsrq}"
}
if (preferences.NeighbourNrSinr){
var sinr = nr!!.ssSinr
dataNeighbour["Sinr"] = "${sinr}"
}
if (preferences.NeighbourNrAsulevel){
var asulevel = nr!!.asuLevel
dataNeighbour["Asulevel"] = "${asulevel}"
}
if (preferences.NeighbourNrDbm){
var dbm = nr!!.dbm
dataNeighbour["Dbm"] = "${dbm}"
}
if (preferences.NeighbourNrLevel){
var level = nr!!.level
dataNeighbour["Level"] = "${level}"
}
dataNeighbour["PCI"] = "${identityNr!!.pci}"
dataNeighbour["CI"] = "${ci}"
dataNeighbour["MNC"] = "${MNC}"
dataNeighbour["MCC"] = "${MCC}"
dataNeighbour["PLMN"] = "${PLMN}"
dataNeighbour["MobileNetworkOperatorName"] = "${identityNr!!.operatorAlphaLong}"
dataNeighbour["TAC"] = "${identityNr!!.tac}"
dataNeighbour["EarFCN"] = "${identityNr!!.nrarfcn}"
} catch (ex: Exception) {
Log.i("TESTING: ", ex.message)
}
jsonObject.putOpt("Site$i", JSONObject(dataNeighbour as Map<*, *>))
}
mNrNeighbourData = jsonObject
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
stopSelf() //a hard stop for the service (si no queremos que siga en funcionamiento al cerrar)
}
override fun onDestroy() {
Log.d(TAG, "onDestroy")
super.onDestroy()
}
inner class MyBinder : Binder() {
fun getService(): ServiceNr? {
return [email protected]ServiceNr
}
}
private fun getBand(arfcn: Int):Int{
when {
arfcn<600 -> return 1
arfcn<1200 -> return 2
arfcn<1950 -> return 3
arfcn<2400 -> return 4
arfcn<2650 -> return 5
arfcn<2750 -> return 6
arfcn<3450 -> return 7
arfcn<3800 -> return 8
arfcn<4150 -> return 9
arfcn<4750 -> return 10
arfcn<5010 -> return 11
arfcn<5180 -> return 12
arfcn<5280 -> return 13
arfcn<5380 -> return 14
arfcn<5730 -> return -1
arfcn<5850 -> return 17
arfcn<6000 -> return 18
arfcn<6150 -> return 19
arfcn<6450 -> return 20
arfcn<6600 -> return 21
arfcn<7500 -> return 22
arfcn<7700 -> return 23
arfcn<8040 -> return 24
arfcn<8690 -> return 25
arfcn<9040 -> return 26
arfcn<9210 -> return 27
arfcn<9660 -> return 28
arfcn<9770 -> return 29
arfcn<9870 -> return 30
arfcn<9920 -> return 31
else -> return 9999
} //Ya paso de seguir haciendo la tabla https://5g-tools.com/4g-lte-earfcn-calculator/
}
}
Click to expand...
Click to collapse

Categories

Resources