Tweaking

For (most) tweaking you need root access. Your phone/tablet/tvbox needs to be rooted. Check Short Overview for that.

Most of this is based on Android 4.x

A nice read on some Android commands are here. Part 2 and Part 3.


Tip: run Chrome without ads: Chrome > Settings > Privacy and Security > Secure DNS > Other > https://dns.adguard-dns.com/dns-query

Tip: use ADB AppControl to disable bloatware packages


Delete stored wifi network (no root required)


Have been looking for this a long time. Finally found a solution. How to remove stored wifi network with a command line. Yes it is possible and it doesn't need root at all.


First you need to know Android stores previous connected wifi networks. If you want to remove them from the list you can do that from the wifi settings menu. But what if you don't have that option? Well you can do it with a command from adb shell.


After connecting to your device with adb then start a shell. Then we want the list of stored networks on this device:

cmd netpolicy list wifi-networks

It will show a list with previpously saved wifi networks looking like this:

wifinetwork0;none

wifinetwork1;none

wifinetwork2;none

wifinetwork3;none

The numbers represent the netId we need. So the first Wifi network listed is netId 0. (numbers stay until reboot)

Now the magic. This is for Android 9 but probably work for Android 12 as well:

service call wifi 16 i32 1

Result: Parcel(00000000 00000001 '........') #done!

And wifinetwork1 is deleted. Check with cmd netpolicy list wifi-networks

Be aware that wifinetwork2 does NOT become 1 in the list. It is still 2. Until reboot, then a new list is build.



Prevent apps running in background (no root required)


Since Android 7? there is a hidden setting to disable apps running in the background. The OP is called RUN_IN_BACKGROUND and RUN_ANY_IN_BACKGROUND.

To find packages running in the background, and thus consumind battery and RAM use this command in adb shell:

ps -A| grep "\."


To disable running an apps (package) in the background use this command in adb shell:


appops set packagename RUN_IN_BACKGROUND ignore

appops set packagename RUN_ANY_IN_BACKGROUND ignore

appops write-settings

To force a process to keep running in the background:

appops set com.pittvandewitt.viperfx RUN_IN_BACKGROUND allow

appops set com.pittvandewitt.viperfx RUN_ANY_IN_BACKGROUND allow

appops write-settings

Note: deny send error back to app, ignore doesn't so app think background is running OK

To see the current OP's for packagename and how much time is spend in that mode:

appops get packagename

To undo changes use:

appops reset packagename

appops write-settings

To see all apps that can/cannot run in background:

appops query-op RUN_IN_BACKGROUND allow | sort

appops query-op RUN_IN_BACKGROUND ignore | sort

To see alls OP's for all packages: dumpsys appops


Note: appops is a shortcut to the cmd appos command


Mirror your device on PC/Mac


Very easy with opensource ScrCpy latest here: https://github.com/Genymobile/scrcpy/releases/latest

More info here https://fossbytes.com/mirror-android-phone-to-pc-windows-macos/

Drag and Drop files for transfer to /sdcard, when APK it will be installed. Keyboard and Mouse, Copy Paste, Recording, etc.


Backup and restore device with Google drive


You can do backups and restores to your own Google Drive for each device. This can be done using a few command from the ADB Shell.

adb shell

bmgr enabled (is it enabled? )

bmgr enable true (if not enabled yet does settings put secure backup_enabled 1)


Selecting the right transport (backup location)

bmgr list transports (show all available transports)

android/com.android.internal.backup.LocalTransport (/cache/backup/<token>/_full/)

com.google.android.gms/.backup.migrate.service.D2dTransport

* com.google.android.gms/.backup.BackupTransportService (Google Drive)

For example to set transport to local:

bmgr transport android/com.android.internal.backup.LocalTransport

Selected transport android/com.android.internal.backup.LocalTransport (formerly com.google.android.gms/.backup.BackupTransportService)


Note: This is the /cache/backup/<token>/_full/<packagename> (Environment.getDownloadCacheDirectory())

-rw------- 1 system system 1186816 2021-01-19 00:09 com.feedr

bmgr list transports

* android/com.android.internal.backup.LocalTransport (/cache/backup)

com.google.android.gms/.backup.migrate.service.D2dTransport

com.google.android.gms/.backup.BackupTransportService (Google Drive)

bmgr list sets (show all devices with your google account, or local disk if transport is local)

1 : Local disk image

or with gms BackupTransportService you see your devices in the cloud (Google Drive)

...ea593 : Redmi Note 8 Pro

...28418 : Xiaomi Redmi 4X

...ad91b : cm84

...86d68 : Asus Memo Pad HD7

...76576 : Samsung...


List the status of the backup

dumpsys backup


Do the backup

For the best backup use the fullbackup option! For example launchers will have widgets restored too.

bmgr fullbackup com.wolf.firelauncher

bmgr run (run any pending operations now)

dumpsys backup (check for Pending key/value backup)


Do the restore

dumpsys backup|grep Current (show current "TOKEN", here 1)

Current: 1

bmgr restore 1 com.wolf.firelauncher

Scheduling restore: Local disk image

restoreStarting: 1 packages

onUpdate: 0 = com.wolf.firelauncher

restoreFinished: 0

done

bmgr run (run any pending operations now)


Restore package from other device

bmgr list sets

...179e3e4 : Hope Lite

...0e28418 : Xiaomi Redmi 4X

...a68ad1b : cm84

...86d7e68 : Asus Memo Pad HD7

The sets are the TOKENS and device names.

So if you want to restore settings from a certain package from another device:

bmgr restore <device token> <packagename>


Check backups and other info

dumpsys backup

and search for "Ever backed up"


Scheduled Backups

When using "dumpsys backup" you will notice scheduled times. These are epoch Unix times. (use "date -d @1611321304 #don't use last 3 digits!!!)

When using "dumpsys jobscheduler|grep -i backup"

JOB #1000/20536: d98d960 android/com.android.server.backup.FullBackupJob

1000 tag=*job*/android/com.android.server.backup.FullBackupJob

Service: android/com.android.server.backup.FullBackupJob

JOB #1000/20537: 3f6a4a1 android/com.android.server.backup.KeyValueBackupJob

1000 tag=*job*/android/com.android.server.backup.KeyValueBackupJob

Service: android/com.android.server.backup.KeyValueBackupJob

JOB #u0a42/1: cbfb24f com.google.android.gms/.backup.component.GmsBackupSchedulerService

u0a42 tag=*job*/com.google.android.gms/.backup.component.GmsBackupSchedulerService

Service: com.google.android.gms/.backup.component.GmsBackupSchedulerService

JOB #u0a42/2: 88de59d com.google.android.gms/.backup.component.MmsBackupSchedulerService

u0a42 tag=*job*/com.google.android.gms/.backup.component.MmsBackupSchedulerService

Service: com.google.android.gms/.backup.component.MmsBackupSchedulerService

com.miui.backup

com.android.wallpaperbackup


Now you can use "cmd jobscheduler"


Red "1" is Job ID.

Get status with "cmd jobscheduler get-job-state com.google.android.gms 1" and it is status "waiting"

Run it now with "cmd jobscheduler run com.google.android.gms 1"

Note: view your backups on Google Drive: https://drive.google.com/drive/backups

Usage bmgr (Android 9):

backup pkg

enable

enabled

run

init

list transports/sets

restore <token> <filter> pkg / android

transport -c

wipe pkg

fullbackup pkg

backupnow --all [--non-incremental/--incremental]

cancel backups

whitelist (print transport whitelist)

Auto backup:

bmgr backup @pm@

bmgr run

Note: https://developer.android.com/guide/topics/data/testingbackup

Starting / Stopping apps from the command line (adb)

Android apps are started using so called activities. These activities are listed in the AndroidManifest.xml inside the apk (zip) file.

You can start these activities (and actions) using the am (activity manager) command from a shell.

  • adb shell

    • pm list packages (gives you for example com.android.settings)

  • dumpsys package com.android.settings

  • look for android.intent.action.MAIN:

  • am start -n com.android.systemui/.BeanBag

am start com.android.settings

am force-stop com.android.settings

am force-stop com.google.android.gms

rm /data/app/com.google.android.gms-2.apk

rm -r /data/data/com.google.android.gms

am start com.google.android.gms

am start -n com.android.settings/.wifi.WifiSettings

am start -n com.android.settings/.wifi.WifiInfo

am start -n com.android.settings/.wifi.WifiManageNetworks

am start -n com.android.settings/.wifi.WifiConnectionSettings (Normal/Downtown/Home)

am start -n com.android.settings/.ManageApplications

am start -n com.android.settings/.DevelopmentSettings

You can also start actions instead of activities with am -a

am start -n com.android.settings/.TestingSettings

am start -n com.android.settings/.ActivityPicker

am start -a android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS

am start -n com.android.settings/.RadioInfo (enable 4G/LTE if radio present)

is the same result as

am start -n com.android.settings/.BandMode

am start -n com.android.settings/.ManageApplications

am start -n com.android.settings/.torchlight.TorchlightSettings

am start -n com.android.settings/.TetherSettings

am start -n com.android.settings/.wifi.hotspot.TetherWifiSettings

am start -a android.intent.action.VIEW -d http://www.google.com

am start -n com.android.phone/.callsettings.PhoneNumberLocator

Do a factory RESET with a broadcast

am start -n com.android.phone/.callsettings.CallAlert

am broadcast -a android.intent.action.MASTER_CLEAR

am start -n com.android.phone/.Settings

am start -n com.android.phone/.NetworkSetting

am start -n com.android.phone/.GsmUmtsOptions

Setting airplane mode ON/OFF

am start -n com.android.phone/.CdmaOptions

am start -n com.android.phone/.GsmUmtsCallOptions

settings put global airplane_mode_on 1

am start -n com.android.phone/.CdmaCallOptions

am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true

am start -n com.android.phone/.GsmUmtsCallForwardOptions

am start -n com.android.phone/.CellBroadcastSms

Off

am start -n com.android.phone/.AutoRejectSetting

am start -n com.android.phone/.DataUsage

settings put global airplane_mode_on 0

am start -n com.android.phone/.CallFeaturesSetting

am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false

am start -n com.android.phone/.UnlockPINLock (MT)

am start -n com.android.phone/.UnlockPUKLock (MT)

Wifi On:

am start -n com.android.phone/.UnlockSIMLock (MT)

svc wifi enable

am start -n com.android.phone/.PreferredNetworks

am start -n com.android.phone/.callsettings.AnsweringCall

am start -n com.android.phone/.RoamingAutoDialSettings (Always call to Korea, must be a Samsung option ;) )

