text:
How to disable dm-verity on Android with "user" build type ROM?
I have One Plus 6T Android device which has a ROM of build type user. This device is rooted with Magisk and I want to disable dm-verity on this device. I have tried to run adb disable-verity but I got an error saying verity cannot be disabled/enabled - USER build
Is there any way to disable this?
Goal: Want to place customized sepolicy file under system_root directory. I have tried to do it with following commands:
C:\Users\GPU-Test>adb shell
OnePlus6T:/ $ su
OnePlus6T:/ # mount -o rw,remount /system_root
OnePlus6T:/ # cp /sdcard/selinux_policy_modified /system_root/sepolicy
cp: /system_root/sepolicy: Permission denied
1|OnePlus6T:/ # cp -f /sdcard/selinux_policy_modified /system_root/sepolicy
cp: /system_root/sepolicy: No such file or directory
1|OnePlus6T:/ # ^C
130|OnePlus6T:/ # exit
130|OnePlus6T:/ $ exit

C:\Users\GPU-Test>adb disable-verity
verity cannot be disabled/enabled - USER build

Also tried to disable Preserve force encryption and Preserve AVB 2.0/dm-verity checkbox but still the above commands have same result. Also on reboot these check-boxes enables again automatically.

can you please be more specific what your question is targeting, because usually you have already patched your device against dm-verity (Magisk Manager has a checkbox for)?

I have added more detail regarding why I want to do this and what I have tried.

why not use / instead of /system_root?

@alecxs on system-as-root devices Magisk mounts recovery ramdisk at /, not system partition. / is volatile filesystem.

@IrfanLatif thanks, "recovery" was the missing piece! Now this article makes sense to me "Magisk mounts system to ‘/system_root’ and bind mount ‘/system_root/system’ to ‘/system.’ " https://www.xda-developers.com/magisk-google-pixel-3-pixel-3a-android-q

@alecxs with Q things have again changed. Now system partition will be monuted at / but the files to be modified/added (e.g. init, init.rc, /sbin) will be overlaid using bind mounts. In each case target is to be system-less and detection-less.

I think I need to place sepolicy file directly into system.img and then flash it via fastboot system system.img command. I have tried lots of tutorial-like https://www.china-devices.com/forum/index.php?threads/how-to-properly-unpack-and-repack-android-system-img-for-sp-flash-tool.18739/ but I get an error like "Invalid sparse file format at header magi \n Failed to read sparse file
". I think these all tutorial are deprecated for new android images. Do you guys have any idea about any tool that can extract system.img?

@VatishSharma modifying system.img isn't a big deal but it makes no difference. Device won't boot with modified system.img if dm-verity is enabled. Let me write answer for you what you can try to disable dm-verity.

I'm going to give a general overview of how dm-verity and related things work on Android according to my limited knowledge. Situation might differ on different devices and ROMs.
HOW IS DM-VERITY ENFORCED?
dm-verity (Verified Boot and AVB) as well as dm-crypt (FDE) are targets of device-mapper feature of Linux kernel. dm-verity verifies the integrity of each block as they are read from block device; enforced by init_first_stage as per fs_mgr_flags set in fstab (1). On system-as-root devices (A/B and non-A/B), kernel is patched to force verity while mounting /system and /vendor if verify/avb flags are found in fstab device tree (dtb).
dm-crypt decrypts/encrypts data transparently when read/written from/to block device. FBE is based on a different kernel framework fscrypt; but both are managed by vold (which runs as a native service) if fs_mgr_flags contain voldmanaged.
WHERE FSTAB IS?
fstab has traditionally been a file on Linux to specify filesystems to be mounted on boot. It's a core component of fs_mgr functionality on Android.
On pre-Oreo releases fstab was in ramdisk. With Treble it was moved to /vendor (or /system/vendor) while the fstab entries for system and vendor (and odm) are moved to Device Tree Blob (dtb). Kernel exports dtb fstab entries in device tree directory at /proc/device-tree/firmware/android.
Some OEMs also put fstab in odm or nvdata partitions.
Source: Android Storage Device Configuration
WHERE DTB IS?
Device Tree is a data structure for describing hardware which is not discoverable to kernel. Device Tree Source (dts) can be converted to dtb (binary blob of DT) and vice versa using dtc. DTB is loaded by bootloader at boot time and passed to kernel so that it can discover hardware and create device nodes accordingly.
DTB is either:

Appended to kernel zImage or Image.gz in boot.img (2). It can be split from gzip archive using split-appended-dtb (sadtb).
Or in dtbo partition as some OEMs do. This can be checked with:
~# ls -l /dev/block/bootdevice/by-name/dtbo*
~# grep -C5 PARTNAME=dtbo /sys/dev/block/*/uevent | grep DEVNAME | sed 's/.*=//; s|^|/dev/block/&|'

Or at the end of boot.img after 2nd stage, or in odm partition (rare, some OEMs do).

Also if the device is non-A/B, dtb (from boot.img and/or dtbo partition) is also added to recovery.img in DTBO section after header, kernel, ramdisk and 2nd stage (3). However this doesn't matter for normal boot. But if the device is also system-as-root, Magisk needs to be installed in this recovery partition as the boot.img contains no ramdisk (4).
In case if DTB is not appended to kernel, dtb(s) are converted to dtb.img using mkdtimg. Same tool can dump back the image.
Source: Implementing DTO
HOW TO DISABLE DM-VERITY?
On userdebug ROMs, dm-verity can be disabled using adb. It modifies magic number of verity metadata block (5, 6) which is written after the last filesystem block on block device (system or vendor) (7). Quoted from here:

the absence of this magic number will halt the verification process

In case of AVB, adb modifies vbmeta header to disable hashtree image verification (8, 9). Quoted from here:

if the AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED flag is set in the top-level vbmeta, then androidboot.veritymode is set to disabled

On user builds ro.debuggable is 0 and adbd isn't running as root. Also there are other differences like that of ALLOW_ADBD_DISABLE_VERITY, so adb won't disable dm-verity. Other approach is to remove verify or avb (10) flag from fstab. Quoted from here:

To verify the partition...
  ...
      In the fstab for the relevant entry, add verify to the fs_mgr flags.

Similarly to remove encryption, forceencrypt=, forcefdeorfbe= or fileencryption= need to be replaced with encryptable=. However encryption cannot be removed without factory reset (FBE too?), so unchecking Preserve force encryption in Magisk app will do nothing.
Some OEMs also use support_scfs fs_mgr flag and ro.config.dmverity=true property on devices with dm-verity enabled.
There are also some exploits discovered in bootloader and adb implementation of some OEMs which can be used to disable dm-verity on affected devices. However such security flaws usually get fixed over time with updates from OEMs.
OPTION 1
Set options in configuration file before installing Magisk:
~# echo 'KEEPVERITY=false' >/cache/.magisk
~# echo 'KEEPFORCEENCRYPT=true' >>/cache/.magisk

If installed, after unchecking Preserve AVB v2.0/dm-verity in app, Magisk needs to be reinstalled. Quoted from here:

in Magisk Manager, “Uninstall > Restore Images” to restore the images, check “Preserve AVB 2.0/dm-verity” box in Advanced Settings, then reinstall Magisk via the app.

OPTION 2
Use some dm-verity disabler zips like this.
OPTION 3
Figure out where the fstab entries of /system and /vendor are on your device.
If in ramdisk (pre-Treble):

Extract ramdisk, modify fstab and repack.
Or patch ramdisk directly:
~# magiskboot cpio ramdisk.cpio 'patch false true'

If in dtb:

If appended to kernel:

Extract boot.img
Split appended dtb(s)
Patch dtb(s).
Append dtb(s) to kernel
Repack boot.img

If in dtbo partition or in boot.img after 2nd stage, patch dtb.img and write back to partition or boot.img.

How to Unpack / Repack Boot or Recovery image and Ramdisk?
Use AIK or magiskboot.
How to Patch dtb?
Patch directly using magiskboot or manually convert dtb to dts, edit dts with any text editor to remove dm-verity flags, and convert dts back to dtb.
RELATED:

How Magisk works?
Android Device Partitions and Filesystems

