ADB Shell Android how to delete group of contacts? - android

I am using adb shell to delete contacts from phone. For example if I have 50 contacts, how to delete first 10?
I use this to delete one by one, is there a way to delete more contacts at once, by one command, to make process faster?
adb shell content delete --uri content://com.android.contacts/contacts/1
I am not looking to clear all contacts, but to delete some and to leave the rest of the contacts.

First, you can query all your contacts:
$ adb shell content query --uri content://com.android.contacts/contacts
Row: 0 last_time_contacted=0, phonetic_name=NULL, custom_ringtone=NULL, contact_status_ts=NULL, pinned=0, photo_id=NULL, photo_file_id=NULL, contact_status_res_package=NULL, contact_chat_capability=NULL, contact_status_icon=NULL, display_name_alt=Doe, John, sort_key_alt=Doe, John, in_visible_group=0, starred=0, contact_status_label=NULL, phonebook_label=S, is_user_profile=0, has_phone_number=1, display_name_source=40, phonetic_name_style=0, send_to_voicemail=0, lookup=4073r100-4D5331434D4F31394337453333, phonebook_label_alt=S, contact_last_updated_timestamp=1571690183031, photo_uri=NULL, phonebook_bucket=19, contact_status=NULL, display_name=John Doe, sort_key=John Doe, photo_thumb_uri=NULL, contact_presence=NULL, in_default_directory=1, times_contacted=0, _id=100, name_raw_contact_id=100, phonebook_bucket_alt=19
Row: 1 last_time_contacted=0, phonetic_name=NULL, custom_ringtone=NULL, contact_status_ts=NULL, pinned=0, photo_id=NULL, photo_file_id=NULL, contact_status_res_package=NULL, contact_chat_capability=NULL, contact_status_icon=NULL, display_name_alt=Doe, Jane, sort_key_alt=Doe, Jane, in_visible_group=0, starred=0, contact_status_label=NULL, phonebook_label=C, is_user_profile=0, has_phone_number=1, display_name_source=40, phonetic_name_style=0, send_to_voicemail=0, lookup=4073r101-2D374B394D4F3929432B512B312D3D, phonebook_label_alt=B, contact_last_updated_timestamp=1571690183031, photo_uri=NULL, phonebook_bucket=3, contact_status=NULL, display_name=Jane Doe, sort_key=Jane Doe, photo_thumb_uri=NULL, contact_presence=NULL, in_default_directory=1, times_contacted=0, _id=101, name_raw_contact_id=101, phonebook_bucket_alt=2
Row: 2 last_time_contacted=0, phonetic_name=NULL, custom_ringtone=NULL, contact_status_ts=NULL, pinned=0, photo_id=NULL, photo_file_id=NULL, contact_status_res_package=NULL, contact_chat_capability=NULL, contact_status_icon=NULL, display_name_alt=Roe, Jane, sort_key_alt=Roe, Jane, in_visible_group=0, starred=0, contact_status_label=NULL, phonebook_label=A, is_user_profile=0, has_phone_number=1, display_name_source=40, phonetic_name_style=0, send_to_voicemail=0, lookup=4073r102-29432F4B31294D55393F3F, phonebook_label_alt=W, contact_last_updated_timestamp=1571690183031, photo_uri=NULL, phonebook_bucket=1, contact_status=NULL, display_name=Jane Roe, sort_key=Jane Roe, photo_thumb_uri=NULL, contact_presence=NULL, in_default_directory=1, times_contacted=0, _id=102, name_raw_contact_id=102, phonebook_bucket_alt=23
Row: 3 last_time_contacted=0, phonetic_name=NULL, custom_ringtone=NULL, contact_status_ts=NULL, pinned=0, photo_id=NULL, photo_file_id=NULL, contact_status_res_package=NULL, contact_chat_capability=NULL, contact_status_icon=NULL, display_name_alt=Roe, Richard, sort_key_alt=Roe, Richard, in_visible_group=0, starred=0, contact_status_label=NULL, phonebook_label=U, is_user_profile=0, has_phone_number=1, display_name_source=40, phonetic_name_style=0, send_to_voicemail=0, lookup=4073r103-51432B313D2943434F2B4B31315B31, phonebook_label_alt=B, contact_last_updated_timestamp=1571690183031, photo_uri=NULL, phonebook_bucket=21, contact_status=NULL, display_name=Richard Roe, sort_key=Richard Roe, photo_thumb_uri=NULL, contact_presence=NULL, in_default_directory=1, times_contacted=0, _id=103, name_raw_contact_id=103, phonebook_bucket_alt=2
You can use sed to, e.g., select the first three rows and trim them to their ids (i.e., the _id attribute:
$ adb shell content query --uri content://com.android.contacts/contacts | sed -n '1,3 s/^.* _id=\([[:digit:]]\+\),.*$/\1/p'
100
101
102
This sed command says not to print anything by default (the -n switch), but for lines 1 to 3 substitute the lines with the value of the _id and print the result (the p flag at the end of the substitution).
I now tried to loop over this output and issue an adb shell delete for every id, but this does not work. It will only issue a command for the first id. I don’t know exactly why this is, but it must have something to do with what the adb shell command does.
As a workaround, we can do all this directly in the adb shell. So, first execute adb shell and then in that shell you can directly use the content command. For better readability I first save the ids in a file and then loop over its lines. Of course, it’s perfectly possible to just pipe the output of sed into the while loop.
mycomputer$ adb shell
android$ content query --uri content://com.android.contacts/contacts | sed -n '1,3 s/^.* _id=\([[:digit:]]\+\),.*$/\1/p' >ids
android$ while read -r id; do content delete --uri content://com.android.contacts/contacts/"$id"; done <ids

Related

adb command for call state details

I would like to get an adb command with a response of a code that map to current call state
the call state I mean are those in following link
https://developer.android.com/reference/android/telecom/Call.html#STATE_ACTIVE
those values are more representative and getting those values in command shell upon executing the adb command will be very helpful for me
I have only managed to get them on a log as per following command
adb logcat -d | findstr -i InCallFragment.setCallState
but I couldnot get the state value as a response of any adb command
Any help will be much appreciated
Thanks
for more illustration
please connect a phone to the PC , do a phone call and end it
use the above command to dump the buffer
refer to the state value
You can use adb shell service call telecom [code] command. The codes for getCallState() will be different depending on the Android version:
6.0.1: 26
7.0.0: 27
7.1.0: 27
7.1.2: 27
8.0.0: 29
8.1.0: 29
I have achieved what you want to do by modifying a custom ROM (LineageOS) and adding an android.util.Log line to print every state.
In my case I modified class:
Call
frameworks/opt/telephony/src/java/com/android/internal/telephony/Call.java
And what I did is inside getState(...) method, adding this line:
Log.i(myTAG, "getState state->" + mState.name());
With this what I have to do is search for myTAG in adb logcat.
I think otherwise you wont be able to do it...
You can dumpsys telecomm service:
adb shell dumpsys telecom
CallsManager:
mCalls:
[TC#7, ACTIVE, com.android.phone/com.android.services.telephony.TelephonyConnectionService, tel:***, A, childs(0), has_parent(false), [Capabilities: CAPABILITY_HOLD CAPABILITY_SUPPORT_HOLD CAPABILITY_MUTE CAPABILITY_CANNOT_DOWNGRADE_VIDEO_TO_AUDIO], [Properties:]]
mCallAudioManager:
All calls:
TC#7
Active dialing, or connecting calls:
TC#7
Ringing calls:
Holding calls:
Foreground call:
[TC#7, ACTIVE, com.android.phone/com.android.services.telephony.TelephonyConnectionService, tel:***, A, childs(0), has_parent(false), [Capabilities: CAPABILITY_HOLD CAPABILITY_SUPPORT_HOLD CAPABILITY_MUTE CAPABILITY_CANNOT_DOWNGRADE_VIDEO_TO_AUDIO], [Properties:]]
mTtyManager:
mCurrentTtyMode: 0
mInCallController:
mInCallServices (InCalls registered):
.
.
Call TC#7 [2018-06-05 14:38:41.505](MO - outgoing)
To address: tel:***
14:38:41.508 - CREATED:PCR.oR#DMA
14:38:41.511 - SET_CONNECTING (ComponentInfo{com.android.phone/com.android.services.telephony.TelephonyConnectionService}, [8c3d1caa626a79d75b154221ea94852a62fee7b3], UserHandle{0}):PCR.oR#DMA
14:38:41.847 - AUDIO_ROUTE (Leaving state QuiescentEarpieceRoute):PCR.oR->CAMSM.pM_2001->CARSM.pM_SWITCH_FOCUS#DMA_2_2
14:38:41.847 - AUDIO_ROUTE (Entering state ActiveEarpieceRoute):PCR.oR->CAMSM.pM_2001->CARSM.pM_SWITCH_FOCUS#DMA_2_2
14:38:43.442 - BIND_CS (ComponentInfo{com.android.phone/com.android.services.telephony.TelephonyConnectionService}):NOCBIR.oR#DMU
14:38:43.519 - CS_BOUND (ComponentInfo{com.android.phone/com.android.services.telephony.TelephonyConnectionService}):SBC.oSC#DMY
14:38:43.519 - START_CONNECTION (tel:***):SBC.oSC#DMY
14:38:43.703 - CAPABILITY_CHANGE (Current: [[ sup_hld mut !v2a]], Removed [[]], Added [[ sup_hld mut !v2a]]):CSW.hCCC#DMg
14:38:43.706 - SET_DIALING (successful outgoing call):CSW.hCCC#DMg
14:38:47.560 - SET_ACTIVE (active set explicitly):CSW.sA#DNM
14:38:47.639 - CAPABILITY_CHANGE (Current: [[ hld sup_hld mut !v2a]], Removed [[]], Added [[ hld]]):CSW.sCC#DNY
Timings (average for this call, milliseconds):
bind_cs: 77.00
outgoing_time_to_dialing: 187.00

Delete contact via adb

How can I delete a contact using the adb shell? I know the raw_contact_id of the contact.
I tried different ways but none with success.
To edit a contact I used the command
am start -a android.intent.action.EDIT content://contacts/people/8
and it worked.
But deleting it with
am start -a android.intent.action.DELETE content://contacts/people/8
does not work and showed me this error message:
Activity not started, unable to resolve Intent { act=android.intent.action.DELETE dat=content://contacts/people/8 flg=0x10000000 }
(flg=0x10000000 means FLAG_RECEIVER_FOREGROUND, I think it is set automatically.)
Do I have to set some flags? Or why does this not work?
A more fancy way is to simulate the process, how a normal user deletes the contact.
am start -a android.intent.action.VIEW content://contacts/people/8
input keyevent 22 # right button
input keyevent 22 # reach field in the right corner
input keyevent 66 # enter
input keyevent 20 # go down
input keyevent 20 # go down --> reached "Delete"
input keyevent 66 # enter
input keyevent 22 # button "Ok"
input keyevent 66 # enter
After clicking on the "Delete" button, the contact app always crashes (Contacts has been closed). Using these key events never worked on my emulator -- if I click on the buttons by hand (with my mouse), everything works…
Third way could be deleting the entries in the databases. This does not make sense for me, because then they are completely deleted -- if they are deleted the "normal" way, the contacts are still stored in some tables (like "deleted contacts").
The content://contacts provider has been deprecated. You should be using content://com.android.contacts instead:
$ adb shell content query --uri content://com.android.contacts/contacts
To remove contact (where's id = 1)
$ adb shell content delete --uri content://com.android.contacts/contacts/1
To remove all contacts at once
$ adb shell pm clear com.android.providers.contacts

Iptables Log Output Cleaning

I am trying to minimize the iptables log , but I don't know how. I read some tutorials about grep,cut and awk. But still I can't do nothing useful. I would like to achieve a result like SRC=192.168.1.6 DST=192.168.1.2 PROTO=TCP SYN.
This is how 2 packets from the original log look like:
<4>[1133131.431453] [IPT IN START] IN=wlan0 OUT= MAC=08:60:6e:a5:bc:0b:00:16:cf:b9:08:2c:08:00:45:00:00:2c:51:56:00:00:3
8:06:ae:1d:c0:a8:01:06:c0:a8:01:02:f8:a4:08:01:f2:0e:30:9c:00:00:00:00:60:02:04:00:ed:7c:00:00:02:04:05:b4:00:00:00:00:0
0:00:00:00 SRC=192.168.1.6 DST=192.168.1.2 LEN=44 TOS=0x00 PREC=0x00 TTL=56 ID=20822 PROTO=TCP SPT=63652 DPT=2049 WINDOW
=1024 RES=0x00 SYN URGP=0
<4>[1133131.440239] [IPT IN START] IN=wlan0 OUT= MAC=08:60:6e:a5:bc:0b:00:16:cf:b9:08:2c:08:00:45:00:00:2c:48:6d:00:00:3
4:06:bb:06:c0:a8:01:06:c0:a8:01:02:f8:a4:04:42:f2:0e:30:9c:00:00:00:00:60:02:04:00:f1:3b:00:00:02:04:05:b4:00:00:00:00:0
0:00:00:00 SRC=192.168.1.6 DST=192.168.1.2 LEN=44 TOS=0x00 PREC=0x00 TTL=52 ID=18541 PROTO=TCP SPT=63652 DPT=1090 WINDOW
=1024 RES=0x00 SYN URGP=0
This is what I've tried: fgrep '[IPT IN ' /proc/kmsg |cut -d" " -f1-4,9,13,14,21,22,23,26
And that was the result:
<4>[1132271.745701] [IPT IN START] DST=192.168.1.2 TTL=45 ID=30608
<4>[1132271.747764] [IPT IN START] DST=192.168.1.2 TTL=54 ID=63992
<4>[1132271.751983] [IPT IN START] DST=192.168.1.2 TTL=52 ID=4162
Btw , I tried few more options , but this one was the only one which returned some results.
Thanks in advance.
p.s Those are iptables_arm , I am experimenting with my tablet. I am trying to read those results from my android program in order to capture portscan launched from my laptop.
I do create a simple log-file in real time, here is how to do it:
tail --follow=name /var/log/yourLogfile | awk '{print $8,$9,$15,$17 | "tee /var/log/newlog"}' &
This creates a new log file /var/log/newlog with data you like to have in it.
i would have just used awk and counted the whitespace separated columns i want:
grep "IPT IN" /proc/kmsg | awk '{print $1 $2 $xy1 $xy2 $xy3}'
the xy1,2,3 parts have to be replaced by the specific number of the column you want ;-)

adb shell input unicode character

Knowing the basic key mappings described in ADB Shell Input Events I get the emulation of text input and special keys working quite well. But what about Unicode characters? For instance I want to use umlauts from the German QWERTZ keyboard layout.
This gets me:
$ adb shell input text ö
Killed
So it seems to crash and
adb shell input text \xFC
prints xFC on the input. I have tried to the the events with getevent but I haven't found a direct mapping, I've also looked into the keymapping file /system/usr/keylayout/Qwerty.kl
I believe the only possibility is via the clipboard, but as pointed out in the question Pasting text into Android emulator clipboard using adb shell it seems to be unknown how to use it for Android Ice Cream Sandwich or later..
I wrote a virtual keyboard that accept broadcast intent, so you can send unicode characters to the editText view via adb.
for e.g.
adb shell am broadcast -a ADB_INPUT_TEXT --es msg "你好嗎! Hello!"
Here is the github project:
https://github.com/senzhk/ADBKeyBoard
Hope this little project would help.
Actually ADBKeyBoard is very good! Thanks for Eric Tang !
Some useful extensions for comfortable usage:
Switch to ADBKeyBoard from adb:
adb shell ime set com.android.adbkeyboard/.AdbIME
Check your available le virtual keyboards:
ime list -a
Use simple quote characters -not double as in example above- if your shell not accepts "!" (explanation sign)
adb shell am broadcast -a ADB_INPUT_TEXT --es msg 'Accented characters here'
Switch back to original virtual keyboard: (swype in my case...)
adb shell ime set com.nuance.swype.dtc/com.nuance.swype.input.IME
Use adb over wifi to simplify your life... :)
input won't work because it can only send single key event through the virtual keyboard (check the source code if you don't know what I mean).
I think the only way left is using Instrumentation. I guess you can create a test for your Activity and then do something like this:
final Instrumentation instrumentation = getInstrumentation();
final long downTime = SystemClock.uptimeMillis();
final long eventTime = SystemClock.uptimeMillis();
final KeyEvent altDown = new KeyEvent(downTime, eventTime, KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_GRAVE, 1, KeyEvent.META_ALT_LEFT_ON);
final KeyEvent altUp = new KeyEvent(downTime, eventTime, KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_GRAVE, 1, KeyEvent.META_ALT_LEFT_ON);
instrumentation.sendKeySync(altDown);
instrumentation.sendCharacterSync(KeyEvent.KEYCODE_A);
instrumentation.sendKeySync(altUp);
instrumentation.sendKeySync(altDown);
instrumentation.sendCharacterSync(KeyEvent.KEYCODE_E);
instrumentation.sendKeySync(altUp);
instrumentation.sendKeySync(altDown);
instrumentation.sendCharacterSync(KeyEvent.KEYCODE_I);
instrumentation.sendKeySync(altUp);
instrumentation.sendKeySync(altDown);
instrumentation.sendCharacterSync(KeyEvent.KEYCODE_O);
instrumentation.sendKeySync(altUp);
instrumentation.sendKeySync(altDown);
instrumentation.sendCharacterSync(KeyEvent.KEYCODE_U);
instrumentation.sendKeySync(altUp);
This will send the modified keys: àèìòù
update 2022
https://stackoverflow.com/a/71367206/236465 shows another solution using AndroidViewClient/culebra and CulebraTester2-public backend.

Set clipboard text via adb shell as of API level 11

Before API level 11, it was possible to set the content of the clipboard by using the service program on the adb shell:
service call SERVICE CODE [i32 INT | s16 STR] ...
Options:
i32: Write the integer INT into the send parcel.
s16: Write the UTF-16 string STR into the send parcel.
There were three integer codes to define the methods:
1 TRANSACTION_getClipboardText
2 TRANSACTION_setClipboardText
3 TRANSACTION_hasClipboardText
For instance this command
$ adb shell service call clipboard 2 i32 1 i32 1 s16 "Hello Android!"
set the clipboard's content to "Hello Android!". As of API level 11 the listed methods are deprecated and the new ones take ClipData as an argument. How do you set the clipboard content now via adb shell?
You've asked two different questions here. The service calls are not related to the API functions.
Android is in general overly-aggressive about marking APIs as deprecated. In this case, it only means that there are new functions with more functionality. The functionality of getText(), hasText(), and setText() still exists and those functions will continue to work, but they are now implemented as trivial wrappers around the newer functions.
As far as the service calls go, those are an internal implementation detail and as you've noticed are not guaranteed to work across Android versions. If you peer into the Android source code, you'll find these transactions currently defined:
TRANSACTION_setPrimaryClip = 1
TRANSACTION_getPrimaryClip = 2
TRANSACTION_getPrimaryClipDescription = 3
TRANSACTION_hasPrimaryClip = 4
TRANSACTION_addPrimaryClipChangedListener = 5
TRANSACTION_removePrimaryClipChangedListener = 6
TRANSACTION_hasClipboardText = 7
The source code also indicates what parameters these transactions require. Unfortunately, TRANSACTION_setPrimaryClip requires a ClipData, which is not an i32 or an s16 and thus is not compatible with service call. We have bigger problems than that however; these transactions require the calling package name as a parameter, and the clipboard service validates that the specified package name matches the calling uid. When using the adb shell, the calling uid is either UID_ROOT or UID_SHELL, neither of which owns any packages, so there is no way to pass that check. Simply put, the new clipboard service cannot be used this way.
What can you do about all this? You can create your own service for manipulating the clipboard from the commandline and install it onto your device. I don't know if there's any way to extend service call, but you can use am startservice as a suitable replacement. If you've created and installed that custom clipboard service, then you could invoke it as:
am startservice -a MySetClipboard -e text "clipboard text"
The code to implement this service could look like this:
public MyService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) {
String text = intent.getStringExtra("text");
ClipboardManager.setText(text);
stopSelf();
return START_NOT_STICKY;
}
}
The service should have an intent-filter that declares it capable of handling the MySetClipboard intent action.
I found a way to do this using com.tengu.sharetoclipboard. You install it with F-Droid, then you start it with am over adb with the following arguments:
adb shell am start-activity \
-a android.intent.action.SEND \
-e android.intent.extra.TEXT <sh-escaped-text> \
-t 'text/plain' \
com.tengu.sharetoclipboard
<sh-escaped-text> is the new contents of the android clipboard. Note that this text must be escaped so that it is not interpreted specially by sh on the remote end. In practice, that means surrounding it with single quotes and replacing all single quotes with '\''. For instance, this would work fine if the local shell is fish:
adb shell am start-activity \
-a android.intent.action.SEND \
-e android.intent.extra.TEXT '\'I\'\\\'\'m pretty sure $HOME is set.\'' \
-t 'text/plain' \
com.tengu.sharetoclipboard
After fish parses it, the argument is 'I'\''m pretty sure $HOME is set.'. After sh parses it, the argument is I'm pretty sure $HOME is set..
Here's a python script to simplify this process:
#!/usr/bin/env python
import sys
import os
def shsafe(s):
return "'" + s.replace("'", "'\\''") + "'"
def exec_adb(text):
os.execvp('adb', [
'adb', 'shell', 'am', 'start-activity',
'-a', 'android.intent.action.SEND',
'-e', 'android.intent.extra.TEXT', shsafe(text),
'-t', 'text/plain',
'com.tengu.sharetoclipboard',
])
if sys.stdin.isatty():
if len(sys.argv) >= 2:
exec_adb(' '.join(sys.argv[1:]))
else:
sys.stderr.write(
'''Send something to the android clipboard over ADB. Requires
com.tengu.sharetoclipboard.
acb <text>
<some command> | acb
acb <some_text_file.txt''')
exit(1)
else:
exec_adb(sys.stdin.read())

Categories

Resources