Wifi Off:

am start -n com.android.phone/.RoamingSettings

svc wifi disable

am start -n com.android.phone/.RoamingGuard

am start -n com.android.phone/.AutomaticConnectionsSettings

Bluetooth On:

am start -n com.android.phone/.SafetyAssuranceSetting

am start -n com.android.phone/.callsettings.PhoneNumberLocator (handy !!)

service call bluetooth_manager 12

am start -n com.sec.factory/.app.ui.UIBarometer

Bluetooth Off:

am start -n com.sec.factory/.app.ui.UINFC

service call bluetooth_manager 8

am start -n com.sec.factory/.app.ui.UIOTG

am start -n com.sec.android.app.camera/.Camera

Volume Up:

am start -n com.sec.android.app.camera/.Camcorder

service call audio 1 i32 1

am start -n com.sec.android.gallery3d/.app.SlideshowDream

Volume Down:

service call audio 1 i32 -1

am start -n com.android.musicfx/.ControlPanelPicker

Car Mode On:

service call uimode 1

Try am start -a android.intent.action.MAIN for all registered activities :)

Build.prop

The /system/build.prop file houses the main system settings for Android. Leave it alone. For changing system parameters use a new file called default.prop and place it in the same folder /system. Watch for permissions and owner settings to be the same as build.prop.

To get all the current properties use the getprop command in a adb shell. You can set properties with the setprop command or of course using /system/default.prop to make them stick after a reboot.

90% of the properties are Android OS (and OS version) related, 10% manufacturer specific. There are a lot of build.prop around with a lot of BS in it. Do research before you use them.

You can find 99.9% of the variables on your device using following commands from an adb shell:

busybox find /system -exec sh -c "busybox strings {} | grep 'ro\.' | sort" \; > /sdcard/_ro_props.txt

busybox find /system -exec sh -c "busybox strings {} | grep 'persist\.' | sort" \; > /sdcard/_persist_props.txt

busybox find /system -exec sh -c "busybox strings {} | grep 'debug\.' | sort" \; > /sdcard/_debug_props.txt

busybox find /data/dalvik-cache -exec sh -c "busybox strings {} | grep 'debug\.' | sort" \; > /sdcard/_debug_props.txt

...

Found that grep -r 'debug\.' /system doesn't work very well.

Note: some persistent.x.x values are stored in the /data/property folder. Check that folder if you remove persistent variables from prop file!

Note: setting wrong values like false instead of 0 may cause boot problems. Make sure you have CWM Recovery installed

Getprop and Setprop

In a adb shell you can set and get properties mentioned above. Use getprop to list all properties of your device. Use setprop <property> <value>

to set a property. Some properties are Read Only. Usually they start with ro. and can only be set in the system.prop or default.prop. Some properties are stored in the /data/property folder and they will start with persistent. (but not all persistent. props are stored there)

Note: search all properties on your phone with this kind of command: find /system -type f -exec strings -f {} \; | grep "persist\."

busybox

You can get the latest busybox here. It should be copied to the /system/xbin folder on your device and set with the proper permissions and owner: 755 root.root and not with the sticky bit on owner (4755, same applies to sqlite3) Sticky bit on owner or groups means that everyone can run that file with elevated root permissions. That is not safe. You should first su to gain root access and then use busybox or sqlite3.

Busybox can create links for the applets itself like: /system/xbin/busybox --install -s /system/xbin

To remove all its symbolic links again use: find /system/xbin -type l -delete (assuming there are no other symbolic links in /system/xbin)

Linux RAM memory and OOM

In Android Short Overview you can find a short explanation of how the Linux kernel handles RAM memory. Basically you have two situations: a device with or without swap/paging file. Low ram devices (512MB) did popup with Android 4.4 and they use the zram swap disks (compressed RAM disk).

A swap disk is used to write memory pages (4KB) to a disk device or file to free up more RAM when needed. Since zram swap disks compress data you can extend your working RAM memory that way.

Swapping has nothing to do with caching. Linux will use a part of RAM to hold temporary data from programs or files. For me it is not clear how the kernel decides how

much RAM to use for caching. I cannot find any parameter that sets the size of the cache. Is it simply "all RAM that is not used by any program"?

An explanation of vm.swappiness is as follows. The value vm.swappiness (default 60) controls the balance between anonymous cache pages (for paging running program data) and file cache pages (requested file data, VFS). When a swap file is present vm.swappiness also controls the tendency to page out running program pages to the swap. Lower values keep programs in RAM, will only be swapped when OOM occurs.

There is a formula coded in Linux kernel that goes like this:

swappiness 0 will maximize running program data caching (causes more disk io loading files), will try to avoid swap files

swappiness 60 will balance program data and file cache

swappiness 100 will maximize requested file caching, will use swap files


With the parameter vm.vfs_cache_pressure you can manage the kernels tendency to free up file cache pages (VFS) when more RAM is needed.

The value has a default value of 100. Larger values, like 200, will cause the file cache to be shrunken quicker, thus leaving less files cached.

Example RAM allocation on device with no swap:

A short explanation:

Buffers and Cached are file related. Could be anything that is inside an APK file. These are dropped fastest (together with Inactive(file))because the can be reloaded from disk when needed again. Cached can also be paged out to swap (SwapCached)

AnonPages are non-file related program data. These are allocated on the fly when you start an APK. These can be dropped when OOM closes programs. If you have a swap device (or file) these AnonPages will be paged out to swap (if OOM/LMK did not kill them before)

Adding more swap with help of a swapfile

You can use the (mostly) ununsed /cache partition for adding extra swap storage to your device. You will have to make a swap file there and add it to swap space.

# First 2 commands only once in shell by hand (add 128MB swap)

dd if=/dev/zero of=/cache/swap.swp bs=1024 count=131072

mkswap /cache/swap.swp

swapon /cache/swap.swp

Put last line in your /etc/install-recovery.sh file since /cache file system is persistent flash partition

Check after reboot again with cat /proc/swaps or with busybox free -m

total used free shared buffers cached

Mem: 842 717 124 0 5 22

-/+ buffers/cache: 690 147

Swap: 0 0 0

In this example the total cache (vsf and anon) is 5+22 = 27 MB. Total used RAM for Android is 717-5-22 = 690 MB (see buffers/cache line)

zram

Newer kernels support zram partitions. These are dynamic compressed RAM file systems that are used for swap files (paging/caching) on mostly low RAM devices.

An example to initialize zram at startup:

echo 536870912 > /sys/block/zram0/disksize

mkswap /dev/block/zram0

swapon /dev/block/zram0 -p 32758

Note:

I have done quite some testing on low RAM phones with large apps but have found that SWAP is very sparsely used under heavy RAM situations. I even saw used SWAP shrink when started more apps simultaneously. Linux likes to reclaim cache memory first. After that OOM/LMK will kill apps before they have a chance to be paged to the SWAP device. The swappiness settings does not make very much of a difference at this point.

The only time I saw the SWAP usage grow significantly was when testing was if the device was in rest for an hour.

- Android, I want to use SWAP under heavy RAM load, not when it is in rest -

Note1: Disable Kernel Samepage Merging (KSM) since it has little memory gain and cost you battery due to constant cpu usage (about 5%)

Edit your build.prop and set :ro.config.ksm.support=false or put this in your install-recovery.sh: echo 0 > /sys/kernel/mm/ksm/run

Or change the parameters to be less aggressive:

pages_to_scan 20 and sleep_millisecs 7000 (which is default anyway without init.rc settings)

From /init.rc:

on property:ro.config.ksm.support=true

write /sys/kernel/mm/ksm/pages_to_scan 100

write /sys/kernel/mm/ksm/sleep_millisecs 500

write /sys/kernel/mm/ksm/run 1