In SAR devices launched with Android 10, I have built a kernel with avb flags(no verity flag found) removed from fsmgr_flags entries and made it permissive. Also empty the vbmeta with verification flag disabled. Is it enough for a dm-verity to be disabled? (I can't test it as twrp is not updated to Android 10 and Idk yet how to mount dynamic partition with rooted adb shell in recovery)

@VatishSharma Sorry I haven't tested with Android 10, so cannot say anything for sure.

Do you have idea of mounting dynamic partitions(I have made twrp and get rooted adb shell but yes its not updated for dynamic partitions and so lack mounting features)?

@VatishSharma no idea.

Do you have an idea how to disable dm-verity in an AOSP build? I assume it's a makefile value.

You can just edit the Magisk root package to ONLY disable the dm-verity flag. It's literally just commenting out a few lines of Magisk scripts, since the functionality is inherently present in Magisk. Here's the link to such a package: Download magisk-onlynoveritypatch.zip Boot into twrp, install from zip, and select this zip.

thx for sharing. unfortunately only registered users can download. and it's hard to register because there is no english captcha :(


text:
Android OS Storage Usage
I have two fresh Galaxy device on Android 9 , the difference is in storage , one is 512GB and another is 128GB. System usage in both is different , 128GB version uses 27GB on fresh but the 512GB version use up to 47GB. There is no installed app and both devices are just out of box.
My question is why Android uses more storage on 512GB version and how can I decrease the amount? If it's dynamic what's the reason and should it decrease if the device is out of storage?

I don't want to root both devices, so I checked it on another device which is previously rooted. By df -h I see it's about device partition, the rooted device is 32GB out of which only 25GB is available. Other partitions are listed as below:

As you can see there is some duplicate mounted partitions , but sum of their sizes will be 32GB.

Root both and take a comparison of du -h /data | sort -h.

Check the partition size using an app like DiskInfo. On Android the system has on own partition. If the partition is larger the free size for user data is smaller.

@Robert df -h would also do the job. Just because eMMC is larger, could /system be larger on the same model? Shouldn't only userdata differ, that's what custom paid extra for.

Would you consider sharing your results? I just asked a very similar question here: https://android.stackexchange.com/questions/244678/installed-base-system-size-on-galaxy-s10-smartphone Thank you :-)

With root take a comparison of space usage on both devices by executing du -h /data | sort -h. Without root you can rely on figures reported by filesystem by running df -h.
From the updated screenshot you have attached, no partition is duplicate mounted. If you are talking about tmpfs, it's a volatile filesystem which lives in RAM and is vanished on reboot. It isn't part of your persistent storage.
Your /data and /system added make 29GiB. That's what you get on a 32GB device. Up to 2GiB difference comes because of Gigabyte (GB) and Gibibyte (GiB). Also there are usually 50+ partitions on an Android device which aren't mounted (except a few filesystems). And there's free space left by manufacturers for over-provisioning of flash memory.
For details see: How disk space is used on Android device?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How to turn on the wi-fi hotspot using command line with root?
I've read a lot posts about it like How to turn on the wi-fi hotspot using ADB? but all of them based on "click emulations", but I have root and it doesn't solve my problem.
I've tried VPN Hotspot app and it work perfectly even without root permissions (using only "WRITE_SETTINGS" perm.)
I need to enable it using command line even when phone is locked, something like:
adb shell su -c service call connectivity 24 i32 0 i32 0 i32 0 s16 random

but for Wi-Fi tethering.
I've Android 11 rooted device.
Update
I found that it is possible to do this through a similar command:
service call tethering 4 null s16 random

void startTethering(in TetheringRequestParcel request, String callerPkg, String callingAttributionTag, IIntResultListener receiver);

But first argument null is wrong because here must be this interface:
parcelable TetheringRequestParcel {
    int tetheringType;
    LinkAddress localIPv4Address;
    LinkAddress staticClientAddress;
    boolean exemptFromEntitlementCheck;
    boolean showProvisioningUi;
    int connectivityScope;
}

How to put it instead of null?

connectivity service does not have a method to start Wi-Fi hotspot. tethering service indirectly calls wifi service which you can call directly.
startSoftAp and startTetheredHotspot methods start the hotspot, and stopSoftAp stops, as the names suggest.
For Android 11, the order of three methods is 47, 48 and 49 respectively. So to start:
~# service call wifi 47

And to stop:
~# service call wifi 49

No configuration argument is required. Android automatically picks the saved AP configuration.
If a package name is required as argument, try to provide an empty string or null or android or com.android.shell.
Check the method number for your Android version in the service interface file: android.net.wifi.IWifiManager.aidl linked above.
All three methods require android.permission.NETWORK_STACK which has a protection level: signature, so won't work without root.

Related:

How to configure and Enable WiFi Hotspot through terminal without ROOT
How to create a WiFi hotspot from the terminal?

Thanks! It works! But I want to know for the feauture, what I should do when I want to call throw service call method where some argument is object like in my case parcelable TetheringRequestParcel. Is it possible to call some methods like it or only simple like wifi?

@mixalbl4 you can only pass basic data types from shell like integers or strings. See service -h. Parcel is a Java object, so you need to write Java code.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Can I access "/data/user/0/" folder in Android emulator from Ubuntu PC?
I am using Ubuntu 18.04.
From Android Studio with the following code I am getting file directory
Context ctx = getApplicationContext();
final File filesDir = ctx.getFilesDir();

which is /data/user/0/com.example.ipfs/files/. I am running my app on Android Emulator. How do I go to the /data/user/0/com.example.ipfs/files/ folder from my PC?

If your emulator runs userdebug ROM so that ADBD runs with root privileges, then simply do adb root; adb shell ls /data/user/0/com.example.ipfs/files/. If it's a final user build (usually the one with Play Services), then you first need to root your emulator (MagiskOnEmulator). See Why are superuser permissions needed to acess /data partition? and Why “adb root” does nothing?

For this, Android Studio has the feature called Device File Explorer that will allow you to view the connected device or emulator internal files. This is useful especially when you are utilising the getFilesDir() as a path to save your app generated files & hence are not able to see them with the standard File Manager.
From the main menu, go to View -> Tool Windows -> Device File Explorer. You can then select your device / emulator from the drop down list.
To access /data/user/0/com.example.ipfs/files/, just go to the directory data/data/com.example.ipfs/files from the list displayed in the Device File Explorer once your device / simulator is connected.

I am using Ubuntu 22.04 right now I tried this solution using AndroidStudio2022 and it's work and I figure out it was pointing to a hidden files below..

PATH:
/home/[user]/.cache/Google/AndroidStudio2022.1/device-explorer/[device_emulator_name]/data/user/0/[project_name]
Example:
/home/awen/.cache/Google/AndroidStudio2022.1/device-explorer/Pixel_5_API_32
[emulator-5554]/data/user/0/com.example.html_pdf_demo


text:
How to share a 4G data connection over wired Ethernet?
I understand that Android is principally an wired-Ethernet client.  i.e. it requests and receives a DHCP address.  The internet is on the other side of the Ethernet cable.
Does any version of Android have the capability of running its wired-Ethernet in an "access-point", "tethering" or "server" mode, where Android's Ethernet provides a DHCP server and NATs Ethernet traffic out through its 4G radio, to the internet?

While the feature has never been part of stock Android (not sure if some custom ROM provides this), it's possible on rooted devices.
I recently answered to How to make Ethernet work on Android over OTG? which may help you make Ethernet work on your device. Once done, there are two more things required:

Run a DHCP server (we already have dnsmasq on device up to Android 9, or you may get a static binary)
Share internet (by doing IP forwarding and NATing)

Both of these steps are explained in my answer to How to create a WiFi hotspot from the terminal? and the answers linked there. Just ignore the steps related to WiFi and pick the relevant parts.


text:
How can I enable Android Debugging from a root shell on the phone?
I have a root shell on the phone.
However, no adb service seems running, i.e. the port 5555 is on the device not open1:
$ telnet 1.2.3.4 5555
Trying 1.2.3.4...
telnet: Unable to connect to remote host: Connection refused

I.e. something what should listen on adb connections, does not run on my Android.
Can I somehow start it from a root shell (on the Android)?
I have Android 10.
1Telnet only serves here port testing purpose, obviously adbd will be connected by adb.

Run:
settings put global adb_enabled 1

You can also start adbd service by executing start adbd or setprop ctl.start adbd. But I prefer the settings way because it properly goes through Android framework.
PS:
For clarification, adbd listens on port 5555 only if ADB over Network is enabled (from Developer Options, or by running setprop service.adb.tcp.port 5555 on device, or by running adb tcpip 5555 on PC). In USB mode (which can be switched to by running adb usb on PC) adbd is not listening on any network port. Some more related details in this answer.


text:
Reinstall OS android on chinese phone Gusun JY809?
I bought a Chinese phone, the Gusun JY809. I am satisfied with the phone itself but it still logs into chinese web apps and stores. Unfortunately, I am in the Czech Republic. I have tried to install CyanogenMod but I could not find the right one.
Are there any custom ROM options for this phone?

Welcome to Android Enthusiasts! We're excited to have you here. Unfortunately, this phone is rather obscure and I'm not able to find any information about ROMs (or rooting, or the bootloader, or really anything) for it. I fear that you may not be able to change the software.

Not really news that sweet to my ears or stomage :-(

I have the same phone and having the same difficulty on finding any info, so far I have been able to:

connect to PC using PDAnet auto drivers
root using Graphical Easy Root Tool
install ClockworkMod Recovery rua1 autoCWM v5.5.0.4

Hope this helps.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
MMS video auto compression
I have a new Samsung Galaxy Note 3.  I love the device, but sending a quick video MMS seems to be a challenge.
On other devices I have used, the video will automatically get compressed to a very low quality and will just send it.  This is all I want.  I don't need to send super clear video, just a small compressed video to family and friends.
Are there any apps that will handle this automatically without making me upload to a cloud service and sending a link or some cumbersome process?
I also don't want to have to choose a low quality recording beforehand, I would like the good quality stored on my phone, but send a simple low quality clip over the air.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How can I send a SMS (Instead of MMS) from a Motorola Atrix 4G?
I was writing a text when suddenly I noticed the message say MMS not SMS. How do I change it back?

It automatically changes to MMS when a message's length goes over 160 bytes (160 ASCII characters). You should be able to go back to SMS by starting a new message.


text:
How do I clear the browser's auto-complete history?
My phone keeps saving what I type into chrome or the browser. I have tried erasing the history it still auto completes if I need to retype it. I understand it great to save all the info but I have typed my credit card in one of them and its saved.
How do I clear the browser's address bar auto-complete history?

If it is auto-completed by Google Chrome, please follow the following steps,

Go to your Google Account Dashboard. This will list all of the information collected on you by Google.
Scroll down to Web History and search for your Credit Card entry or other entries to be removed, and remove it from the history. Or you can go directly to your Web History.
Further, in Dashboard you can scroll down to `Chrome Sync and click on Manage Chrome Sync.
Click on the Stop and Clear button to clear all the Autofil and
Omnibox History and to stop syncing the data with Google Server.

Steps 3 & 4 will merely stop Google from collecting data on Google Chrome's Omnibar (I am not 100% certain on this).

Press and hold the offending autofill suggestion.  A pop up appears to "remove a Learned word".


text:
Open Facebook links with Facebook app?
When I receive a http Facebook link, I have the option to choose my browsers but not the Facebook app, is there a way to force it? Is it the normal behavior?

Do you have the official Facebook app installed?

Yes, I do. I thought it would show as option like the browsers.

It has never done this for me. Twitter, Google+ etc do, but facebook always went to the browser. Just tried it on Galaxy S4, Nexus 4, HTC Desire X, HTC One and a Nexus 7 now and the same on all. Fresh installed and logged in Facebook app too.

I'll try some third party apps to see if it works like that. Why wouldn't Facebook links open in Facebook app. I don't see a reason.

Tried some apps and no one was capable to open urls... Seems like Facebook doesn't want us to open its links in a app.

Facebook doesn't care. This is very annoying. Pretty much every app can open links related to them regardless of schema. Except Facebook with devs who are stubbornly expecting everyone to use a non-standard schema, rendering almost all http-based Facebook links in the web unopenable on the app. /rant

Is it normal behavior?

Facebook app only handles specialized URL scheme fb:// and nothing more, so any standard HTTP/S Facebook links (http:// or https://) will be ignored by the app. So, yes, unfortunately this is normal.

Is there a way to force it?

As of current writing, until their developers implement a filter to handle HTTP protocol, there is no way to do that from their apps.
It might be possible for a 3rd-party app to fix this with a workaround (e.g. Open Link in App app, as mentioned from this answer, but it seems currently it's not working, possibly due to change in FB protocol).

The Facebook app on Android now supports deeplinking. So your http:// and https:// should work. Within the Facebook app as well as from other apps.

What do you mean?

@ADTC Tap on any Facebook link, and the OS will open it in the FB native app (if installed)

No it doesn't do that. The link only opens in the browser, as if there is no app installed. (I have the Facebook app installed.)

Works for me on Android 6 and 7 both. On Galaxy S7 and Pixel, both.


text:
not able to access playstore after factory reset
I am not able to access the Google Play Store on my Samsung Galaxy Y GT-S5360 after a factory reset. How can I get it working again?

Could you [edit] your question to be a bit more detailed? What happens when you try to open the Play Store?

it just freezes and goes back to home screen. Also a message comes after a while saying google play store has unexpectedly stopped working.

Try doing a factory reset again, and don't include you gmail e-mail during setup i.e before the home screen comes, once the home screen is active then go to google play and login, should be able to download the apps

@Tephanie If it doesn't work, is there a reason why you accepted the answer?

@dotVezz i am new at this

@Tephanie No worries! And welcome to the site!


text:
Text to speech erratic after android 4.3 update
I use the app AnkiDroid on my HTC One to learn Italian. It has a text to speech option which, when enabled, reads the text on the flashcards aloud. However, after updating to Android 4.3, this function has become extremely erratic - only 1 of every 20/30 cards is read out (it worked perfectly before the update).
I have also recently bought a Google nexus 7, running Android 4.4.2, and it also has the same issue. Does anybody have any ideas about why this is happening and if possible how I could resolve this?

This might be an issue for the app developers to address. Have you considered reporting it on the AnkiDroid Issues Page?

I did report it there but the developers suggested to ask here as it may be something to do with the android update. I have now found a tts engine that is working more reliably, though not perfectly, but I'm pleased. Thanks for your help!

I released AnkiDroid 2.0.3 yesterday, it fixes the TTS bug described at https://code.google.com/p/ankidroid/issues/detail?id=1892
Does 2.0.3 fix the problem you described in your question?
Before 2.0.3 the TTS part of AnkiDroid had not changed in a long time, so it must be that TTS changed in Android 4.3.
If anybody has some info about what changed in Android 4.3's TTS it would be extremely appreciated.

The update may well have helped because I have just downloaded Svox Classic and tts seems to work reasonably reliably now. It does miss out the odd word - probably 1 in 8 but I'm really pleased the function is working on the whole once again! Does anyone have any experience with Acapela's compatibility with Ankidroid? Would love some feedback before I buy! I was using Ivona before (which I really like and also happens to be free!) however that, as well as Google's own tts engine, still has major problems for me. Maybe it's an issue to raise with Ivona now. Thanks a lot for your help!


text:
What is the mobile provisioning website supposed to do?
When I go to Settings → More... → Mobile plan it gives me a message "{mobile operator} has no known provisioning website".
Digging into Android source code for WirelessSettings.java I found how URL gets populated (it was later moved to IConnectionManager but I guess it have similar implementation):
private String getProvisioningUrl() {
    String url = getActivity().getResources()
            .getString(com.android.internal.R.string.mobile_provisioning_url);
    log("getProvisioningUrl: mobile_provisioning_url=" + url);

    // populate the iccid, imei and phone number in the provisioning url.
    if (!TextUtils.isEmpty(url)) {
        String phoneNumber = mTm.getLine1Number();
        if (TextUtils.isEmpty(phoneNumber)) {
            phoneNumber = "0000000000";
        }
        url = String.format(url,
                mTm.getSimSerialNumber() /* ICCID */,
                mTm.getDeviceId() /* IMEI */,
                phoneNumber /* Phone number */);
    }

    return url;
}

So potentially it can create an URL like:
https:\\operator\provisioning.aspx?ICCID=8991101200003204510&IMEI=49015420323751&number=008801552341588
My question is, what such a provisioning site supposed let me do?
Is information passed to URL is sufficiently secure for a network operator to identify a customer so it can skip authentication?

To my understanding this functionality is to configure your current provider services such as offers, cheaper international calls, flatrates...
But I suppose you'd always have to login first. Just the those 3 things don't seem to be secure enough to just login with them.

Some providers have a special website which is only reachable via the mobile network's data connection. On that page I don't need any login or userdata, as it already knows from which mobile number I'm connecting.


text:
How to find out if my mobile data is working or defective?
I installed CyanogenMod 7.2 stable on my Samsung Galaxy Ace before, but it seems mobile data wasn't working. I decided to download the latest nightly build (2013-03-01) but still the mobile data doesn't work.
What are some ways to troubleshoot/test if my mobile data is working? Note: it was working before on stock ROM.

I found the problem: Roaming was active. That's why mobile data wasn't working.
Simply disabling roaming fixed the issue.


text:
How can I set the lockscreen personal message after updating?
On my Samsung Galaxy S3, I had an option to change the personal message on the lock screen. After the system update,  the option is still there, but it is grayed out. Does anyone know how to fix this?

Do you have a lock screen set? Or is it None?

its just the swipe

Swipe to an empty lock screen, press the "+" button and add messaging. That should do it.
If it still doesn't work try this.

Go to Settings >> My Device >> Home Screen Mode and change it to "Standard Mode". That should enable the personal message option on your lock screen...


text:
Allowing app installs from “unknown sources” for Secondary Users on Android 4.4.2
I see that "Unknown Sources" under Settings → Security on Android 4.4.2 is greyed out (I can't enable it) for my Secondary user on my Nexus 7, Is it expected behavior? Is there any way to enable it?

The Secondary user is not with a restricted profile

Android by default does not allow secondary users (Restricted Profiles) to install apps from Unknown Sources.
But, under Application and Content restriction for the particular user, you can enable specific menu in Settings menu. You can check whether Unknown Sources can be enabled.

Just click it 10 times in a row and then it will ask you are you sure then just click yes and then there you go your ready

Or 20? Or, 30? This question concerns secondary users. How confident is that answer, since I don't believe secondary users have any control over this?

Please supply some source for this statement of "fact"?

Enable it from the Owner user then it is enabled for all secondary users

This is clearly not the case, as implied by the OP's own statement. Obviously they already enabled it from the owner's user profile, and that didn't resolve the issue. Also, this was already answered an entire year ago, and correctly.


text:
contacts crashes sporadically
Sometimes, when I click on the phone icon on my Galaxy S3, it freezes for a second and then says that the app Contacts has crashed. Afterwards I can reopen contacts with no problem.
This happens sporadically; sometimes it crashes multiple times in a day, sometimes it lasts a week without problems.

Could you let us know how often this happens (Every day? Every hour?), and perhaps which version of Android you're running? Did this start happening after you installed another app or some other event?

I'm not sure what started this or I would of uninstalled it. 4.1.3 and it varies when it happened some times it will be multiple times in a day then not for a week or so.

Have you tried the usual?

I have, I'm probably just gonna end up reformating


text:
Are all apps on Google Play compatible with the Samsung Galaxy S4?
I wanted to know whether the Samsung Galaxy S4 will run every app from the play store or not? I had done a lot of googling but failed to find an answer.

In general, NO.
Some apps:

run on specific devices only (i.e. not compatible with S4)
run on specific Android versions
available only in specific countries
available only on specific carriers
requires root access. (i.e. if phone is not rooted, it won't work)

You forgot to mention "are not available on specific carriers."

Or "are only available on specific carriers".

@Chahk an Al Thanks for that. Added into answer. :)

No there are not all compatible. When you watching an application on Google play ( from your device ) if you cannot find the button for installing that app, that means that your device is not supported by that application. Also if you visit that application page on Google play desktop site, and your device is listed in your account than a message will appear in browser that says that specific application is not compatible with your device.

I would say 80% app is compatible. And other 20% are for other specific devices. Specific android version and  specific screen size

What are you basing that on?  I've not seen any breakdowns like that of app/device compatibility, anywhere.

I'm with @Logos here. If you're going to give numbers, please cite your sources.


text:
How to save or back-up whole SMS threads on SIM
I have a Samsung-SGH -I927 and would need to save on my SIM card or send to my email for back up several text SMS messaging threads. I know that I can do this with an individual SMS' by lightly tapping on them and choose the save to SIM option, but I do not know how to do it with a whole thread. How can I do it?

Welcome to the site! This is a good question, but previous questions may already have answers that will help you. Have you seen http://android.stackexchange.com/questions/2466/how-do-i-backup-and-restore-sms-messages ?

Try using 'Super Backup' utility. You'll get an option to backup your entire SMS threads on your SD card in xml file. You can easily restore your sms too.


text:
Forward button functionality in the Play Store
l was watching one of the Play Store app videos on Note 3 and accidentally touched the back button twice. And That's when I realized HARD one more time that I can not do a forward (back to what I was watching). As a result, I could not locate that app again.
This ( not being able to go forward ) becomes an issue on many other situations too..
So, forward button is definitely has its own place in the UX. ( Imagine not having the forward button on the internet browsers, that's exactly the situation here. )
Is there a history of visited apps on the play store on the device that I can navigate back and forward through?

That's an interesting question, and I agree that it would be nice to have a forward button in the play store. Browsers, however, actually do have forward buttons if their devs allow it. Here's an example using Chrome.

thx dotVezz. The reason I brought up the internet browser's forward button talk into my question was to make a point about the forward button's place in UX world in general. There, I tried to say how the life would have sucked without that functionality in browsing the Internet. I knew that the internet browsers on the device (not just chrome but all) have their own little back & forward functionality . Thank you for the screenshow anyway though. I appreciate it. I think an overall ( device level ) forward button functionality has to be somehow worked out.

An OS-level forward button would almost certainly not be a good idea in a practical sense. The idea of it is good, but the functionality is up to the app developers for a reason.

For me, your rant about wanting a forward button really detracts from what would otherwise be a useful question about seeing your Play Store history.

Dan, I agree. That rant was not necessary.


text:
Galaxy S3 randomly deleting my contacts
My Samsung Galaxy S3 just deletes some of my contacts on a regular basis.  Any ideas on how to stop this and or recover those deleted contacts?

Welcome to Android Enthusiasts! We're excited to have you here. Is this only happening to certain contacts, or is it completely random? After recreating a contact, does it later get deleted?

It just totally randomly makes the contact unknown and all the info for the contact is deleted/gone.

Are these newly added contacts? If you are adding new contacts and adding them as "phone" contacts and not "google" contacts, and you have syncing on, it may be syncing your google contacts to your phone, and deleting the ones that aren't google contacts. This happened to me a couple of times.

Thanks but no syncing on .... :(


text:
Why does MTP show wrong directory location?
MTP (Miserable Transfer Protocol) failed once again.
After moving a directory to a different path, it is still on the same path as before according to MTP.
I already tried re-plugging the USB port and reading it from a different computer. Same result.
Why is MTP so bogus that it shows a moved folder on its previous path?

What is Content Provider?
It seems to be a problem related to Media Providers. As the name suggests, they provide a database of available media in a more organized way to other apps as the Contacts Storage (com.android.providers.contacts) provides contacts to requesting apps. Purpose is to scan and store media file info for quick access so that individual apps don't have to scan folders manually for an up-to-date library, reducing time and effort.
Android's built-in Media Providers:
Some file explorers, media players and gallery apps depend on the files database (/data/data/com.android.providers.media/databases/external.db) built by Media Storage app for MediaStore content provider from the contents of external storage (/sdcard and external SD card; removable storage like USB isn't indexed). Apps Media Storage (com.android.providers.media under which com.process.media runs), Downloads (com.android.providers.downloads.ui), Download Manager (com.android.providers.downloads) and MTP Host (com.android.mtp) work in collaboration under same UID.
Database is built/updated as MediaScanner (android.process.media) is invoked by some app such as by sending broadcast MEDIA_SCANNER_SCAN_FILE or through scanFile. Broadcast receiver com.android.providers.media.MediaScannerReceiver is launched on boot that listens for android.intent.action.BOOT_COMPLETED, so MediaScannerService will also launch on boot. But restarting phone sometimes doesn't update whole external database (or at least delays). MediaScanner is also triggered when a new storage device is mounted i.e. on MEDIA_MOUNTED which could possibly be manually broadcasted to force updation on pre KitKat versions.
In response, apps are informed of updated databases such as by receiving broadcast MEDIA_SCANNER_FINISHED or through onScanCompleted.
Problem with Media Providers:
MtpService is also a part of Media Storage. Due to some bugs (acknowledged since 2012) in implementation of MTP, database isn't updated or is delayed or isn't properly communicated with the client as the files change, so MTP shows outdated / incomplete contents. The same can happen if an app creating or downloading a new file fails to trigger the MediaScanner or fails to receive back the updated information.
Solution:
In order to force database updation, delete the file and run some media scanner app. Non-root users can delete this file by clearing data of Media Storage app.
But be aware, it'll also clear internal.db which will make ringtones unavailable and a new database will be built from /system/media on next reboot i.e. on BOOT_COMPLETED.
PS: Note that the internal SD card we see is emulated from /data/media/ using sdcardfs (or FUSE in older versions of Android). Actual contents of internal memory can be seen directly from /data/media/ (root required). UMS used to expose the /data block device to PC but was deprecated in favor of MTP. It's a good option when larger size of data is to be transferred at high speeds. It can be enabled by some workaround.
There are also other reasonable alternatives for MTP like FTP, SFTP/SSHFS, adbfs etc.
RESOURCES:

How Android categorizes files based on their extensions
MTP, External Storage, and Your App
Scan Media Files In Android
Broadcasts overview
Android Content Providers


text:
Restricting an app to only send internet traffic but not receive that back?
Is there a way or app to restrict some apps on my Android, or the whole device, to only send internet data packets but not receive them back?
I want to confuse a game app by doing this. It restricts me to have only two games simultaneously. But I want to suppress this behavior by opening game in normal way, blocking incoming traffic and then sending three or more requests to start a game. The app errors, but after restarting, all three or more games will start.
I have a rooted phone.

Let us continue this discussion in chat.

It's possible, but far from easy to achieve. There are multiple approaches we can use to block (or at least try to block) incoming traffic.
But blocking one way traffic doesn't make sense in most cases. An app sending TCP packets but not receiving back responses will consider itself disconnected from internet. However, you may try for your particular case if it works.
Note: All of below discussed methods need root access.
UID BASED BLOCKING:
Android uses Linux kernel which has a builtin firewall netfilter that can be used to filter network traffic. There is an iptables module named owner that filters traffic based on its UID / GID. Every app on Android is a UNIX user and has a unique UID.
But the problem is that owner module is only valid for outgoing traffic i.e. the packets generated locally. IP packets coming from some other machine don't carry owner information with them. So the owner module applied to incoming traffic should fail or it should give a warning as explained here. To measure per-app incoming / outgoing network usage, Android patched kernel to include qtaguid module. But iptables wasn't patched to use the module from command-line. Also see related details in How to view network traffic requested by app?.
However owner module works for some of the incoming TCP packets received back with TCP Flags, which may block incoming traffic fully or partially:
# iptables -I INPUT -m owner --uid-owner <APP_UID> -j DROP

* To remove the rule, replace -I with -D
Probably the reason is that same TCP packets are returned back for Handshake and Bye but I'm not sure about that. However be ensured that it doesn't work for 100% TCP/UDP traffic. See escaped traffic:
# iptables -I INPUT -j LOG --log-uid --log-prefix 'INCOMING '
# dmesg -w |  grep INCOMING | grep -vE 'IN=lo|=5353|=1900|ICMP' | grep -v UID=

Some firewall apps block outbound traffic using VPN on Android. VpnService API also makes use of UIDs and SOcket_MARKs to control traffic in routing table / RPDB, just before leaving the device.
PORT BASED BLOCKING:
More certain and complex ways of blocking incoming traffic rely on watching all the network sockets being created and deleted. A socket is a combination of IP address and port.
To get some basic idea of this approach, let's take example of Firefox app on my phone, with UID 10081:
# ss -4tuapne | awk '/uid:10081/ { print $5,$1,$2,$7.$8 }'
192.168.1.11:39910 tcp ESTAB users:(("mozilla.firefox",pid=22370,fd=163)) uid:10081
...
...
# iptables -I INPUT -p tcp --dport 39910 -j DROP

This will block all incoming traffic to port 39910 being used by Firefox app. But this approach is not practical because creation and deletion of sockets is taking place at such a high pace that even in native code some packets would be missed. And at the next moment the same port will be assigned to some other app's socket. This seems only possible if the local port is fixed, but for normal apps, random system selected available (TCP / UDP) port is being used for socket creation (can be controlled with ip_local_port_range).
You can find some more details View network traffic requested by app.
IP BASED BLOCKING:
This methods works best if you know the source IP address of packets. Find all servers your app is trying to connect on internet (e.g. by blocking app for outgoing traffic) and block them using iptables source IP filtering, if they are not a hundred in number and they don't keep on changing frequently:
# iptables -I INPUT -p tcp -s <IP_ADDR> -j DROP


text:
Is it possible to get root permission using Magisk in Work Profile?
I had flashed Magisk in the recovery, but when I run Magisk Manager in Work Profile it says Magisk is not installed. Does this imply that there is an independent recovery for Work Profile as well? Is there any way to gain root access in Work Profile?

Choose User-independent option in Multiuser Mode Settings of Magisk app.
User profiles and multi users are managed inside OS, nothing to do with recovery.

I have the same issues and I selected the "User-Independent" settings in Magisk Manager outside the work profile. After that the magisk app in my work profile ask for additional setup and downloads Magisk setup zip but after download it says "Setup Failed".

@SleepyLord If a feature doesn't work as expected, it's a bug. Register your issue here.


text:
How to grant an app a permission that isn't in its manifest for audio recording?
Non rooted Moto G6 Play running Android 9.
I'm using Termux and would like to use Sox's rec command to record audio from the terminal.  Unfortunately, since Termux doesn't request the mic permission, it just records silence.  I can't grant Termux the permission in Settings because...well, it doesn't request it.  It's not in the app manifest, therefore Android (understandably) assumes it wouldn't know what to do with the permission if it had it and doesn't list "record audio" as an option.
Is there a way I can force Android to grant an app a permission it never asked for?

Just in case this is an XY problem (X: how to record audio using sox from terminal, Y: how to grant a new permission on Termux), you might be interested in ZShaolin that claims having in-built sox (there's also the free ZShaolin Light XDA-Dev, though I'm not sure if it includes sox)

Not possible without root but even with root SoX recording might not work.

Android Manifest Permissions
Android permission system has different Protection Levels (1, 2); Normal permissions are granted to any app without user interaction while Signature|Privileged (SignatureOrSystem) permissions (whitelisted in /etc/permissions/privapp-permissions-*.xml) are granted only to system apps. Both are granted when app is installed or on first startup (if system app) and configuration is saved in /data/system/packages.xml file. Some signature permissions can be granted to non-system apps after user's approval using appops.
Dangerous permissions are those which require user's approval to be granted or denied. User's choice is saved in /data/system/users/<User_ID>/runtime-permissions.xml where device owner's User_ID is 0 (don't confuse it with UNIX DAC's UID).
Most of the manifest permissions are enforced by Android framework (system_server) but some are mapped to GIDs; hence enforced by kernel. Permission to GID mapping is stored in /data/system/packages.list.
How to Grant an App Unrequested Permission
You can modify above mentioned files to grant a permission which isn't requested by an app in its Manifest. I haven't tested with all permissions but this trick works (at least up to Pie) because Android framework doesn't verify the saved permission configuration vs. apps manifest files on every reboot (may be the changes are reverted back to actual during a scheduled maintenance task or when some app is installed or updated; I'm not sure).
In our case we want to grant android.permission.RECORD_AUDIO to Termux which is a dangerous permission, so this is how you should edit your runtime-permissions.xml followed by an immediate reboot:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<runtime-permissions fingerprint="...">
  ...
  <shared-user name="com.termux">
    <item name="android.permission.READ_EXTERNAL_STORAGE" granted="true" flags="0" />
    <item name="android.permission.WRITE_EXTERNAL_STORAGE" granted="true" flags="0" />
    <item name="android.permission.RECORD_AUDIO" granted="true" flags="0" />
  </shared-user>
  ...
</runtime-permissions>

To confirm:
~$ pm dump com.termux | grep -A3 'runtime permissions:'
      runtime permissions:
        android.permission.READ_EXTERNAL_STORAGE: granted=true
        android.permission.WRITE_EXTERNAL_STORAGE: granted=true
        android.permission.RECORD_AUDIO: granted=true

Why SoX won't work?
That said, still SoX won't be able to record audio because (AFAIK) it's not using Android's Java APIs (android.media) or native APIs (aaudio/opensles). It uses ALSA/OSS driver directly or through PulseAudio which needs direct access to device interfaces in /dev/snd/ or /dev/{audio,dsp*} and proc tree in /proc/asound/. For details see Android Audio Architecture.
However direct kernel level access isn't a norm on Android, so you need root access. Apps with android.permission.MANAGE_VOICE_KEYPHRASES are allowed to read /dev/snd/* devices. It's a privileged signature level permission which is mapped to GID audio (1005). You can edit packages.xml to get this permission granted:
    <package name="com.termux" ... >
        <perms>
            <item name="android.permission.MANAGE_VOICE_KEYPHRASES" granted="true" flags="0" />
        </perms>
    </package>

    <shared-user name="com.termux" ...>
        <perms>
            <item name="android.permission.MANAGE_VOICE_KEYPHRASES" granted="true" flags="0" />
        </perms>
    </shared-user>

And packages.list:
com.termux ... 0 /data/user/0/com.termux default:targetSdkVersion=28... 1005,3003

But SELinux allows only privileged apps (having context priv_app) to read files in /dev/snd while /proc/asound/ isn't readable by apps at all, so you need to patch sepolicy as well.
And even after that, configuring SoX to use ALSA/OSS/PA is up to you.

Non-Root Solutions
Instead of using ALSA directly, PulseAudio can also be configured to stream audio over TCP or UDP or UNIX sockets. That's how media playback works on Termux. See this issue. However capturing audio only work through Android APIs. You can install termux-api package to use termux-microphone-record command for audio recording. It uses MediaRecorder class of Java API, or you may consider modifying SoX source to use Android's native APIs.

RELATED

How to Play Sound from Termux when using Linux?
How Android's permissions mapping with UIDs/GIDs works?

There are two ways:

Termux is an open-source app on Github. Therefore you just need the Android development tools and git for cloning and building a custom version (may be with a different package name so you can have both your version and the official installed).
As your device is rooted you can try to add the permission to the list of registered permissions of an installed Termux. As far as I know the relevant data should /data/system/packages.list or /data/system/packages.xml.
After modifying those files you should reboot the device to activate the changes.
For more details see also this answer.
Note: I am not sure what happens to these modifications in case an update of Termux is installed. I assume that the update will revert your changes.


text:
How Android's permissions mapping with UIDs/GIDs works?
Reading the book: Android Security Internals I'm reading at Chapter 2 - Permission Management paragraph that permissions are assigned to application at install time by the package manager with a mapping like Apk's UID <-> Permissions.
Later in the book (Permission Assignment - Permissions and Process Attributes paragraph) I read that

If additional permissions have been assigned to the application, they are mapped to GIDs and assigned as supplementary GIDs to the process.

And, since android.permission.INTERNET permission is associated with inet GID:

any process for an app that has been granted the
  INTERNET permission is associated with the supplementary GID correspond-
  ing to the inet group

But I was asking me if this is always necessary.
Imagining a case where you install APK X declaring android.permission.INTERNET permission in AndroidManifest.xml, since mapping of permissions with UIDs is done at install time, PackageManager should be able to map the permission directly with the APK's UID instead of adding inet GID to your APK package. So I'm wondering why it has to be that:

any process for an app that has been granted the INTERNET permission is associated with the supplementary GID correspond- ing to the inet group

Anyone can clarify me this?

That is simply the way it works. Checking if a user is member of a specific group is much simpler than on every request having to check if a user is authorized to this and that.

Android's permission management can be divided majorly in two parts: Linux kernel and Android framework.
DISCRETIONARY ACCESS CONTROL:
Discretionary Access Control (DAC) based on users, groups and access mode predates back to early days of UNIX. Every file (including directories) and process has a user owner (UID) and a group owner (GID). So a process is allowed to Read Write and eXecute a resource depending on its access mode bits (RWX) for User, Group and Others (UGO). These permissions attributes are saved along with files on filesystem.
UID/GID 0 is special for Linux kernel; it's the super user (administrator) that is never denied from doing anything. All other users in range 1-65534 are non-privileged IDs which an OS can use in whatever way it wants to control access.
Android reserves UIDs in range 1000-9999 for system use unlike Linux distros where 1000 is usually the first UID assigned to human users. Android is designed for single human user but every Java app, whether preinstalled (as system or user app) or installed by user, is treated as a user. UID range 10000-19999 is reserved for these apps. At first boot (for preinstalled apps) or when installing a new app, a unique UID/GID is assigned to the app which is static unless the app is uninstalled. This app vs. UID mapping can be seen in file /data/system/packages.list or using command id (1) if the app provides a shell or can execute native binaries.
All of these UID's have hard-coded names on Android which are predefined, unlike Linux distros, where there are almost standardized naming conventions for users and groups which can be added / removed in /etc/passwd and /etc/group. Android shares only root user name with Linux. However these names are only for the ease of human users, for kernel only numbers (UID/GID) mean.
Access Control Lists (ACLs) can be used to extend DAC for more granular privileges but those are rarely used on Linux and (AFAIK) not used on Android.
LINUX CAPABILITIES:
Root user's authorities are further divided into subgroups called capabilities. Instead of using UID 0 whenever an elevated task is to be performed, a non-privileged UID can be granted only the required capability. File capabilities which are attached to files using Extended Attributes (XATTR), can also be used to elevate process capabilities whenever required. Android makes use of File Capabilities as well as Ambient Capabilities. See this thread for more details.
MANDATORY ACCESS CONTROL:
Mandatory Access Control (MAC) was introduced later to supplement DAC for better security. Android uses SELinux as part of its security implementations. SELinux also makes use of Extended Attributes to label files with a context while every process is also run with a SELinux context. Then a policy is defined which includes thousands of rules allowing one context access the other, denied otherwise by default. See this answer for more details on SELinux and an example how Android makes use of DAC, capabilities and MAC.
By making use of Linux kernel's DAC, MAC and capabilities, Android launches every app in a sandboxed virtual machine forked from zygote process, with its unique ID and with all capabilities dropped, so that forced to access only it's own files in /data/data/<app_pkg_name> or in external storage. See this answer for more details.
MANIFEST PERMISSIONS:
To have a further fine-grained control of system resources, in addition to Linux's access control mechanisms at kernel level, Android enforces it's own Manifest Permissions to installed apps within its core framework. These permissions are of three types: Normal, Dangerous and Signature.
All normal permission are granted to a requesting app without human interaction. For instance a user can't restrict an app from accessing internet if the app is requesting android.permission.INTERNET. Some of such permissions are controlled by using third party tools.
Dangerous permissions - such as READ_CONTACTS - aren't granted to an app without user's approval. Some of Signature permissions treated as Special permissions - such as REQUEST_INSTALL_PACKAGES - can also be controlled from Settings app > Apps & notifications > Advanced > Special app access menu on newer Android versions.
Additionally some of the permissions for which user doesn't have independent control such as GET_ACCOUNTS, or the operations which don't have corresponding permissions at all such as RUN_IN_BACKGROUND, can be controlled from a hidden permissions manager of Android: AppOps. But this is meant only for OS use and not for end users.
PERMISSION CHECKING AND ENFORCING:
Permission preferences are stored by Android Package Manager in different files such as /data/system/packages.list, /data/system/packages.xml, /data/system/users/0/runtime-permissions.xml at app install time or at runtime. These permission checks are then enforced on multiple events such as when accessing intents, starting an activity, sending/receiving broadcast, accessing a content provider, starting/binding to a service etc.
Though the whole permission checking and enforcing process happens under zygote in which ActivityManager and PackageManager - which are part of system_server - play major role, the core framework doesn't handle every permission check on its own. It again takes help from kernel to make permission checks more robust and efficient.
For instance READ/WRITE_EXTERNAL_STORAGE permissions are enforced through UIDs/GIDs by bind-mounting different views of Storage in a mount namespace for every app. See this answer for further details.
PERMISSION <--> GID MAPPING:
Another special case where Android relies on Linux kernel for permission check is android.permission.INTERNET. As stated earlier, only UID/GID 0 is special for standard Linux kernel. However Android applied a special patch PARANOID_NETWORKING to Linux kernel which maps certain capabilities to certain group IDs in range 3000-3999 making them special. One of those is INET (3003) group which allows its members to access internet (create PACKET sockets) which isn't possible without capability NET_RAW otherwise. All permission <-> GID mappings can be found in file /system/etc/permissions/platform.xml.
Coming to your question:

since mapping of permissions with UIDs is done at install time, PackageManager should be able to map the permission directly with the APK's UID instead of adding inet GID to your APK package

So the answer is, PackageManager doesn't handle android.permission.INTERNET on its own. It just adds the app to INET group and saves the configuration. Let's take example of Termux:
~# grep termux /data/system/packages.list
com.termux 10142 0 /data/user/0/com.termux default:targetSdkVersion=28 3003

Next time the app is launched with 3003 in its supplementary groups so that kernel doesn't restrict the app from accessing internet when enforcing DAC:
~# ps -p $(pgrep com.termux) -o cmd,uid,gid,supgrp
CMD                           UID   GID SUPGRP
com.termux                  10142 10142 3003,9997,20142,50142

SOURCES:

Dissecting Android Permissions
Android Application Launch explained
Configuring DAC on Android


text:
How to identify the app/process which re-mounts partitions R/W, creates files and changes file permissions?
I have a rooted device, with superuser rights granted to a few apps I trust. I have often found my /system or /vendor partition mounted read/write, and some files chmoded to 0777. Similarly directories/files with random names are created/deleted (e.g. /sdcard/.a03Degpoif), .nomedia files are created inside them to hide their contents from gallery etc.
logcat/dmesg contains no traces of all this happening in background. This doesn't happen periodically but in a slapdash way, internet connectivity isn't a condition either. I have tried disabling/uninstalling apps, looking for any suspicious processes running, but couldn't identify the culprit(s).
Is there a way to figure out who is doing this?

Note: Following solution requires a rooted device. Kernel must be built with AUDIT_WATCH, preferably AUDIT_TREE.
The only good thing Google did was to choose the flexible and configurable Linux kernel for Android, not going for something like a crippled kernel and trying to handle everything from userspace, including running a Linux kernel (1).
Linux kernel's Audit System makes it possible to log any system calls or filesystem changes made by a process. In our case we need to identify the process(es) which are writing to /sdcard or /system and making syscalls mount and chmod.
Linux distributions have a service auditd which communicates with kernel to get information about security-related events. On Android we have already logd, not as configurable as auditd but enough for basic monitoring. logd mainly covers the functionality of its desktop counterpart syslogd, but also includes klogd and partially auditd to get logs from SELinux subsystem of kernel.
We can add a few more rules using auditctl to also report events we are interested in. You can use auditctl from a minimal Linux environment on your Android device, or compile the binary from source code (should be built with --with-arm / --with-aarch64 whatever your devices' architecture is), or get one pre-compiled here.
Now create rules files in /etc or wherever you want to:
# /etc/audit-start.rules

# enable auditing, won't work in PID namespace
# won't work if permanently disabled with kernel parameter "audit=0"
-e 1

# delete previous rules (though there are none on Android)
-D

# increase the buffers to avoid failure
# no. of event to be queued, waiting for logd to read them
-b 10000

# disable rate limit (msgs/sec) to avoid failure
-r 0

# this determines how long to wait in burst of events
--backlog_wait_time 0

# set failure mode to dmesg
-f 1

# define filesystem rules, whatever file/directory you want to watch
-w /system -p wa -k FILESYSTEM_AUDIT

# define syscall rules, see all syscalls with 'ausyscall --dump' or
# here: github.com/linux-audit/audit-userspace/blob/master/lib/aarch64_table.h
-a always,exit -S fchmod -S fchmodat -k CHMOD_AUDIT
-a always,exit -S mount -k MOUNT_AUDIT

# /etc/audit-stop.rules

# clear on exit, restore Android default values
-e 0
-D
-b 64
-r 5
--backlog_wait_time 18000

Apply rules:
~# auditctl -R /etc/audit-start.rules

Now make changes; mount /system R/W, write/delete something there and change file permissions.
Depending on logd configuration, you can get audit log in one or more of different logs (2) including events buffer (3) of logcat and main buffer (4):
~# logcat -d -b events,main | grep _AUDIT

Or in kernel's printk buffer (5) and logact's kernel buffer (6):
~# dmesg | grep _AUDIT
~# logcat -d -b kernel | grep _AUDIT

audit(0.0:16122): arch=c00000b7 syscall=40 success=yes exit=0 a0=7fcec5db38 a1=7fcec5db3f a2=0 a3=8021 items=1 ppid=761 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=(none) ses=4294967295 comm="busybox" exe="/data/data/com.mixplorer/files/busybox/busybox" subj=u:r:magisk:s0 key="MOUNT_AUDIT"
audit(0.0:16126): arch=c00000b7 syscall=53 success=yes exit=0 a0=ffffff9c a1=7b839180c0 a2=81a4 a3=0 items=1 ppid=11687 auid=4294967295 uid=10135 gid=10135 euid=10135 suid=10135 fsuid=10135 egid=10135 sgid=10135 fsgid=10135 tty=(none) ses=4294967295 comm="Thread-7" exe="/system/bin/app_process64" subj=u:r:untrusted_app:s0:c135,c256,c512,c768 key="CHMOD_AUDIT"
audit(0.0:16141): arch=c00000b7 syscall=35 success=yes exit=0 a0=ffffff9c a1=7bc22a3c40 a2=0 a3=7bdfbd3098 items=2 ppid=11687 auid=4294967295 uid=10135 gid=10135 euid=10135 suid=10135 fsuid=10135 egid=10135 sgid=10135 fsgid=10135 tty=(none) ses=4294967295 comm="pool-2-thread-1" exe="/system/bin/app_process64" subj=u:r:untrusted_app:s0:c135,c256,c512,c768 key="FILESYSTEM_AUDIT"

First line shows that some process running as root with Magisk's SELinux context has made syscall 40 (mount) and the command shows it's MiXplorer app (just as example, I did that myself).
Second line indicates that the app running with UID 10135 has chmoded something.
Third line shows the same app (by making syscall 35) deleted something in /system partition.
This is a simple use case. More recursive rules can be defined to deal with complex situations, interpreting other fields of log as well, as explained here.
To clear rules:
~# auditctl -R /etc/audit-stop.rules

NOTE:

For simple cases where the objective is just to get notified of some filesystem changes (and not to trace the originator), inotify API can be used instead as explained in this answer.
In order to mark all the processes that run before the audit starts auditable by kernel, pass audit=1 boot parameter to kernel, either by editing cmdline in boot.img or use fastboot -c option.
To save audit log to a file, run logcat in background:
logcat -s auditd -b events -f /data/media/0/auditd.log &

so mixplorer changes /system and /vendor files and creates random folders on /sdcard?

@alecxs no this was just an example. I did that myself using MiXplorer. I used this method in past to identify some process which were doing something more complex. Simple eample is to make understanding easy.

Is there a way audit logs be written to the storage instead of remaining in the memory? For example, if I have a directory where random files are being created at random point of time I cannot foresee when they would be created so I would want logs to be stored for a later access despite having a reboot occurred in between this time.

@Firelord logcat -s auditd -b events -f /sdcard/auditd.log &


text:
This app promises to run "fstrim" without root but I am not sure if it works
I am not sure if this app works. Can someone please help me? My phone is new and in its warranty period so I can't root it yet. I tried this app but I am not sure if it actually did something. Unlike the other famous app on the PlayStore for fstrim, it doesn't require root access which is quite incredible.

AFAIK, only apps running as root (UID 0) (1) or system (UID 1000) (2) or with android.permission.MOUNT_UNMOUNT_FILESYSTEMS (3) can do fstrim. But third party apps can neither get UID 0/1000 (without rooting phone), nor the said permission is for third party apps (4).
Also manually sending FITRIM ioctl with fstrim command requires at least capability SYS_ADMIN (5), which is almost root if not full root.
The app you have mentioned asks for permissions CLEAR_APP_CACHE (delete all apps cache data) and KILL_BACKGROUND_PROCESSES (close other apps). So it's quite evident what it must be doing to give a feel of lag-free experience.
PS: You don't need to run fstrim manually in most cases, OS can handle this. See this answer.

I highly doubt it. I use an app called Trimmer which requires root to trim /cache, /data, /system. I installed this app & ran only selecting cache, but it shower trimeed cache & data. I ran a logcat, did not catch anything. So most probably it is a snake oil or at best it clears your cache.


text:
How to block TCP connections?
I have an app, a replica of a shooter game in Android. It is just for experimental use only, me and my friends are testing it. I need to block all TCP connections so I can test my security.
But its servers change IP addresses of the domain, so no matter how many ways I use to block the domain, user still get connection with the server.
Is there a way to only block TCP connection for an app? But only TCP connection, because my playing server is UDP server.
Can I block all incoming TCP connections as well?

Is there a way to only block TCP connections for an app in Android?

Yes, if you have rooted phone:
~# iptables -I OUTPUT -m owner --uid-owner 10275 -p tcp -j DROP

This will block 100% outgoing TCP traffic of app having uid 10275. You can get UID from file /data/system/packages.list.
To block only UDP:
~# iptables -I OUTPUT -m owner --uid-owner 10275 -p udp -j DROP

Or to block both, don't mention any protocol.

Can I block all incoming tcp connections?

INPUT doesn't work with owner module. Better is to just block outbound traffic, incoming is automatically blocked because traffic is initiated from client end i.e. your phone.
See this answer for details.
Also you can use iptables based firewall app like AFWall+ or VPN based firewall like Netguard to block outbound traffic.

Thank you this worked perfectly


text:
What is the "u#_everybody" UID?
In (multi-user) Android there are UIDs like these:

u0_everybody
u10_everybody
u11_everybody

Those seem different to the usual uXX_aYY UIDs used for the applications. What is their purpose? Is this a way to make files available to all applications (share between applications of a user account)?

As stated here:

Cross-user interactions are blocked using the everybody GID.

Android reserves UIDs / GIDs ranging from 10000 to 19999 for apps. AID_EVERYBODY is one of the special groups, which is used to control app's read / write ability to external storage (/sdcard). This group has GID 9997 for device owner. If there are profiles or multiple users, GID takes form XX09997, where XX is UserID. So u11_everybody resolves to UID 1109997 and u11_a500 to 1110500.
Starting with Android 6, every app has it's own view of /sdcard, which is controlled by exposing /data/media/[UserID] with different permissions. This is achieved by making use of an emulated filesystem (previously FUSE, now sdcardfs) and mount namespaces. For device owner i.e. UserId 0, /sdcard appears with following three VIEWs of permission sets:

For processes running in root mount namespace such as init, netd, vold etc., permissions appear as 0.1015, 0771.
For processes having android.permission.READ_EXTERNAL_STORAGE, permissions appear as 0.9997, 0750.
For processes having android.permission.WRITE_EXTERNAL_STORAGE, permissions appear as 0.9997, 0770.

Screenshot shows three emulated VIEWs with different gid and mask values to get different permissions sets:

* Files never have executable permission i.e. mask=6 becomes mask=7 for files.
* mask=23 is appearing wrong, may be a bug? In actual it's mask=27.
Considering three distinct VIEWs, we come with four situations:

Processes running with root privileges i.e. UID 0 have always R/W access to /sdcard. However if a non-privileged process running in root mount namespace wants R/W access to /sdcard, that would be controlled by group AID_SDCARD_RW (GID 1015). An example is ADB daemon which runs with UID / GID 2000 but 1015 in its supplementarry groups.

Since every app runs with its unique UID in a separate mount namespace:

Apps without READ/WRITE_EXTERNAL_STORAGE permissions won't be able to read or write to /sdcard.

Since every app is a member of everybody (9997) group:

Apps with READ_EXTERNAL_STORAGE permission will be able to read the /sdcard.
Apps with WRITE_EXTERNAL_STORAGE permission will be able to write to /sdcard. So the app has full R/W access to shared / external Public Storage including other apps' Private Storage.

There's an exception to above rules for apps; every app has always R/W access to its own External Private Storage. Let's take example of app com.xyz with UID 10500. Apart from internal data directory /data/data/com.xyz, app has a Private Storage directory /sdcard/Android/data/com.xyz with owner UID 10500. So this directory is always readable / writable by the app.
 Please note that /sdcard/Android/data is traversable for all apps, but no R/W access.
In the same way it works for other user accounts / profiles.
Opaque Binary Blobs: (OBB)
Some apps need additional storage to save large files which can't be included in .apk file due to 100MB maximum size limit. There are two possible obb locations where these files are saved: /data/media/obb/ and /sdcard/Android/obb/. The former was introduced before multi-users concept, so it's only available to device owner. Later is available to apps in multi-user accounts / profiles as well.
Access to former is controlled the same way as to /sdcard, while later is always accessible by an app as is the private external storage.

RELATED:

What is /storage/emulated/0/?
Public and Private files on External Storage
Why is the 'storage/emulated/' directory inaccessible?
How Android's permissions mapping with UIDs/GIDs works?
Are multiple-users protected from each other differently than apps?
How disk space is used on Android device? (see directories occupied by an app under APPS SPACE USAGE).

considering the length you did go (i.e. reference parts of the source code) I can appreciate the effort put in this answer and thank you.   Here as comment also some points it'd be great to get confirmed.  1) with Android 6 different users (multi-users) are better isolated, than just mere apps (using mount namespace), true?   2) the various types (i.e. per user) of the everybody (9997) GID serves the purpose to give access to /sdcard access to apps, allow apps to access a common place /sdcard and not only their "app private" /sdcard/Android/data/com.xyz, correct?

there is(?? was )  this obb folder in Android, does this "share between users"-mechanism still work in combination with the mount namespace isolation?

@humanityANDpeace 1) I have mentioned this in a comment on your previous question, can add as answer if needed. The only notable additional isolation between apps of different user accounts is the separate shared storage (i.e. /sdcard). 2) Yes, everybody group is only to control apps' access to shared public external storage (/sdcard) and other apps' private external storage (/sdcard/Android/data/*). An app has always R/W access to its own private external storage /sdcard/Android/data/com.xyz. OBB section is added to answer


text:
How to view network traffic requested by a specific app?
There are lots of discussion on how to see which app is requesting network connection. I have tried the following apps:
tcapturepacket
wifi monitor
connection tracker

However, none of them was useful. For example, for a short period of time, I uploaded a 30KB pcap file which can be viewed here. Still I haven't find out which app is requesting connection and to where it is trying to connect.
I also tried to look at adb logcat, but didn't find useful information. Maybe something has been missed here. Any guess?

If you have rooted phone, go for nethogs (for live monitoring) or iptables (to get statistics) commandline tools. Using VPN or Android stats based apps is the only possible non-root solution. Or refer to this answer for a logcat/dumpsys based solution.

First of all, tracking a UID or PID of a network stream isn't straight forward because these aren't network related but OS related parameters. Proposals and abandoned projects do exist.
Android assigns a unique UID to every installed app just like every human user on Linux has a UID. So we can capture packets sent by a specific UID over the network interfaces to track the usage.
TCPDUMP:
Now how we can capture network traffic? Most of the network sniffers use libpcap family of system-independent libraries for this purpose. It supports BSD Packet Filter (BPF) for in-kernel packet filtering. Some popular utilities that use libpcap include tcpdump, nmap, tshark/wireshark, dumpcap, nethogs etc. Android app Network Utilities and others also make use of tcpdump.
However UID info is not propagated through the AF_PACKET/PF_PACKET channel that pcap uses at OSI Layer 2. So what we can do here is to make use of network sockets (combination of IP and port) being created and used by an app. netstat -tup or ss -tup will show all network sockets with active/established connections. Both tools are available on Android (or you can get a static binary), ss is the newer one. Socket vs. UID information can also be directly read from /proc/net/{tcp,udp}. Android app Netstat Plus works on same principle. This will provide Local Address (socket) being used by a process.
Once we know what sockets are being used by an app (UID), tcpdump -i wlan0 src <IP> and port <PORT> will dump the whole traffic originated from that process.
Similarly a remote socket (if not connected to by multiple apps) can also be used for filtering results.
LIMITATIONS:
However there are some issues with this approach:

Android apps usually launch more than one process at a time in parallel i.e. multiple PIDs working under same UID. So we have to capture traffic from all processes.
Apps keep on creating and deleting sockets. Keeping track of continuously changing sockets is almost impossible particularly when there are a large number of apps accessing network simultaneously.
There is - though rare - possibility that local sockets are being shared by multiple processes on UNIX-like OS's. Remote shared sockets such as UDP/53 which is used for DNS resolution cannot be tracked for a single process. This further weakens the approach.

NetHogs traverses procfs and copes with the above limitations (though not always very successful):

IPTABLES:
The above described shortcomings of a Layer 2 tool can be mitigated using iptables LOG or NFLOG. Layer 2 is just above the Physical Layer i.e. it's the last thing packets encounter before leaving the device. That's why, being at Data Link Layer and working at lower level of net stack, BPF is a kind of stateless packet filtering mechanism as compared to netfilter / iptables which works at OSI Layer 3 (nearer to userspace programs). So iptables can also get information from TCP/IP stack (Layer 4). It filters packets based on their creator UIDs using module owner that interacts with sockets to find packet ownership.
iptables writes to kernel log which can be read using dmesg or logcat. UID of an app can be obtained using some app or read from /data/system/packages.list or pm list packages -U.
# iptables -I OUTPUT -m owner --uid-owner <UID> -j LOG --log-level 7 --log-prefix 'SNIFFER: ' --log-uid
# dmesg -w | grep SNIFFER

Output can be saved to a file and formatted using tools like grep, awk, printf etc. Network Log - though very outdated - works in similar way. AFWall+ is a firewall based on iptables that can log / notify an app's network activity when the app is blocked.
The only downside with this approach is that it cannot be used to sniff traffic from one process when there are multiple processes running with same UID. iptables can't capture packets based on PIDs. They decided not to use iptables with processes because the process is started before it is blocked/sniffed, and program could easily spawn a child process with new PID which would not be blocked / sniffed. Also PIDs are created and destroyed as quick as sockets are. So there is always room for traffic being leaked.
QTAGUID:
owner module won't work for incoming or forwarded traffic because IP packets carry no ownership information. To measure per-app incoming / outgoing network usage, Android patched kernel to include qtaguid module. We can read statistics from /proc/net/xt_qtaguid/stats. With some shell scripting get live data usage since reboot:

However on Android 9+, qtaguid is being replaced with extended BPF (which is also planned to replace netfilter framework in Linux kernel). Related: Which process is responsible for capturing data usage?
IPTABLES + TCPDUMP:
An alternate is to put the outgoing traffic from an app in an NFLOG group and later tcpdump captures packets from that group:
# iptables -I OUTPUT -m owner --uid-owner 1000 -j NFLOG --nflog-group 30
# tcpdump -i nflog:30

This is to ensure that we get closer to physical layer when sniffing outgoing traffic. But it can still give false positives e.g. if packets are dropped / lost in routing tables. That's why sniffers work at OSI layer 2. Or even better is to watch from outside e.g. using a proxy / VPN server or on a tethered PC or at router. But this won't capture traffic on per UID/PID basis.
OTHER OPTIONS:

Use diagnostic tools like strace to track syscalls related to network activity of a process. force_bind and tracedump also work on same principle. Linux kernel's audit subsystem can be used for the same.
Use Network classifier cgroup with iptables NETFILTER_XT_MATCH_CGROUP to sniff traffic from certain process(es).
Use Network Namespaces to isolate processes and read data usage on per interface basis. nstrace works on same principle.
If the intention is entirely to block traffic originating from certain processes, SELinux and seccomp can be used to restrict the processes' ability to create sockets by defining restricted policies and suppressing syscalls respectively.

Most of these are not straightforwardly viable options for Android and require advanced configurations.

ANDROID'S APIs (NON-ROOT OPTIONS):
Some apps like NetGuard use VpnService API of Android to block traffic at Layer 3 (TUN interface). The app can "notify when an application accesses the internet". Per app capturing and tracking (1, 2) is possible using VPN API as Android makes use of UIDs and SOcket_MARKs (1, 2) to control traffic in network Routing Policy (RPDB), just before leaving the device.
Some apps like NetLive make use of NetworkStatsManager, but it lags the real-time usage and "does not update quickly enough", it's "meant to provide historical data".
NOTE: I've no affiliation with any app referenced.

RELATED:

Restricting an app to only send internet traffic but not receive that back?
Why network activity is detected from apps after firewall blocks them?
Capturing mobile phone traffic on Wireshark

With PCAPdroid you can see the individual connections made by the apps. It's an open source tool developed by me which works without root (root is optional). It has lots of interesting features for users security and privacy, check it out

This is exactly what I needed, and I got it to work in 5 minutes. Thank you.

If you only want to track which app performs connections to which server I recommend the app
Net Monitor to you. It acts as a local VPN and is therefore able to detect all network traffic. Furthermore it shows which app has performed the network request (including remote host, ports, and even if the connection is plain or SSL/TLS).
Therefore if you use this app in combination with the capture tools you already mentioned in your question you should able to trace back each and every network connection.


text:
How does SuperSU check if a phone is rooted?
I have a rooted custom device (Android 8.0), I can use adb and run su and do whatever I want in the shell. But SuperSU or any other app cannot find root. I have made a symlink from /system/xbin/su to /system/bin/su but it still does not work.

/system/xbin/su is a normal su binary that's shipped with userdebug or engineering builds of ROMs. It gets you root access by making syscall setuid. On the other hand, with SuperSU or Magisk root, a special binary is placed at /system/bin/su (or some other path) which works quite differently. For details see How Magisk works?.
So, with only a working /system/xbin/su executable, your device isn't essentially "rooted". SuperSU or Magisk won't work with this binary. And so the apps cannot get root access.
RELATED: What special privileges “/system/xbin/su” does have w.r.t. root access?


text:
Storage location of "adb_keys"
I have a Galaxy s3 (I9300) that has a broken touch screen (display is fine). I therefore can not click the authorization dialog that pops up when I try to access the device via adb on any ROMs above Android 4.2 as they require authorization to access the device via adb.
On 4.2 and 4.3 of the stock ROMs, I am able to copy my ~/.android/adbkey.pub  file from my machine to /data/misc/adb/adb_keys on the device via CWM recovery and gain access. I have tried this with LineageOS 14 which is on Android 7.1.1 and I still don't get access. I am wondering where the adb_keys file is located on android 7.1.1 so I can do the same.

Since Android 4.2 when public key authentication was added to ADB, up to latest release 10, there are only two possible locations for adb_keys on stock Android:

On the device, vendors public keys are installed at build time in /adb_keys. User-installed keys are stored in /data/misc/adb/adb_keys.

So is the case with Android 7.1.1:
static const char *key_paths[] = {
    "/adb_keys",
    "/data/misc/adb/adb_keys",
    NULL
};

First one is only found on userdebug/eng ROMs. Also on debuggable builds, you can set ro.adb.secure to 0 to "allow adbd to connect without authentication". However "user builds filter out PRODUCT_ADB_KEYS, so no /adb_keys will be included". (Source)
So the RSA public keys added to /data/misc/adb/adb_keys should work. Make sure proper ownership (system:shell), mode (0640) and SELinux label (u:object_r:adb_keys_file:s0) are set on the file and restart adbd after adding key(s). Also check correct line endings (use dos2unix) after adding key(s) and make sure the right private key pair is available to adb server on PC. Path is ~/.android/ on Linux and %userprofile%\.android\ on Windows, or add the key filename/directory to ADB_VENDOR_KEYS environment variable.

RELATED:

Why “adb root” does nothing?

How do I apply a SELinux label to a file? semanage doesn't exist on Android, or at least my OnePlus 6.

@Nowaker use chcon. SELinux policy is not configurable on Android devices, unlike PCs. So there's no semanage.


text:
How to move 7GB ext4 partition on external SD card to 30GB partition on another SD card?
I had rooted my Android Lollipop 5.1.1  phone and installed Link2SD and linked installed apps on ext4 7GB 2nd partition of external SD card of 16GB size . The apps installed occupied 6.5GB space and I am getting low space now. I got 64GB external SD card and want to dedicate 30GB.
I created image of 7GB 2nd partition of external SD card through following command:
dd bs=4k count= if=/dev/block/mmcblk1p2 | gzip -5 -c > /storage/sdcard1/sdcard2root.img.gz

Now whats the way to clone this image to a 30GB partition?

note that (gzip) compression only works on /dev/block/dm-0 (but not actually on /dev/block/mmcblk0p30) because of encryption

It's easy to achieve on a Linux PC:

Attach both SD cards to PC.
Dump 2nd partition from old SD card to new one. It's also possible directly from Android device. See Creating Partition Dump.
Resize filesystem size to 30GB (the new partition size) using resize2fs.

COPY WHOLE FILESYSTEM:
The above approach works on Android too if you are able to attach new SD card through USB OTG SD card reader, while the old one is inside phone.
Or you can do it in 2 steps, as you are already trying:

Create partition dump:
~# gzip -9ck /dev/block/mmcblk1p2 >/storage/sdcard1/sdcard2root.img.gz

You can use dd or cat or even cp. Make sure you have enough space on primary external (physically internal) storage to save dumped (and optionally compressed) image of SD card's 2nd partition.
Compression is useful only with sparseness. To avoid copying freed filesystem blocks (of deleted files) use e2image -rap. Or discard logical to physical block mapping using fstrim (on mounted filesystem) or e2fsck -E discard, and drop page cache using sync; echo -n 1 >/proc/sys/vm/drop_caches.
Insert new SD card and do partitioning using parted or gdisk or fdisk.
Write partition image to new SD card:
~# gzip -dck /storage/sdcard1/sdcard2root.img.gz >/dev/block/mmcblk1p2

Maximize filesystem size to partition size:
~# resize2fs /dev/block/mmcblk1p2

COPY FILESYSTEM CONTENTS:
Another method is to only copy/move filesystem contents (files, directories etc.) and not the whole filesystem structure. But files' metadata needs to be preserved, or things may break (since the partition is to be mounted inside /data). It includes timestamps, permission mode, owner, group and extended attributes, particularly SELinux contexts. Some executable binaries (in /system) might also have file capabilities set (saved as extended attributes) but that's usually not required for user data. Other metadata like ACLs (also saved as extended attributes) and file attributes (inode flags) are not generally used on Android devices.
On Linux tools like rsync (or even cp) can preserve the required metadata. For reference see this and this answer. On Android (to move the contents in 2 steps) tar is a good choice:
~$ cd /path/to/old_sdcard/mountpoint/
~$ tar --create --preserve-permissions --selinux --verbose --gzip --file=/storage/sdcard1/sdcard2root.tar.gz .

Insert new SD card, do partitioning (if required), and create filesystem using mkfs.ext4 (by default it takes whole partition). To restore backup:
~$ cd /path/to/new_sdcard/mountpoint/
~$ tar --extract --preserve-permissions --selinux --verbose --gunzip --file=/storage/sdcard1/sdcard2root.tar.gz

thanx for answering  i will  try it  and let you know i have windows  so i cant try  linx option but will try  e2image or dd commands thanx a lot again

Android tar binary doesn’t have selinux option. So is busybox.

@KhurshidAlam https://forum.xda-developers.com/t/exe-static-linux-binaries-for-arm-android-cryptsetup-encfs-f2fs-tools-testdisk-photorec.3709380/page-8#post-79825447

@IrfanLatif Thanks. But how do you install those ? Adb push /system/bin ? Wouldn’t it overwrite existing  ?


text:
How to disable USB OTG on Android 6+?
I need to disable the OTG (USB) on Android 8. I already did it on Android 6 by disabling a permission on the file android.hardware.usb.host.xml but it is not working anymore on Android 8.1.

android.hardware.usb.host.xml file - located under /vendor/etc/permissions/ or /system/etc/permissions/ before Treble - contains feature name="android.hardware.usb.host" which indicates that the device can communicate with USB devices as the USB host. This feature is evaluated by PackageManager (along with other software / hardware features) and used by Google Play to filter (in)compatible apps based on the value <uses-feature android:name="android.hardware.usb.host" /> in AndroidManifest.xml. See details here.
Also if the device doesn't support USB host mode, UsbHostManager service is not started, so apps like this which use USB host APIs cannot connect to USB devices. But any connected device is still detected by kernel and appears under /sys and /dev.
To confirm if the device supports USB host mode:
~$ pm list features | grep usb.host
feature:android.hardware.usb.host

~$ dumpsys usb | grep host_manager
  host_manager={

These lines shouldn't appear after you delete android.hardware.usb.host.xml file.

However since Android 6 USB storage devices such as a USB stick are handled by vold, which doesn't depend on the feature discussed above. vold listens to kernel through a netlink socket for block device uevent (1) and matches that with some entry in fstab (2). Then it creates disk and partition nodes in /dev/block/vold/ (3), checks filesystem for errors and mounts in /mnt/media_rw/ (also emulates SD cards in /mnt/runtime/) (4). After that ExternalStorageProvider (a content provider) is triggered which grants apps URI access to OTG storage through SAF or  Scoped Directory Access.
So in order to disable auto-mounting of USB storage devices by vold, you need to remove the corresponding entry from fstab as referenced here:
/devices/*/xhci-hcd.0.auto/usb*    auto    auto    defaults    voldmanaged=usb:auto

fstab is found under /odm/etc/ or /vendor/etc/. Before Treble it was in rootfs (/). See details in this answer.

At least for Android 7 (fstab in /) this does not seem so easy, because the root partition gets rewritten on every reboot, so changing fstab does nothing. It seems you have to unpack boot.img change fstab and pack it again, because on boot, this filesystem gets written to root.

@user136036 correct.


text:
How to make Termius look for hostnames on the local network first?
I have four devices:

Windows 10 PC
Android Phone (v6.0.1)
Internet Router
"servername" (Raspberry Pi 4)

All are connected locally using Wifi (not that it should matter) using the simplest possible configuration imaginable.  Every device has working internet access.  Everything talks with everything else nicely apart from when I try to use Termius on Android to ssh into "servername".
On the PC I can simply issue the command putty fred@servername and I can login without difficulties, as one would expect.
However Termius on the Android phone does not seem to understand that "servername" is attached locally to the same wifi network as the phone itself.  If I open a local SSH session on the phone itself and ping "servername", then it appears to be going after some random internet IP address (92.xxx.xxx.xxx) and fails to login.
If I use the server's local IP address (192.168.xxx.xxx) then Termius can SSH to it with no issues.
So, how can I persuade Termius (free version) to understand local network host names?  I cannot find any settings that correspond to this problem.

So, how can I persuade Termius (free version) to understand local network host names?

In fact you have to persuade Android OS, not a specific app. Resolving hostnames is handled by Android's C library to which apps are linked through APIs at the time of compiling.

On the PC I can simply issue the command putty fred@servername and I can login without difficulties, as one would expect.

You haven't mentioned which Wi-Fi router you are using and if you have a DHCP/DNS server running on local network or not. But to resolve local hostnames on Android, you must have a local DNS server running. Usually Wi-Fi router is the DHCP/DNS server.

I cannot find any settings that correspond to this problem.

That's the difficult part, you have to configure your phone to use a local DNS server but Android doesn't provide a straightforward way to do this.

If I open a local SSH session on the phone itself and ping servername, then it appears to be going after some random internet IP address (92.xxx.xxx.xxx) and fails to login.

It indicates that Android phone is sending DNS queries to internet. You have to make sure that DNS queries are sent to the local DNS server only. Public DNS servers don't know what hostnames you have set on your private network. Android loves Google so much, so you will often find queries going to 8.8.8.8 (may be when router is advertising the IPv6 DNS server). Configure static IP in Wi-Fi settings to set IP address of local DNS server as the first (and preferably only) DNS. Or if you have root you can use Android kernel's built-in firewall netfilter to force a nameserver. Since DNS uses UDP port 53, do a Destination Network Address Translation (DNAT):
~# iptables -t nat -I OUTPUT -p udp --dport 53 -j DNAT --to 192.168.1.1:53

Non-root solution which works for both Wi-Fi and Mobile data is to use a VPN app like Virtual Hosts which intercepts DNS traffic and makes queries to configured upstream DNS server.
This should resolve your problem.
For more details please see How to ping a local network host by hostname?.
Related: How DNS works on Android?


text:
How to change random filesystem label on USB OTG?
I am without PC right now, but I need to Format USB Drive (to FAT32 or Ext4) with Samsung S8 (Android 9) and change label. But I can't find any app that can do this. I can format USB drive in Storage Menu, but without any options, it just gives it Random number name (I can see it in Total commander) and I think it's Ext4, but again no options. Is there any option to rename the Label?
I found they there is Aparted app (port of gparted) but it needs ROOT and also it gives random label.
I also tried to rename drive in Total commander, but it says it's ranamed, but in reality it has old label. Thanks for any help :).

Renaming of volumes usually requires root permission. As Android does not allow to set a label when formatting the volume any other app without root permission will not be able to change the label.

It's not possible to create filesystem or set label without root access. Block devices in /dev/block/ are created with ownership 0:0, mode 0600. Also apps aren't allowed to access SELinux context device or block_device set on /dev and /dev/block. You can use a rooted device or custom recovery like TWRP. Or use a PC (if available). On Linux and Android command-line is same.

I need to Format USB Drive (to FAT32 or Ext4)

Use mkfs.fat -F32 -n <LABEL> or mkfs.ext4 -L <LABEL> to create filesystem with required label. Or later use fatlabel/mlabel or e2label/tune2fs to change label of an already created filesystem.

I can format USB drive in Storage Menu, but without any options, it just gives it Random number name

The random number is not name (or label), it's filesystem UUID (32-digits long string on Linux filesystems like ext2/3/4) or Volume ID (8-digits long string on Windows filesystems like NTFS/FAT32/exFAT). Similarly GUID partitions have a PARTUUID and PARTLABEL (as reported by blkid).
USB OTG and external SD card is mounted by Volume Daemon (vold) on Android. Since Android 6 by default vold uses filesystem UUID or VolumeID to create a mount path (which is not an actual path in case of USB OTG) like /storage/[UUID]:

"Developers may continue to build paths dynamically or statically depending on their use case. Including the UUID in the path identifies each card to make location clearer for developers. (For example, /storage/ABCD-1234/report.txt is clearly a different file than /storage/DCBA-4321/report.txt.)"

So even if you set label, whatever filesystem you choose, you will see the random number in path. However, like label, you can also set UUID/VolumeID of your choice (in case you want to retain same file path after formatting). Some file explorers, though, show filesystem label as storage name along with path.