Note2: keep an eye on the kswapd0 process (use top -m 1). It could be using very high cpu if you misconfigure memory management. This will be hours at 80% or more.

PID PR CPU% S #THR VSS RSS PCY UID Name

35 0 80% R 1 0K 0K root kswapd0

1455 0 2% S 20 384964K 91784K bg u0_a0 com.nng.igoprimoisr.javaclient

32525 0 2% R 1 1152K 424K root top

931 0 1% S 5 6016K 456K root /system/bin/mpdecision

428 1 1% S 118 503360K 77156K fg system system_server

This kswapd lock issue, causing high cpu and battery drain, will occur on devices without swap device. You can beat it by changing VM settings.

The best that worked for me was setting vm.swappiness to 10 (default 60) and don't set OOM levels low (advised: 4096,5632,8192,14336,16384,20480). Also increase vm.min_free_kbytes to at lease 2 or 3 % (at lease 4096 = 4MB).

To find last cpu usage to see kswapd (raging at 94% at least 30 seconds) use dumpsys cpuinfo

Load: 11.03 / 11.05 / 12.38

CPU usage from 58447ms to 21204ms ago:

94% 35/kswapd0: 0% user + 94% kernel

3.8% 32530/com.google.android.gm: 3.3% user + 0.5% kernel

...

0% 531/com.android.systemui: 0% user + 0% kernel / faults: 4 minor

0% 1007/thermald: 0% user + 0% kernel / faults: 95 minor

253% TOTAL: 9.8% user + 243% kernel

dumpsys batteryinfo|grep -C 1 kswapd0

Proc kswapd0:

CPU: 0ms usr + 39m 6s 0ms krn

Reset Battery statistics with: dumpsys batteryinfo --reset

If you suffer from kswapd rage you can try this solution:

echo "0,1,2,4,9,15" > /sys/module/lowmemorykiller/parameters/adj

echo "6144,8192,10240,12288,14336,16384" > /sys/module/lowmemorykiller/parameters/minfree

echo 3072 > /proc/sys/vm/min_free_kbytes # higher for smaller page cache

echo 60 > /proc/sys/vm/swappiness

See kernel source for laptop_mode and swappiness: https://github.com/torvalds/linux/blob/master/mm/vmscan.c

It worked for a problematic device I have with 3.4.0 kernel.

OOM Configuration

Every running app gets an OOM SCORE, That goes from 0 to 1000. Apps with score 1000 will be killed sooner when OOM ( Out-Of-Memory) condition occurs. OOM happens when Android cannot allocate (get) more RAM for running apps.

The apps oom_score can adjust with the oom_score_adj value. This can vary between -1000 and 1000.

The values for each app can be found in the /proc/<PID> folder in the files oom_adj, oom_score, oom_score_adj

OOM ADJ levels are functional levels from 0 to 15, -12 and -16. Running apps can have any ADJ level from 0 to 15. The higher the ADJ level, the higher the OOM SCORE. The more likely it is killed when allocatable RAM runs lower.

First we have to find the defined oom_adj levels. They can be found with the dumpsys activity oom command.

The oom_adj levels:

OOM levels:

-16: SYSTEM_ADJ

-12: PERSISTENT_PROC_ADJ

0: FOREGROUND_APP_ADJ

1: VISIBLE_APP_ADJ

2: PERCEPTIBLE_APP_ADJ

3: BACKUP_APP_ADJ

4: HEAVY_WEIGHT_APP_ADJ

5: SERVICE_ADJ

6: HOME_APP_ADJ

7: PREVIOUS_APP_ADJ

8: SERVICE_B_ADJ

9: CACHED_APP_MIN_ADJ

15: CACHED_APP_MAX_ADJ

Example with the Launcher app:

ps shows a PID of 742 (u0_a130 742 146 385412 68888 ffffffff 400c2a70 S com.anddoes.launcher)

cat /proc/742/oom_adj shows 0 (=foreground)

cat /proc/742/oom_score shows 61

Now we start another activity on the phone like System settings and the Launcher is switched to the home adj level. The oom_adj went up to 6 (=home app) and the oom_score went up to 422

To see all OOM SCORES of all apps you can use: ps -o

USER PID PPID VSIZE RSS OOM_ADJ OOM_SCORE WCHAN PC NAME

u0_a130 742 151 413800 59968 6 422 ffffffff 4020da70 S com.anddoes.launcher

Note: processes with the -16 and -12 oom_adj value will never be killed by OOM.

Changing the OOM configuration

All oom_adj are in 4Kb values, so called memory pages. For MB you will have to multiply all values with 4.

More about OOM configuration here.

First we need to find which OOM adj levels are configured. You can do that with the command:

cat /sys/module/lowmemorykiller/parameters/adj

Example for OOM adj levels configured: 0,1,2,4,9,15

Now we look at the memory threshold configured on your device with that command: /sys/module/lowmemorykiller/parameters/minfree

That will give you something like this: 3072,4546,5816,14522,16663,20480

So to complete the story the complete picture for above situation is:

0 FOREGROUND_APP 12 MB (3072x4kB)

1 VISIBLE_APP 18 MB (4546x4kB)

2 PERCEPTIBLE_APP 23 MB (5816x4kB)

3 BACKUP_APP 57 MB

4 HEAVY_WEIGHT_APP 57 MB (14522x4kB)

5 SERVICE 65 MB

6 HOME 65 MB

7 PREVIOUS_APP 65 MB

8 SERVICE_B 65 MB

9 CACHED_APP_MIN 65 MB (16663x4kB)

10 CACHED .. 80 MB

11 CACHED .. 80 MB

12 CACHED .. 80 MB

13 CACHED .. 80 MB

14 CACHED .. 80 MB

15 CACHED_APP_MAX 80 MB (20480x4kB)

All other, not listed in the adj file) oom_adj memory thresholds are copied from next listed one above.

So if you want to use all oom_adj levels (or can it be only 6 entries?):

echo "0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15" > /sys/module/lowmemorykiller/parameters/adj

echo "1024,2048,3072, ....." > /sys/module/lowmemorykiller/parameters/minfree

To check the times oom kicked in see: cat /sys/module/lowmemorykiller/parameters/oomcount

(or cat /sys/module/lowmemorykiller/parameters/lmkcount)

List all OOM values for processes with ps -o

USER PID PPID VSIZE RSS OOM_ADJ OOM_SCORE WCHAN PC NAME

root 1 0 540 376 -16 0 c013d634 000117e0 S /init

root 2 0 0 0 0 0 c00a2de0 00000000 S kthreadd

u0_a15 2506 147 358632 32692 7 449 ffffffff 401f1a70 S com.google.android.gms.feedback

u0_a39 3015 147 334812 53424 1 120 ffffffff 401f1a70 S com.google.android.tts

system 3133 147 329568 31724 2 154 ffffffff 401f1a70 S com.android.MtpApplication

Disable OOM (not advised)

Disable OOM all together (disarm it):

echo 9999 > /sys/module/lowmemorykiller/parameters/adj # OOM adj level for process to kill

echo 1 > /sys/module/lowmemorykiller/parameters/minfree # kill if free mem reaches (4kb blocks)

or simple one level OOM:

echo 4 > /sys/module/lowmemorykiller/parameters/adj # OOM level (BACKUP_APP_ADJ) process or higher to kill

echo 8192 > /sys/module/lowmemorykiller/parameters/minfree # kill if free mem reaches (4kb blocks)

There are more memory management systems these days. I know of LMK and DHA/FHA.

Tip: use Kernel Adiutor for this OOM and other Kernel stuff

Note: messing with these parameters can cause crashes or battery drain. Manufacturers know what they do settings these to the best values.

Start or stop init.rc services

In the /init.rc file there are initial services that are started at boot time. You can start or stop them. Use this command to find them:

cat /init.rc|grep service

So if you want to stop the mtpd you type: stop mtpd

If you want to stop and start the ril deamon (telephony) then: stop ril-daemon and start ril-daemon

If you want to stop Android just type stop. You can start Android again typing only start.

Note: you cannot start or stop services from apps with these commands.

Applying settings at startup (init.d)

When your device boots the kernel's /init.rc file is executed. This file is in the kernel you you cannot do easy editing on it.

Some "init.rc" services are started from this file to.

Take a close look at that /init.rc file. You will see that /system/etc/install-recovery.sh is called8 there like this:

service flash_recovery /system/etc/install-recovery.sh

class main

oneshot

Now we can create a shell script /system/etc/install-recovery.sh that executes anything you want at boot time.

#!/system/bin/sh

sysctl -w net.ipv6.conf.wlan0.disable_ipv6=1

...

etc

Of course you can put into the install-recovery script what you want. Most setprop or sysctl commands or even use it for a semi init.d mechanism.

Command you can use in the install-recovery.sh (example):

# We might need the total RAM in this script

RAM_MB=$(($(busybox awk '/MemTotal/{print $2}' /proc/meminfo)/1024))

# Misc tweaks for battery life, write back dirty cache ever 10 sec

busybox sysctl -w vm.dirty_writeback_centisecs=1000 #500

#echo "1000" > /proc/sys/vm/dirty_writeback_centisecs #500

busybox sysctl -w vm.dirty_expire_centisecs=400 #200

# Increase the read ahead for all disks (def 128, inode ext4 32)

#busybox find /sys -name read_ahead_kb -exec sh -c "echo 256 > {}" \; #128 (32*4KB blocks)

#busybox find /sys/fs/ext4 -name inode_readahead_blks -exec sh -c "echo 64 > {}" \; #32

# Decrease the read ahead for all disks (def 128, inode ext4 32) to minimize unusable dirty cache

busybox find /sys -name read_ahead_kb -exec sh -c "echo 64 > {}" \; #128 (16*4KB blocks)

busybox find /sys/fs/ext4 -name inode_readahead_blks -exec sh -c "echo 16 > {}" \; #32

# cat /proc/sys/kernel/random/entropy_avail should be > 2000

# cat /proc/sys/kernel/random/poolsize > poolsize/2=write write/2=read

busybox sysctl -w kernel.random.read_wakeup_threshold=1024 # 64

busybox sysctl -w kernel.random.write_wakeup_threshold=2048 # 128

# zram read buffer only 64KB

echo "64" > /sys/devices/virtual/block/zram0/queue/read_ahead_kb #128

busybox sysctl -w vm.min_free_kbytes=1024 #5120

busybox sysctl -w vm.swappiness=1 #60 if no swap disk/file then 0? With zram swap 100 !!

busybox sysctl -w vm.overcommit_ratio=70 #50 %RAM at expense of cache?

busybox sysctl -w vm.vfs_cache_pressure=200 #100 >100 reclaim cache more for running programs

# avc cache. Not less than "entries". Check with cat /selinux/avc/hash_stats

echo 256 > /sys/fs/selinux/avc/cache_threshold #512

# For devices with zram

if [ -f /sys/block/zram0/disksize ]; then

ZRAM=$((RAM_MB/4)) #zram is compressed, aiming at 1/4 real RAM

swapoff /dev/block/zram0

echo 1 > /sys/block/zram0/reset

sleep 2 # needed after reset!!!

echo $((ZRAM*1024*1024)) > /sys/block/zram0/disksize

mkswap /dev/block/zram0

swapon /dev/block/zram0

fi

busybox sysctl -w net.ipv6.conf.all.disable_ipv6=1 #0

# On a wifi only tablet you don't need telephone

# On a wifi only tablet you don't need telephone

if [ "$(getprop init.svc.ril-daemon)" == "running" ] && [ "$(getprop gsm.sim.operator.alpha)" == "" ]

then stop ril-daemon

fi

# list them with: cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors

echo hotplug > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

# adjust the low memory killer OOM

echo "1024,1280,4096,5120,6144,7680" > /sys/module/lowmemorykiller/parameters/minfree

sync

busybox sysctl -w vm.drop_caches=3

If you can mount rootfs as rw (mount -o remount,rw /) you can change the /init.rc file to fire any shell script without the need to flash boot.img again.

Below you find some options to put in your install-recovery.sh file

#!/system/bin/sh

logfile=/data/local/tmp/mylog.log

echo $(date) > $logfile

# disable Google Play Services for better battery

#pm disable com.google.android.gms

# We might need the total RAM in MB for this script

RAM_MB=$(($(busybox awk '/MemTotal/{print $2}' /proc/meminfo)/1024))

# check if Low mem is available first

grep LowTotal /proc/meminfo && LOW_MB=$(($(busybox awk '/LowTotal/{print $2}' /proc/meminfo)/1024))

grep LowTotal /proc/meminfo && RATIO_MB=$((100*$LOW_MB/$RAM_MB)) #Ratio > 55?

#echo $((RAM_MB*4)) > /proc/sys/vm/min_free_kbytes # official Sqrt(Memtotal*16)

echo RAM: $RAM_MB LRAM: $LOW_MB RATIO: $RATIO_MB >> $logfile

sleep 30 # wait until /etc/init.qcom.post_boot.sh (or other) script has run

### Tweaks for performance and stability

#echo 500 > /proc/sys/vm/dirty_expire_centisecs #200

#echo 1000 > /proc/sys/vm/dirty_writeback_centisecs #500 (write to disk later)

#echo 10 > /proc/sys/vm/dirty_ratio #20 %FREERAM talking kb's

#echo 2 > /proc/sys/vm/dirty_background_ratio #5 %FREERAM talking kb's

#echo 0 > /proc/sys/vm/overcommit_memory #1

#echo 60 > /proc/sys/vm/overcommit_ratio #50+swap see /proc/meminfo:CommitLimit %RAM

#echo 50 > /proc/sys/vm/swappiness #60 (0-100)

#ls /sys/fs/cgroup/memory/sw/memory.swappiness && echo 50 > /sys/fs/cgroup/memory/sw/memory.swappiness

#echo 50 > /proc/sys/vm/vfs_cache_pressure #100 (0-1000) free more page then vfs cache (kswapd)

ls /proc/sys/vm/highmem_is_dirtyable && echo 1 > /proc/sys/vm/highmem_is_dirtyable # faster I/O

ls /proc/sys/vm/extfrag_threshold && echo 100 > /proc/sys/vm/extfrag_threshold #500

# cat /proc/sys/kernel/random/entropy_avail must be > 2000

echo 128 > /proc/sys/kernel/random/read_wakeup_threshold #(64)

echo 256 > /proc/sys/kernel/random/write_wakeup_threshold #(128)

echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6 #(0)

echo 2 > /proc/sys/net/ipv4/tcp_adv_win_scale #(1)

echo 1 > /proc/sys/net/ipv4/tcp_low_latency #(0)

echo "Original oom parameters:" >> $logfile

cat /sys/module/lowmemorykiller/parameters/adj >> $logfile

cat /sys/module/lowmemorykiller/parameters/minfree >> $logfile

cat /proc/sys/vm/min_free_kbytes >> $logfile

# Valid OOM 0 to 15

# OOM levels:

# SYSTEM_ADJ: -16

# PERSISTENT_PROC_ADJ: -12

# FOREGROUND_APP_ADJ: 0

# VISIBLE_APP_ADJ: 1

# PERCEPTIBLE_APP_ADJ: 2

# HEAVY_WEIGHT_APP_ADJ: 3

# BACKUP_APP_ADJ: 4

# SERVICE_ADJ: 5

# HOME_APP_ADJ: 6

# PREVIOUS_APP_ADJ: 7

# SERVICE_B_ADJ: 8

# HIDDEN_APP_MIN_ADJ: 9

# HIDDEN_APP inbetween (aka CACHED_APP)

# HIDDEN_APP_MAX_ADJ: 15

# two settings that are overriden by some other post boot script.

# to view OOM levels: dumpsys activity oom

# OOM ADJ and SCORE with: ps -o

#echo "0,1,2,4,9,15" > /sys/module/lowmemorykiller/parameters/adj #(0,1,2,4,9,12)

#echo "6144,8192,10240,12288,14336,16384" > /sys/module/lowmemorykiller/parameters/minfree #24,32,40,48,56,64 MB

#echo 4096 > /proc/sys/vm/min_free_kbytes # higher for smaller page cache (3072)

#echo $((RAM_MB*4)) > /proc/sys/vm/min_free_kbytes # for 900MB about 3600KB

# kernel 3.4.0 assigns to little lowmem, correct lowmem watermark. See /proc/zoneinfo

uname -r|grep '3.4.0' && echo "16 16" > /proc/sys/vm/lowmem_reserve_ratio # double it

#Stop OOM, Kill processes with oom_adj value 9999 if minfree is 4kb (will never happen!)

#echo 9999 > /sys/module/lowmemorykiller/parameters/adj # OOM adj level for process

#echo 1 > /sys/module/lowmemorykiller/parameters/minfree # kill if free mem reaches (4kb blocks)

# Simple OOM kill all process with OOM ADJ level 4 or higher when free mem less than 32 MB

#echo 4 > /sys/module/lowmemorykiller/parameters/adj # OOM adj level for process (BACKUP_APP_ADJ)

#echo 8192 > /sys/module/lowmemorykiller/parameters/minfree # kill if free mem reaches 32 MB

#echo 5 > /sys/module/lowmemorykiller/parameters/debug_level #2 (0-5) write logcat killed process

#echo 64 > /sys/module/lowmemorykiller/parameters/cost #32 64 is less agressive adj

# disk read ahead buffer (def 128, inode ext4 32) (cat /proc/diskstats, find /sys -name read_ahead_kb)

# smaller read_ahead causes less dirty pages in cache

# test speed: hdparm -tT /dev/block/vold/179:33 (see mount)

busybox find /sys -name read_ahead_kb -exec sh -c "echo 64 > {}" \; #(128) (16*4KB blocks)

busybox find /sys/fs/ext4 -name inode_readahead_blks -exec sh -c "echo 16 > {}" \; #(32)

# Give netd more prio for quicker inet

busybox renice -15 $(pidof netd)

# let kswapd0 only run on CPU0 (testing)

#echo 0 > /proc/irq/$(pidof kswapd0)/smp_affinity_list

# External sdcard read_ahead from 128 KB to 256 KB (/dev/block/vold/179:33 /storage/extSdCard)

echo 256 > /sys/devices/virtual/bdi/179:32/read_ahead_kb

governor=`cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor`

echo Original governor: $governor >> $logfile

# we want hotplug or interactive, if found (return code $? is 0) set it

grep interactive /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors && governor=interactive

grep hotplug /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors && governor=hotplug

#activate the governor, will create "/sys/devices/system/cpu/cpufreq/$governor" folder

if [ $governor ]; then

chmod 644 /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

echo $governor > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

fi

case "$governor" in

"interactive")

# Interactive governor if no hotplug

echo 20000 > /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay

echo 95 > /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load #85

# echo 1209600 > /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq

echo 0 > /sys/devices/system/cpu/cpufreq/interactive/input_boost

echo 80000 > /sys/devices/system/cpu/cpufreq/interactive/min_sample_time

echo 20000 > /sys/devices/system/cpu/cpufreq/interactive/timer_rate

echo Interactive governor set >> $logfile

;;

"hotplug")

# hotplug governor

echo 30 > /sys/devices/system/cpu/cpufreq/hotplug/cpu_down_avg_times

echo 10 > /sys/devices/system/cpu/cpufreq/hotplug/cpu_down_differential

echo 0 > /sys/devices/system/cpu/cpufreq/hotplug/cpu_hotplug_disable

echo 1 > /sys/devices/system/cpu/cpufreq/hotplug/cpu_num_base

# echo 4 > /sys/devices/system/cpu/cpufreq/hotplug/cpu_num_limit

echo 10 > /sys/devices/system/cpu/cpufreq/hotplug/cpu_up_avg_times

echo 95 > /sys/devices/system/cpu/cpufreq/hotplug/cpu_up_threshold

echo 10 > /sys/devices/system/cpu/cpufreq/hotplug/down_differential

echo 0 > /sys/devices/system/cpu/cpufreq/hotplug/ignore_nice_load

echo 1 > /sys/devices/system/cpu/cpufreq/hotplug/io_is_busy

echo 0 > /sys/devices/system/cpu/cpufreq/hotplug/powersave_bias

echo 1 > /sys/devices/system/cpu/cpufreq/hotplug/sampling_down_factor

echo 80000 > /sys/devices/system/cpu/cpufreq/hotplug/sampling_rate

echo 30000 > /sys/devices/system/cpu/cpufreq/hotplug/sampling_rate_min

echo 85 > /sys/devices/system/cpu/cpufreq/hotplug/up_threshold

echo Hotplug governor set >> $logfile

;;

*)

echo Could not find Interactive or Hotplug governor >> $logfile

;;

esac

# check if we need telephone services to run on this device

baseband=`getprop ro.baseband`

echo ro.baseband property: $baseband >> $logfile

case "$baseband" in

"whatever" | "unknown") #Tablet without GSM/SIM

stop netmgrd

stop qmuxd

stop ril-daemon

esac

# Clear battery statistics at boot

dumpsys batteryinfo --reset || dumpsys batterystats --reset

### For Phone

### Disable Bandwidth restrictions (Don't use on Android 6+, traffic monitor won't work!)

setprop persist.bandwidth.enable 0

ndc bandwidth disable

### limit debug file in /data/system/dropbox

#content insert --uri content://settings/secure --bind name:s:dropbox_max_files --bind value:i:1

#content insert --uri content://settings/global --bind name:s:dropbox_max_files --bind value:i:1 (Android > 4.2)

rm /data/system/dropbox/*

### remove tombstones (crash logs)

rm /data/system/shared_prefs/*

rm /data/tombstones/*

# First 2 commands only once in shell by hand

#dd if=/dev/zero of=/cache/swap.swp bs=1024 count=131072

#mkswap /cache/swap.swp

ls /cache/swap.swp && swapon /cache/swap.swp

### sync file system, clear page cache

sync

echo 1 > /proc/sys/vm/drop_caches

echo Done >> $logfile

echo For details see $logfile

exit 0

Devices without swap disk(about 1 GB RAM):

echo 3514 > /proc/sys/vm/min_free_kbytes

echo "6144,8192,10240,12288,14336,16384" > /sys/module/lowmemorykiller/parameters/minfree #24,32,40,48,56,64 MB

For Low RAM devices with zram swap (512 MB RAM):

echo 100 > /proc/sys/vm/swappiness #(60) force to use swap

echo 100 > /sys/fs/cgroup/memory/sw/memory.swappiness

setprop sys.vm.swappiness 100

echo 2048 > /proc/sys/vm/min_free_kbytes #we have swap file so this can be low

echo "2048,4096,5120,7168,8192,12800" > /sys/module/lowmemorykiller/parameters/minfree #8,16,20,28,32,50 MB

#sysctl -w vm.extra_free_kbytes=2048 #4500

sysctl -w vm.user_reserve_kbytes=8192 #14218

sysctl -w vm.page-cluster=0 #3(8) 0=1 1=2 2=4 3=8 pages of 4 KB per read (high=laggy)

For low RAM devices (512MB) you can win some free RAM decreasing the default display cache sizes. These are based on a screen resolution of 1280x800. More info here. A 800x480 screen uses 2.6 times less memory for display cache.

For low RAM or screen resolution like 800x480 you can set caches like this in build.prop/default.prop:

#ro.hwui.fbo_cache_size=16

ro.hwui.fbo_cache_size=8

#ro.hwui.layer_cache_size=16

ro.hwui.layer_cache_size=8

#ro.hwui.texture_cache_size=24

ro.hwui.texture_cache_size=10

#ro.hwui.texture_cache_flush_rate=0.6

ro.hwui.texture_cache_flush_rate=0.2

ro.hwui.texture_cache_flushrate=0.2

A nice read on memory on Android (low RAM devices) here.

To view the current app memory usage: dumpsys meminfo

To view the linux vm memory status: cat /proc/vmstat or cat /proc/meminfo

To view the OOM situation: dumpsys activity oom

For low ram devices add more swap with help of /cache/swap.swp like described earlier.

Storage Speed Test

You can test the read speed of your NAND and sdcard with the busybox hdparm utility. Use mount to find the storage devices.

/dev/block/vold/179:33 /storage/extSdCard vfat rw,dirsync,no

Then test for cached and direct read mode speeds:

hdparm -tT /dev/block/vold/179:33

/dev/block/vold/179:33:

Timing buffer-cache reads: 360 MB in 0.51 seconds = 721924 kB/s

Timing buffered disk reads: 53 MB in 3.00 seconds = 18062 kB/s

dumpsys command

dumpsys -l list all the possible services you can use with dumpsys command. (user, not root)

With every service found (see examples below) you can use the -h option: dumpsys activity -h

activity [activities] [broadcasts] [oom] [permissions] [providers] [services]

battery

content (like system/global/secure settings)

deviceidle

package l[ibraries] f[eatures] perm[issions] pref[erred]

window

dumpsys activity services | grep ServiceRecord # get all running package services

Using dumpsys to fake battery status:

dumpsys battery info

dumpsys battery level 5 # fake battery level

dumpsys battery usb 0 # disable charging

dumpsys battery reset # back to reality

Using dumpsys to force deviceidle ("app doze mode"):

dumpsys deviceidle enabled # ask if "app doze mode" is enabled

dumpsys deviceidle enable all # Nougat, mLightEnabled=true mDeepEnabled=true

dumpsys deviceidle disable light # Nougat, disable only light doze mode

dumpsys deviceidle disable

dumpsys deviceidle force-idle

dumpsys deviceidle whitelist

dumpsys deviceidle step deep # Nougat, activate deep doze

dumpsys package com.android.systemui # list all activities, intents broadcasts, permissions and services fro that package

dumpsys statusbar # list all possible icons on statusbar

dumpsys sensorservice # list of all devices sensors

dumpsys usb -h <..> # emulate usb port functions

dumpsys power # list all power related setting

dumpsys uimode # list twilight mode, sunrise sunset :)

dumpsys deviceidle # list device Doze variables and state

dumpsys deviceidle force-idle # Force device Doze

Etc...

sysctl command

Other more kernel (unix) related variables can be set using sysctl command from the adb shell or by a shell script. If you have a rooted device you have busybox installed. One of the busybox applets is sysctl. If busybox is installed properly you can type sysctl in an adb shell.

With sysctl -a you get all the current values. You can set values with sysctl -w <name>=<value>

Examples:

sysctl -w net.ipv6.conf.wlan0.disable_ipv6=1

sysctl -w net.ipv4.tcp_app_win=44

sysctl -w net.ipv4.tcp_mtu_probing=1

sysctl -w net.ipv4.tcp_wmem="4096 16384 404480"

All sysctl variables have files with their value in it. Alternatively to the sysctl -w command you can use echo to change them too. The values are all stored under the /proc/sys/ folder.

Example: echo 1 > /proc/sys/net/ipv4/tcp_mtu_probing

svc command

From the shell or in a script you can use the svc command to control some states: power, 3G, wifi and usb

Available commands:

help Show information about the subcommands

power Control the power manager

data Control mobile data connectivity

wifi Control the Wi-Fi manager

usb Control Usb state

nfc Control NFC functions

svc wifi enable - turn on wifi

svc wifi prefer - prefer wifi data over 3G

svc usb getFunction - see how usb is connected

svc usb setFunction mtp,mass_storage,adb - change usb mode, cat /init.usb.rc | grep 'sys.usb.config='

Android's settings db

Android uses a lot of SQLite3 databases to store settings. Much Android apps use a SQLite db. Also Android itself. The most important settings of Android can be found in the settings secure and the system tables of the database, and global table since Android 4.x

Settings and the table name where they are stored vary per Android version and API/SDK level. Some settings are depreciated, others move from the system to the global table when API levels (Android versions/SDK) go up.

Get your API level: adb shell getprop ro.build.version.sdk

Googles documentation on the settings:

Most of the settings can be found if you decompile framework.jar and framework2.jar

content query --uri content://settings/system --sort "name ASC"

content query --uri content://settings/secure --sort "name ASC"

content query --uri content://settings/global --sort "name ASC"

content query --uri content://settings/secure --where "name like 'wifi%'"

content insert --uri content://settings/secure --bind name:s:wifi_idle_ms --bind value:i:60000

content insert --uri content://settings/secure --bind name:s:dropbox_max_files --bind value:i:1

or for Android 4.2+

content insert --uri content://settings/global --bind name:s:wifi_idle_ms --bind value:i:60000

content insert --uri content://settings/global --bind name:s:dropbox_max_files --bind value:i:1

content insert --uri content://settings/system --bind name:s:auto_toast_count --bind value:i:1

content update --uri content://com.anddoes.launcher.settings/favorites --where "title='Maps'" --bind title:s:'Google Maps'

content insert --uri content://settings/secure --bind name:s:default_input_method --bind value:s:com.sec.android.inputmethod/.SamsungKeypad

Note: be very careful with these commands. Use insert instead of update. The databases may be lost or emptied if you do it wrong. Make backup first!

Example tracing a value found in content://settings/system (check system for your Android version first)

content query --uri content://settings/system | grep with_circle

>> Row: 403 _id=59333, name=with_circle, value=0

busybox find /system -exec sh -c "busybox strings -f {} | grep 'with_circle' " \;

>> /system/framework/framework.odex: with_circle

Another way of setting wifi_idle_ms is to use the settings command.

settings put global wifi_idle_ms 300000

settings get global wifi_idle_ms

settings put secure wifi_watchdog_on 0

settings put secure wifi_watchdog_poor_network_test_enabled 0

settings put secure sysui_qs_tiles wifi,bt,inversion,cell,airplane,rotation,flashlight,readmode,location,cast,hotspot,remotewindow,hotknot,audioprofile,dataconnection,simdataconnection,dulsimsettings,apnsettings

settings put secure sysui_qs_tiles default

settings delete secure sysui_qs_tiles

settings put system screen_brightness_mode 0

settings put system screen_auto_brightness_adj 0

settings put secure display_density_forced 340

settings put secure lock_screen_show_notifications 1

settings put secure lock_screen_allow_private_notifications 1

settings put secure lock_screen_owner_info "If lost please contact Tweakradje at gmail dot com"

settings put global zen_mode 1 # don't disturb mode

settings put global heads_up_notifications_enabled 1 # big notification toast at top of screen

settings put global heads_up_snooze_length_ms 2000

settings put global add_users_when_locked 0 # not very secure to switch this on

settings put global dropbox_max_files 1 # reduce nr crash files in /data/system/dropbox to 1

settings put secure location_providers_allowed +gps # add gps option to existing values

settings put secure location_providers_allowed -gps # remove gps option to existing values

(Android 6+)

settings list system

settings list secure

settings list global

From Android 6 (MarshMallow) these settings have moved from a sqlite3 db to xml files, located at /data/system/users/0/settings_system.xml, settings_secure.xml and settings_global.xml

To get all LIVE monitored settings values you can use this dumpsys content:

dumpsys content | grep settings/ | sort

settings/global/HIC_enable: pid=2044 uid=10031 user=-1 target=3df1a5c

settings/global/adb_always_notify: pid=1739 uid=1000 user=0 target=eb5ce2c

settings/global/adb_enabled: pid=1739 uid=1000 user=0 target=44061df

settings/global/add_users_when_locked: pid=2044 uid=10031 user=0 target=2377dd5

To get all settings used in the ROM:

dumpsys activity provider all > /sdcard/_ALL_SETTINGS.TXT (up to Android 7)

dumpsys settings > /sdcard/_ALL_SETTINGS.TXT (from Android 7)

Or use from Windows command line: adb bugreport > bugreport.txt

adb over wifi

You can use adb over wifi too. Here is how.

  • adb shell

  • su

  • setprop service.adb.tcp.port 5555

  • stop adbd

  • in Developer Options untick and tick USB debugging, that will start adb daemon again

On your pc now type: adb connect <ip of your device>

Note: It is not wise to put service.adb.tcp.port in your default.prop or build.prop as it opens a permanent hole for hackers.

Trim Flash storage cells

You device stores info in Flash Memory. Like SSD disks do. These memory cells can only be used for writing X times. So they are protected and switched off when they have been released to be rewritten, like a file has been deleted. This to protect them from being written to many times.

After a month or so you can make them available again for storage (trimming). Use the fstrim command for that.

busybox fstrim -s /data

busybox fstrim -s /system

busybox fstrim -s /cache

Handy Linux commands

To get your way around Linux these command come in handy. For the correct syntax just type the command. With 20% of all the linux commands you can do 80% of the work.

cd <a folder> - change directory, example: cd /etc

ls <options> <pattern> - list a folders content, example: ls -l *.prop

cat <files> - show content of <files>, example: cat /init.rc Create file: cat > file1.txt Add to file: cat >> file1.txt then enter multi line text and close with CTRL+\ Z

cp <options> <source> <destination> - copy files or folders, example: cp /sdcard/install-recovery.sh /etc

rm <options> <files> - remove a file or folder, example: rm /data/dalvik*/*

echo <sometext> - print <sometext> on the screen, example: echo $? which print last command errorlevel

grep <options> <pattern> <files> - find content in <files>, example: grep -ir 'debug\.' *

chown <owner>.<group> <files> - user 0 and group 0 is root, example: chown 0.0 *.sh

chmod <-R> <pattern> <files> - pattern is 3 bytes: owner group world, like 755, r=4 w=2 x=1 for each byte, example: chmod 755 *.sh

find -type f -exec chmod 644 {} \; change all file permissions to rw-r--r--

find -type d -exec chmod 755 {} \; change all directory permissions to rwxr-xr-x

find <from> <options> <pattern> - find files but very powerfull, example: find / -name '*prop' -exec cat {} \;

lsmod - list loaded modules/drivers (list them with ls -l /system/lib/modules)

insmod <filename.ko> - load a module/driver, example: insmod /system/lib/modules/ath6kl_sdio

rmmod <module> - unload module, example: rmmod ath6kl_sdio

modinfo <filename> - get all the info for that module

ps - process status gives you a list of what is running on your system

(renice <prio> <pid> - change priority of a running process)

top <options> - shows the processes that use the most cpu, example: top -n 1 -m 10

mount <options> - connects a block device to a folder, example: mount -o remount,rw /system

ln <-s> <source> <destination> - make links in the file system, example: ln -s /system/etc /etc

df <folder> - disk free shows amount of free bytes of mounted block devices, example: df /system

du <options> <folder> - disk usage shows amount of used bytes of a folder, example: du -k -s /system

sync - write cache to disk (called dirty cache)

reboot - reboot the device

while ! pidof com.android.settings ; do sleep 1 ; done - wait for android settings db

while ! pidof com.android.systemui ; do sleep 1 ; done - wait for android GUI

BRIGHTNESS="$(cat /sys/class/leds/lcd-backlight/brightness)" - put output of command into variable

date -d @1611321304 #convert Linux epoch date (secs since 1-1-1970) to readable format, don't use last 3 numbers

...

Android has a stripped down version of busybox called toolbox. You can find the commands with ls -l /system/bin and see links "-> toolbox"

Busybox adds loads of commands to this list. Type busybox to list all commands. You can run these commands by typing busybox <command>

Then you can use output redirection and piping. Some examples:

echo 1000 > /proc/sys/vm/dirty_writeback_centisecs

cat /system/build.prop | grep -i 'ro\.'

One beautiful example of the find command. Change the owner and group on only folders in the /system folder

busybox find /system -type d -maxdepth 1 -exec chown root.root {} \;

Or on every single file starting with the /system folder:

busybox find /system -type f -exec chown root.root {} \;

Or find all files called read_ahead_kb beginning at the /sys folder and echo 256 into them:

busybox find /sys -name read_ahead_kb -exec sh -c "echo 256 > {}" \;

Use text from clipboard to fill a_file via terminal:

    • cat > a_file

    • paste the text from the clipboard

    • press Ctrl+D

or cat >> a_file to append clipboard text to an existing file

Search *.odex file for content "ro.": find / -type f -exec strings -f {} \; | grep "ro\."

Mass rename files, for example *.*.ORG into *.*: for f in *.ORG; do mv "$f" "${f%.ORG}"; done

or rename *.* into *.*.ORG: for f in *; do mv "$f" "${f}.ORG"; done

Network info

This will show you commands to get info about your network cards and ip/mac adresses, routing, live connectios etc. This is all done from the adb shell.

First you want to know which network cards you have in your device: netcfg

netcfg

rmnet0 DOWN 178.225.239.54/30 0x00000000 00:00:00:00:00:00

rmnet1 DOWN 0.0.0.0/0 0x00000000 00:00:00:00:00:00

.....

ip6tnl0 DOWN 0.0.0.0/0 0x00000080 00:00:00:00:00:00

lo UP 127.0.0.1/8 0x00000049 00:00:00:00:00:00

sit0 DOWN 0.0.0.0/0 0x00000080 00:00:00:00:00:00

p2p0 UP 0.0.0.0/0 0x00001003 e6:40:e2:57:36:6b

wlan0 UP 10.0.0.138/24 0x00001043 e4:40:e2:57:36:6b

or ip addr or ip link

ip addr

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN

link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

inet 127.0.0.1/8 scope host lo

inet6 ::1/128 scope host

valid_lft forever preferred_lft forever

2: rmnet0: <> mtu 1500 qdisc pfifo_fast state DOWN qlen 1000

link/[530]

inet 178.225.239.54/30 scope global rmnet0

.....

16: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000

link/ether e4:40:e2:57:36:6b brd ff:ff:ff:ff:ff:ff

inet 10.0.0.138/24 brd 10.0.0.255 scope global wlan0

inet6 fe80::e640:e2ff:fe57:366b/64 scope link

valid_lft forever preferred_lft forever

17: p2p0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN qlen 1000

link/ether e6:40:e2:57:36:6b brd ff:ff:ff:ff:ff:ff

With the command netstat you will get all live network connections. To see all network traffic bytes since boot use dumpsys netstats

If you have a rooted device you can disable the bandwidth limit with setprop persist.bandwidth.enable 0 or temporarily with ndc bandwidth disable

Powerrrrrr...and CPU's

Android like any other OS runs on the cpu. As time goes by the number of cpu cores grow. Now we are on quad cores. That means you have 4 cpu's packed in one chip. To have so much cpu power has a downside on a phone or tablet: huge power consumption so short battery life.

Cpu's therefore have a few tricks to reduce power consumption:

  • reduce the cpu frequency

  • switch on or off extra cpu's

  • voltage control

The process that regulates those things (scaling) to happen is called the governor. Simply put: more cpu cores and more Mhz if you need it.

Android has a few of those governors built in. You can find them for your device in the kernel file:

/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors

ondemand userspace powersave hotplug performance

The current governor can be found in this file: /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

For multiple core cpu's on phone and tablet it is advised to use the hotplug governor. Also if you have multiple cpu's only the cpu0 cpufreq files are used.

If you use other governors you can also switch cores on or off and set the max core speed like this:

echo 1 > /sys/devices/system/cpu/cpu1/online

echo 1 > /sys/devices/system/cpu/cpu2/online

echo 1 > /sys/devices/system/cpu/cpu3/online

echo 1508000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq

But you cannot set any speed for your cpu cores. The speeds allowed are fixed in this file: /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies

1508000 1404000 1300000 1209000 988000 754000 497250

To monitor your cpu in real time you can use this program called PerfMon by ChainFire. To manage your governor you can use programs like NSTools or No-frills CPU Control.

When your device turn off the screen it usually goes into the Deep Sleep state. If it doesn't then something is very wrong. Most common is that some process keeps the data connection on continuously. You can check the cpu state history with CPU Spy or No-frills CPU Control (in settings add Deep Sleep).

There are many "Battery Savers" in the store. Most switch off Wifi and 3G/2G/Radio at given times, kill tasks that run or even lower the CPU frequency while the screen is off. I cannot recommend any of them but I have tried a few. Most use more power then they save. Below I will name a few.

Deep Sleep Battery Saver has a different approach then other battery savers. It will force running processes to stop (go into deep sleep) and wakes them up at given intervals. In the free version you cannot set much but for most users it will do.

Night Battery Saver and Timed Toggles just switch off your data connections during a given period. Very simple and effective.

The GPU

Beside de cpu(s) Android devices also have a GPU for processing graphics, hardware encoding/decoding video, OpenGL, etc.

Default the Android GUI (like Home Launcher) use the cpu to render it. If you have enabled the Development Options you can set the GPU to to that for you. Force GPU for 2D in all applications.

You can also set it in /system/default.prop (don't use system.prop)

debug.sf.hw=1

persist.sys.ui.hw=1

persist.sys.composition.type=gpu

The Surface Flinger

On Android there is a part that takes care of the GUI graphics when you scroll or swipe on the screen. It is called the Surface Flinger.

You can set some properties to make it behave to your liking. My preferred settings that can be set in /system/build.prop or better in /system/default.prop are:

debug.sf.hw=1

# Surface flinger 1.0 2.0 4000

ro.fling.distance.coef=2.0

ro.fling.duration.coef=3.0

ro.max.fling_velocity=3000

Package Manager from the command line

The binary for installing and managing packages (apk's) is simply called pm. pm is very useful and can do things you can't from the gui.

Some usage info:

pm list packages

pm list features

pm list libraries

pm path PACKAGE

pm dump PACKAGE

pm install ANY.APK

pm uninstall [-k] PACKAGE

pm clear PACKAGE

pm enable PACKAGE_OR_COMPONENT

pm disable PACKAGE_OR_COMPONENT

pm block PACKAGE_OR_COMPONENT

pm unblock PACKAGE_OR_COMPONENT

pm grant PACKAGE PERMISSION

pm revoke PACKAGE PERMISSION

pm set-install-location [0/auto] [1/internal] [2/external]

pm get-install-location

for p in `pm list packages -d -u` ; do pm clear ${p/package:/} ; done #clear data for every disabled package

pm install /sdcard/whatsapp.apk installs WhatsApp on your device.

pm list packages |grep whats shows package:com.whatsapp

pm list packages -d -f shows all disabled packages with apk path

cd /data/data && for d in * ; do pm list package $d ; done || rm -r $d

pm path com.whatsapp shows package:/data/app/com.whatsapp-1.apk

pm dump com.whatsapp shows all info about whatsapp

pm disable com.whatsapp disables WhatsApp

pm disable com.google.android.youtube disables Youtube (which is a system app, cannot be done by GUI)

pm enable com.whatsapp

pm disable radiotime.player/tunein.player.pro.FordReceiver disable the action for BT changed in TuneIn Radio

To remove all data from disabled packages:

for p in $(pm list packages -d) ; do echo $p | busybox awk -F ':' '{print "/data/data/" $2}' | xargs rm -r ; done

To disable all Samsung Knox packages:

for p in $(pm list packages |grep nox) ; do echo $p | busybox awk -F ":" '{print $2}' | xargs pm disable ; done

To remove all Samsung Knox packages:

for p in $(pm list packages -f|grep nox) ; do echo $p | busybox awk -F "/" '{print "/"$2"/"$3"/"$4}' | xargs rm -r ; done

On newer version of Android you need to use pm disable-user <packagename> to disable an app. Also even newer versions you use block to completely disable an app.

pm list packages to find all packages installed

package:com.android.defcontainer

package:com.sec.phone

package:com.android.providers.partnerbookmarks

package:com.android.contacts

package:com.sec.android.gallery3d

package:com.android.phone

...

The administration files for packages can be found in /data/system with packages.list and packages.xml

cat packages.list|grep -i download

com.android.providers.downloads.ui 10022 0 /data/data/com.android.providers.downloads.ui default 1028,1015,1023,1024

com.android.providers.downloads 10022 0 /data/data/com.android.providers.downloads default 1028,1015,1023,1024

cat packages.xml|grep -i download

<package name="com.android.providers.downloads.ui" codePath="/system/app/SecDownloadProviderUi.apk" nativeLibraryPath="/data/app-lib/SecDownloadProviderUi" flags="573125" ft="14e8ffd5870" it="14b96292d80" ut="14e8ffd5870" version="19" sharedUserId="10022">

<package name="com.android.providers.downloads" codePath="/system/priv-app/SecDownloadProvider.apk" nativeLibraryPath="/data/app-lib/SecDownloadProvider" flags="1074314949" ft="14e8ffd5c58" it="14b96293168" ut="14e8ffd5c58" version="19" sharedUserId="10022">

Disabled packages administration is stored per user. This store is in the /data/system/users/<user_nr>/package-restrictions.xml file.

Install apk packages from the PC with Right Click on apk:

[HKEY_CLASSES_ROOT\apk_auto_file\shell\Install\command]

@="cmd /c \"\"C:\\windows\\adb.exe\" install -r \"%1\" & TimeOut 10\""

Which sould read in the registry: cmd /c ""C:\windows\adb.exe" install -r "%1" & TimeOut 10"

To disable a service from a package. For example the wallpaper service:

dumpsys activity | grep ServiceRecord | grep ImageWallpaper

pm disable com.android.systemui/.ImageWallpaper

pm enable com.android.systemui/.ImageWallpaper

The netd daemon

All network is controlled by the netd daemon and its command interface ndc.

ndc bandwidth

ndc clatd

ndc dualon

ndc firewall

ndc idletimer

ndc interface

ndc ipfwd

ndc ipv6fwd

ndc list_ttys

ndc nat

ndc netinfo

ndc network

ndc pan

ndc pppd

ndc pppoectl

ndc resolver

ndc route

ndc rtsol

ndc softap

ndc tether

ndc IPv6Tether

ndc throughput

An example to switch of bandwidth management: ndc bandwidth disable

iptables firewall

There is a firewall onboard. Android uses the linux iptables firewall. The ruleset can not be loaded from /etc/iptables or whatever. It is built into the kernel. But you can add your own rules or whatever by a shell script like /etc/install-recover.sh else you loose your own rules after a reboot. Btw: iptables need root

There are three tables to manage that you can address with the -t option. Default you manage the filter table. But there is filter, nat, mangle, raw and security(?).

A few command you need to know:

  • iptables -S list the current rules syntax of all chains, can be used in a shell script like that

  • iptables -L -n -v lists the current rules with ip numbers and actual data usage

  • iptables -h help

The default rules are created by the /system/bin/netd daemon using the ndc firewall shell command.

Use the ndc firewall enable or disable command to turn it on or off.

There are several Firewalls in the playstore that use iptables. Droidwall is the mother of them all. AFWall+ continued development as did Avast Antivirus and Security.

Like Droidwall they only cover the App data traffic on your Wifi and 3G network. AFWall+, like Droidwall, offers the possibility to add your own advanced iptables commands in a script.

Example to log and monitor outgoing connections for applications (UID):

iptables -I OUTPUT 1 -j LOG --log-prefix "[IPT OUT START] " --log-level 4 --log-uid (Insert in chain OUTPUT as rulenum)

iptables -A OUTPUT -j LOG --log-prefix "[IPT OUT END] " --log-level 4 --log-uid (Append to chain OUTPUT)

Then if you view the ruleset you will see this:

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)

pkts bytes target prot opt in out source destination

0 0 LOG all -- * * 0.0.0.0/0 0.0.0.0/0 LOG flags 8 level 4 prefix "[IPT OUT START] "

0 0 LOG all -- * * 0.0.0.0/0 0.0.0.0/0 LOG flags 8 level 4 prefix "[IPT OUT START] "

8648 1087K bw_OUTPUT all -- * * 0.0.0.0/0 0.0.0.0/0

0 0 LOG all -- * * 0.0.0.0/0 0.0.0.0/0 LOG flags 8 level 4 prefix "[IPT OUT END] "

0 0 LOG all -- * * 0.0.0.0/0 0.0.0.0/0 LOG flags 8 level 4 prefix "[IPT OUT END] "

View logging with the command: fgrep '[IPT OUT ' /proc/kmsg or grep '\[IPT OUT ' /proc/kmsg or for a oneshot dmesg | grep '\[IPT OUT '

<4>[28158.336077] c0 [IPT OUT START] IN= OUT=wlan0 SRC=10.0.0.138 DST=74.125.206.139 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=27906 DF PROTO=TCP SPT=35042 DPT=80 WINDOW=14600 RES=0x00 SYN URGP=0 UID=10021 GID=10021

<4>[28158.336380] c0 [IPT OUT START] IN= OUT=wlan0 SRC=10.0.0.138 DST=74.125.206.139 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=27906 DF PROTO=TCP SPT=35042 DPT=80 WINDOW=14600 RES=0x00 SYN URGP=0 UID=10021 GID=10021

You find the applications UID with the quickest with the command: cat /data/system/packages.list|grep 10021

To remove the rules again to stop logging, list the rules with iptables -S and then

iptables -D OUTPUT -j LOG --log-prefix "[IPT OUT START] " --log-uid

iptables -D OUTPUT -j LOG --log-prefix "[IPT OUT END] " --log-uid

or simply reboot your device.

To block a Domain: iptables -A OUTPUT -p tcp -m string --string "a_domain.com" --algo kmp -j REJECT --reject-with icmp-host-unreachable

Use iptables -s nat <any command> to manage the nat table. For listing the rules it becomes iptables -t nat -S

For oem there is the /system/bin/oem-iptables-init.sh file.

Battery level in task bar

For Android lower than 4.4 in adb shell

content insert --uri content://settings/system --bind name:s:display_battery_level --bind value:i:1

content insert --uri content://settings/system --bind name:s:display_battery_percentage --bind value:i:1

For Android 4.4+:

content insert --uri content://settings/system --bind name:s:status_bar_show_battery_percent --bind value:i:1 #inside battery icon

content insert --uri content://settings/system --bind name:s:status_bar_show_battery_percent --bind value:i:2 #outside battery icon

settings put system status_bar_show_battery_percent 1

stop

reboot

Selecting another Radio Band on your Phone

Modern phones can work in all countries arround the world. So Phones support a lot of Radio frequencies (Bands) and protocols.

Most Phones will figure it out themselves. Sometimes you want to fix your Phone to a proper frequency.

GSM 800/850/900/1700/1900/2100MHz

WCDMA 800/850/900/1700/1900/2100MHz

You need adb.exe again. Start a cmd shell in Windows and connect with adb using:

    • adb shell

    • am start -n com.android.settings/.BandMode

...or on most Samsungs you can Dial *#2263# or on other phones *#*#4636#*#* Select "Phone Information" then "Select Radio Band"

Select the proper Band for your country, or Automatic.

You can check (on Samsung at least) your current Radio connection when dialing *#0011#

CSC on Samsung devices

Samsung adds or removes features with CSC function. This consists of various parts:

/system/CSCVersion.txt (the complete csc zip file)

/system/SW_Configuration.xml

/system/csc (folder with CSCVerstion.txt content)

...

PEH

common

contents.db

customer.xml

language.xml

others.xml

sales_code.dat

In customer.xml and others.xml you can add many options.

GPS with supl

Although there is a /etc/gps.conf file my Samsung device don't do AGPS with any of the options there. It is restricted to certain customers by CSC. To get AGPS you can do the following.

Edit the /system/csc/customer.xml file with Notepad++ (-rw-r--r-- root root 17337 2016-01-26 23:40 customer.xml):

<CustomerData>

<GeneralInfo>

...

</GeneralInfo>

<Settings>

<GPS>

<!-- GPSActivation>gpsActivation</GPSActivation -->

<AGPS>

<ServAddr>supl.nokia.com</ServAddr>

<Port>7275</Port>

<SuplVer>2</SuplVer>

<TLS>1</TLS>

</AGPS>

</GPS>

<Main>

Save it and copy it back to the /system/csc folder. Make sure the permission are correct (like above). Reboot your device.

After reboot check if the settings are applied with: logcat -d|grep -i csc

You should see:

D/CscGPS ( 736): CSCGPS.updateParameters

D/CscGPS ( 736): supl host : supl.nokia.com

D/CscGPS ( 736): supl_ver : 1

D/CscGPS ( 736): supl port : 7275

D/CscGPS ( 736): CSCGPS.GPSUpdate

High quality audio over Bluetooth (bluez stack)

For devices using the (older) Bluez bleutooth stack you can pump up the bluetooth audio quality. You need to change 2 files in the /etc/bluetooth folder.

main.conf

[General]

#DisablePlugins = network,input

Name = %m

Class = 0x40020C

DiscoverableTimeout = 120

PairableTimeout = 180

PageTimeout = 8192

DiscoverSchedulerInterval = 3600

InitiallyPowered = true

RememberPowered = false

DeviceID = 0075:100:100 (keep your device id here)

ReverseServiceDiscovery = true

NameResolving = true

DebugKeys = false

EnableLE = true

AttributeServer = false

DefaultLinkPolicy = 15

audio.conf

[General]

Enable=Sink,Control

#Disable=Headset,Gateway,Source

Master=false

SCORouting=HCI

AutoConnect=true

[Headset]

HFP=true

MaxConnections=2

MaxConnected=2

FastConnectable=true

[A2DP]

APTXSources=1

MPEG12Sources=1

SBCSources=1

SBCQuality=HIGH

APTXSinks=1

SBCSinks=1

MPEG12Sinks=1

#DelayReporting=

[AVRCP]

InputDeviceName=AVRCP

MetaDataEnable=true

[WBspeech]

WBSEnable = true

I2sEnable = 0x01

IsMaster = 0x00

ClockRate = 0x02

PcmInterfaceRate = 0x00

For MediaTek (blueangel stack) there is a configuration embedded in the /system/lib/libbtcusttable.so file.

Android Bluedroid has a config file in /data/misc/bluedroid/bt_config.xml

Increase Google Maps Offline refresh time

You need a rooted device and a SQLite editor. With SQLite goto the Maps app and select the gmm_offline-<nubmer>.db database. Select the offlineRegions table. You will see the World (Global Data) and your own offline regions records. Long click the expirationTimeMs field and select Edit Field.

Change the value from 1450382334427 to 9450382334427 milliseconds for all records. Exit SQLite editor.

If you now start Maps and goto offline regions you will see an expiration date of 92620 days instead of 30 days. If you download new regions this will be reset!

Add neko tile

cmd statusbar add-tile com.android.egg/.neko.NekoTile


....