Shell scripts for Android | We discuss residents and other useful commands in everyday life.

Rep: (947)
Shell scripts for Android

The topic is devoted to the creation, debugging of scripts on the shell, as well as the development and study of various utilities command line Android.
For the full implementation of the desired under Android, as a rule, you will need root-rights and busybox.
This topic has grown from the topic.Tasker(parent theme), so don’t be surprised if you are suddenly sent there. (Tasker is a shell in Android.) From this topic has grown subsidiaryLinux kernel from the insideAll questions on the kernel should be asked in it.
Recipes, ideas, semi-ready examples.
Interception of hardware buttons, this script began with this script. It is recommended that you read the discussion.original postin the subjectTasker. Over the years, the script has found many different uses, seeMAX 3Tasker in the same topic, recipe "We catch events in logcat" here.
Modern lookto the button interception script: work on errors, performance evaluations, optimization.
Recipes withbusybox inotifyd
- Monitoring block devices(connect / disconnect flash drives and not only)
- Automate downloading files via torrent
- Spy on screenshots
Processing the status bar notificationaka Search in a file by a dynamically formed template from a pipe (pipe), recipes - in the discussion.
Recipes withservice call
- Read / write clipboardvia clipboard service [interfaceIClipboard]
- Mounting / Unmounting Disksvia mount service [interfaceIMountService]
- Enable USB MTPvia usb service [interfaceIusbmanager]
Search for service method numbers forservice call: with Taskertime, two; withusingJaDX (themeon the forum)
Reading contactsthrough contacts provider and utilitycontent
Showdowns with selinux
- More discussion selinux, which are key to understanding the work selinux in Android:
1 + discussion.Start, answerand away we go:note, comment, explanation, clarification, question, answer, end
2 + discussion.question, answer 1, answer 2, one more question, update 1, update 2, report, note, comment, end
- change selinux to support policiesnit.d: recipe itself, toolsandcomment.
We understand with the network routing in Android:Start...end.
We're setting up the network settings throughndc:
- general information onndc: Shell scripts for Android (Post Visitor7 # 58763900), Shell scripts for Android (Post username11 # 58769171)andScripts on the shell under Android (Post Visitor7 # 58784069)
- wifi access point control (tethering)Scripts on the shell under Android (Post kaztost # 58025052)
- installation of the dns server for the interfaceShell scripts for Android (Post Angel_Hranitel # 80575498)
RAM-Drive on Android (with continuation)
How to change init.rc (bottom message)
Tracking changes in a specific directory
Airplane mode (see and below)
Create a swap
We work with API VKontaktethroughcurl
Connect to a given Wi-Fi network
RTFM: materiel, regulatory documentation, literature
Bibliographyon Unix device, list item 1 is mandatory for reading
Shell programming (Unix)textbook A. Soloviev (seed - n. 1 of the above list - certainly preferable to paraphrase)
Help onbusybox
Android regulatory documents:
- Android Architectureaka Android Interfaces and Architecture - internal system device
- Android Core Technologies(Modern name - Configure an Android Device) - that can hack into the system and how to do it right
Hardware: "freezing" applications and components
- explanationon fingers
- discussion of the nuances:question, answer
- from obuzhdeniya above a couple of years there was a storyApplication freeze3 or many bukf
Hardware:character escaping
Shell scripting in the Android environmentXakep article in the magazine for those who are not able to master more or less serious text for sane people - a waste of time
Shell Developer Tools
teamset -x- the debugging tool built into the shell, displays each script command instderr, the details.
wShell- terminal emulator with web interface based on Shell In A Box. If the Android device and the computer are on the same local network, you can access the command line of the device from a computer via a web browser.
Shellcheck- static analyzer (lint) for shell scripts (few details)
Safety Rules. Read a must.
Most commands and scripts hosted in this thread are executed as root. This means that a command (or script), if used improperly, can create new problems and not help solve old ones. And the problems are already big, before which the old ones will seem to be a mere trifle.
Therefore, before you rush to download, drive commands and execute them
1. Make a full backup of the firmware (nandroid backup).
If you do not know what it is, you are in this topic too soon. Read the help sections for newbies on the forum, the theme of the firmware of your device.
"Toy" backups, such as Titanium Backup will not help, if something terrible happens. The backup manager bu built into Android ICS and higher (used by programs like Helium) will also not always help. Do not indulge and do not be lazy, make a normal backup from under the recovery.
2. Made in paragraph 1 backup put in a safe place.
Do not delete it immediately after your experiments have ended, in your opinion, successfully. Android can have a completely different view on their success. Watch the system, live some time in it. If you see strange things, roll back to the saved state. Watch again.
By the way, backup will help and analyze what happened, if something suddenly happens. We may need files from it during the trial.
3. If you don’t understand at all what a particular script does, laid out in the subject, still try to figure it out before you use it.
For some scripts it is necessary to comply with the conditions of their execution, otherwise they will not only not work, but also do something with the system. Easily.
Surely the script as it is laid out will not suit you. You will need to "finish" it to fit your needs.
Finally, the worst (and most unlikely, but still). You can slip a script that will do something bad. And okay, if you just poudalyaet files in the system, you also completed claim 1 of the Rules. (Really? Sure? Well, believe it.) Even worse, if the script sends something to a short number in Zimbabwe. Well, there is a credit card number, for example. What credit cards do not have? Nothing SMS to the short number in Zimbabwe is not free, you know. And do not think that anything you protect the script as root will not catch any anti-virus or various security managers. Of course, we quickly intervene and stop the further spread of malware. (But specifically your SMS is gone. In Zimbabwe.)
4. Your device (phone, tablet) is not the only testing ground for your experiences.
Most of the scripts can be checked and debugged on the BB under Linux. Virtual machine and Live distribution is enough. Any Linux distribution. It will take busybox to bring such a polygon closer to the real machine, but in any Linux distribution box, busybox is present.
You can also use the Android emulator. Yes, there is a Google on the farm and such. Lies next to the SDK for Android, an image with Android can be found on the Internet. This is anyway better than killing a real device. I remind you that it cost you a certain amount. (Of course, working in the emulator you are already tired of step 1 of the Rules. You do not need to follow these rules.)
5. For debugging scripts it is better to use not a terminal emulator application, but adb (Android Debug Bridge) or ssh session From BB to the device.
Fingers will break typing characters on the virtual keyboard. Again, make a mistake, make mischief. The client part of adb (for BB) can be found on the Internet, the server part in Android already exists (do not forget to enable debugging in “Settings”). Applications with ssh server can be found on Google Play.

There is no curator in the subject. If there is a user in the subject who wants to become a Curator and the correspondingRequirements for candidates, he can apply in the topicI want to be curator(after having studied the topic header and all materials for curators).
Prior to the appointment of the curator, on filling caps, please contactmoderatorssection through a buttonPictureunder the messages to which you want to add links.

Post has been editedderak1129 - 22.06.20, 23:05
Reason for editing: Notification.

Rep: (947)
In a hat

To begin, I will drag my post from the Tusker theme for a better understanding of the question, what is it about, and how can I apply it.

Quote. (Large))).
From here:Tasker (Post # 23702923)

# help lesson tasker tasker example shell shell interception of hardware buttons

Example DescriptionWork shell script to intercept phone hardware buttons .

Connoisseurs of linux commands and their specifics - do not laugh.

Need root and busybox .

The text of the "lesson" under the spoiler
Full support was provided by the respectedusername11 where I sometimes just pressed buttons, following a set of his wise advice.
This example is offtopic! : D because the tasker does not participate in it. Totally. Only shell, only hardcore. An example of a working way))
Since this is just an example, everyone can drag it into many pieces and use the necessary parts in conjunction with their needs.

In general, there will be a lot of text, because I am a talker ..

Let's get down to business. Here is the resulting example, and immediately write what it does, and then parse:
(rep = 0; script -q -c 'getevent / dev / input / event1' / dev / null | while read code; do torch = `cat / sys / class / leds / torch / brightness`; screen =` cat / sys / class / leds / lcd-backlight / brightness`; (echo "$ code" | grep -q '^ 0004 0004 00000004. $') && ["$ rep" = "0"] && ["$ screen" = "0"] && (torch = $ (expr 255 - $ torch); echo "$ torch">/ sys / class / leds / torch / brightness); rep = $ (expr 1 - $ rep); done)</ dev / null>/ dev / null 2>/ dev / null &

So, this line (this is ONE line) launched in the terminal, or through the Tasker Task "Run script" runs into memory (and hangs there! The terminal can be closed) and does the following: Itkeeps track of pressing the hardware button Volume Down (I think most Xperia will work, too, officially debugged under Xperia Ray) when the screen is off, and turns on (and off) the flashlight .

Let's start with the interception buttons. As the most interesting public opportunity. We must not forget here that regular phone functions that occur when you press a button, the phone caught in parallel and work out the function. So, hang only "their" poleznyashki to pressing will not work. Why do I have simplified the process of studying the interception itself the task - I just react buttons when the screen is off. When regular lock the phone does not respond to the volume button when the screen is off.

In general, it turns out beautifully: you press the volume rocker and INSTANTLY the lamp turns on, and the screen remains off.

Debugging the script, this is actually 99.9 percent of the total time spent on it, so it is much more convenient to “chat” in wired or wireless adb. Turning debugging options through the phone terminal is tiring. (there will be a lot of debugging).

Part 1. Interception. Theory.

So,intercept . Spy on pressing the buttons, we will be the program (console text program) "GetEvent", getevent . You can simply type (with root rights) in the terminal the name of the command and bewitched to look at the running lines))
# getevent
The output will begin to pour like this:
/ dev / input / event7: 0003 0010 fffffed0
/ dev / input / event7: 0003 0011 ffffff5a
/ dev / input / event7: 0003 000a 000003ee
/ dev / input / event7: 0000 0000 00000000
/ dev / input / event7: 0003 0003 00001138
/ dev / input / event3: 0003 0000 00000006
/ dev / input / event7: 0003 0004 000000d3
/ dev / input / event3: 0003 0001 00000007
/ dev / input / event7: 0003 0005 000000b3
/ dev / input / event3: 0003 0002 00000078
/ dev / input / event7: 0003 0000 00000028
/ dev / input / event3: 0003 0028 00000043
/ dev / input / event7: 0003 0001 ffffffde
/ dev / input / event3: 0000 0000 00000000
/ dev / input / event7: 0003 0002 fffffd4d
/ dev / input / event7: 0003 0010 fffffecf
/ dev / input / event7: 0003 0011 ffffff60
/ dev / input / event7: 0003 000a 000003f2

in this case, events come from ALL phone devices, we need to figure out where our hardware buttons are. And to receive "interruptions" only from them, that it would be easier to process the arriving codes, and, of course, to "wake up" once more from any-each position sensor (for example) - we do not need the battery to quickly stop. (Especially, if the result of waking up then rests on the "fat" tasker).
When starting the commandgeteventat the very beginning it gives a list of all available devices and then it begins to pour in lines of events. After starting, you can quickly press Ctrl-C so that the list of devices does not leave the screen. Or you can use the '-S' command key, and the command will show all valid events and end:
# getevent -S
output of the command in my case:
add device 1: / dev / input / event8
name: "atdaemon"
add device 2: / dev / input / event1
name: "pm8058-keypad"

add device 3: / dev / input / event7
name: "compass"
add device 4: / dev / input / event6
name: "simple_remote_appkey"
add device 5: / dev / input / event5
name: "simple_remote"
add device 6: / dev / input / event4
name: "apds9702"
add device 7: / dev / input / event3
name: "bma150"
add device 8: / dev / input / event2
name: "clearpad"
add device 9: / dev / input / event0
name: "msm_pmic_pwr_key"

In this case, we are interested in the hardware buttons; it was experimentally found out that this devicepm8058-keypad, i.e. device path '/ dev / input / event1'. Behind this, we study the components of event providers. (and there is both a compass, and separately a power button, and a touch screen ..).
Now you can narrow the request to the system to the target. The fact is that on different devices these eventN are all different. In what order they are programmed by the manufacturer, so they are shown. (I mean, it’s not possible to copy the lines here, I’ll have to look for it myself for my phone).
So / dev / input / event1 ..
# getevent / dev / input / event1
(and in the console silence .. :) duck buttons must be pressed! I have three of them: a house, and two volumes). For each press and for each release, we get a pack of codes. To press one, to release - another:
one press and one release of the Volume Down button
Yes, these are the packs oneveryact!
0004 0004 00000004
0001 0072 00000001
0000 0000 00000000
0004 0004 0000000c
0000 0000 00000000
0004 0004 00000014
0000 0000 00000000
0004 0004 0000001c
0000 0000 00000000
0004 0004 00000024
0000 0000 00000000

0004 0004 00000024
0000 0000 00000000
0004 0004 00000004
0001 0072 00000000
0000 0000 00000000
0004 0004 0000000c
0000 0000 00000000
0004 0004 00000014
0000 0000 00000000
0004 0004 0000001c
0000 0000 00000000

So the system (and we pry for the real codes that the system handles) distinguishes between pressing, pressing, and also __ pressing if there are any. That is, if you catch the "Long Volume Down" - then this is all handles, you first detect the pressure yourself, and what was the pause before release, well, before holding, yes. And only then cause your action. I haven’t reached my hands yet, but there is such a key '-t' - to show the time stamps of each flown code.

Having pushed all my three buttons)) I came to the conclusion thatsufficiency in my particular casecatching the code '0004 0004 00000004', although it happens in the press and in the release, but we will catch and take this into account.

username11 writes that the first action line serves the real action code (clicks, messing around the sensor, some other sensor), and the rest is the "echo of the system" for the first action - some, as I understand it, generating already "soft" additional codes for other system traps. What would happen in another desired process also triggered by the action. In addition: by my Logically, bundle codes of zeros are the completion of the "description" of the code. That is, each zero ('0000 0000 00000000') is the end of the logical "string" of the event. In any case, this is a lire., You can’t sew it down, but you’ll have to catch codes))

So, I chose to catch the Volume Down button with just one line of code '0004 0004 00000004', which is unique within the pm8058-keypad (/ dev / input / event1) device.
Next comes the teamreadin the mix with the teamwhile, in this form:

formalized:"data entry | while read var1; do [our line-by-line processing]; done"

data inputin this case, it is our data provider, "getevent / dev / input / event1"
vertical stickthis is redirection of console output (what we see as lines appearing after the getevent command) to another command for processing further. (yes, I write for those boots like me)).
while reada set of commands that do the following:while("bye") provides us with an infinite loop of reading the lines "from under" the getevent, andread("read") each line of the form '0004 0004 0000001c' pushes through the variables of the shell, whose names are indicated after the word 'read'.
For example. The command "enter_data | while read dev code" the first "word" BEFORE THE DIVIDER (we have this space) will put in a variabledev, and the rest of the tail (until the end of the line) in the variablecode. (We will then call $ dev and $ code in the shell in the shell values). And they will be equal to dev = '0004', code = '0004 0000001c'. And if we say three variables: "input_data | while read dev code1 code2", then our example, given to the input of the command, it spreads like this: dev = '0004', code1 = '0004', code2 = '0000001c'. Truth be?
I myself came to the local conclusion thatto meIt's easier to catch the ALL string ('0004 0004 00000004') in one variable, that is, I have it 'while read code'. And one variable $ code is already compared to the desired value.

All that follows the semicolon (semicolon, so to speak) after the commandread, this is the command for processing the result of "pushing" _each_ lines with codes arriving fromgetevent.

Local output: That is, we ordered interrupts from the event1 device, hardware buttons, and everything, everything is "hanging" and inactive. The system is sleeping. Pressing the button (any) awakens the system (it works itself) and sends it to getevent a stack of lines with the event that occurred. We scatter the resulting lines with while read on the components and leave for further processing each lines separately, comparing, whether this is ours, the required line, or not. And then we launch the combat load, perform some kind of action (turn on the flashlight, like me, or call the tasker task right away). (Basically, here is the whole solution). But, about it all in due time, more low, for now the whole series of ambushes waited for me:

Part 2. Workarounds. The first encounter with practice.

Immediately after I rushed into battle, nothing worked for me. Simple verification team:
# getevent / dev / input / event1 | while read code; do echo $ code; done
.. did not show anything!
(the meaning of the command: we get fromgeteventarray of strings usingwhile read variabledragging the array into strings and just in each cycle with the commandechowe derivevaluevariable (the bucks icon in front of the name), in this case, the entire line in one gulp, it is in a single variablecode).

Miraculously, I discovered that it shows the result, if you press the button many times. It turned out the following. On the "stick" is buffering! That is, redirecting data flow from undergeteventit works, of course, but the system buffers the data - it collects them in a heap and gives it away only after accumulating a certain amount, apparently about 4k. ANDusername11 gives the following advice: take the bizybox command script and frame it with the above line. As I understand, script tells the system to know the "output device" as (conditionally) tty, not a block device. And pushing every byte through the "stick" immediately, without waiting for the accumulation of the full buffer.
That is, the following verification team has worked well:
# script -q -c 'getevent / dev / input / event1' / dev / null | while read code1 code2 code3; do echo "code1: $ code1, code2: $ code2, code3: $ code3"; done
(Yes,conclusionteamsscripthad to remember to lower intoilet/ dev / null)
(this example displays, when pressing buttons, bundles of strings of the form: "code1: 0004, code2: 0004, code3: 00000004" is no longer slouching too deeply, IMMEDIATELY after pressing, without putting anything in the drawer).

However, it is time to parse the results of clicks and screenings that are needed, it was absolutely fresh for me)) This resulted, after many days (unhurried) study of the Internet of man-faks-havtushek, into the following:
# script -q -c 'getevent / dev / input / event1' / dev / null | while read code1 code2 code3; do ["$ code1" = "0004" -a "$ code2" = "0004" -a "$ code3" = "00000004"] && echo "code1: $ code1, code2: $ code2, code3: $ code3"; done
(the line is already "wow", yes. So, what I do is: tear each line into three parts, code1-3, and then compare successively the valuecode1from 0004, and so on, and as a result I bring out the result ONLY to the pressure I need (the && sign indicates that the commandechowill be executed only if the whole comparison is performed in square brackets)).
I again to the authorities. (moreover, as I later found out in the process of sorting through various options, the first two comparisons work! plugging in the third). For a long time I pooped until I was instructed on the command of cognitive data output:
# script -q -c 'getevent / dev / input / event1' / dev / null |od -cb
(it displays the byte values ​​of the text in different formats, well, like line 12345 will look like 31 32 33 34 35). And right after it was discovered that at the end, behind the last 00000004, apart from the regular Linux sign, the line break 0D was still worried (completely DOSovsky) 0A. And of coursewhile readlawfully shoves him into the last variable, in my case incode3. And we have a comparison before the sign, if at the end of the line the left tail, the comparison does not work.
The chief offered me (already on the verge of my understanding of the Linux com line) options for this next round, I stopped at this:
here are the first checks]&& echo "$ code3" | grep -q '^ 00000004. $' && echo "code1: $ code1 (and at the end went output via echo )
(as I understood, search for a string throughgrepwith the key '-q' gives the value true / false in ourdupea cascade of double ampersands && for comparing the comparison logic. Circumflex and buck with a point are already OUT the limits of my understanding, but I believe that this is a search from the beginning of the line and the omission of an arbitrary end, the one that stuck out of the signs 0D and 0A).

Thus, a complete search for my sequence (recall, '0004 0004 000000004') WITHOUT a combat load, began to look like this:
(codeI again, pampered with splitting the line into pieces, made a heap, still I still have one full-line code)
# script -q -c 'getevent / dev / input / event1' / dev / null | while read code; do echo "$ code" | grep -q '^ 0004 0004 00000004. $' && echo "code: $ code"; done
(and threw out the square brackets, still the main result givesgrep)
Here, the first result. In the terminal, one line is displayed for pressing the button I need, and one for pressing. Nothing is displayed on the other buttons. You can screw on / off the lamp!

Part 3. Flashlight. Long road in the dunes.

Well, here I am still decently lost my head, the Chief suggested how easier it is to make a "switch" on the command line, from 0 to 1 and back, the _one_ command. (as I asked: "how to make xor ax, 1"))) It turned out:a = $ (expr 1 - $ a).

I knew in advance the "variable" of the flashlight, for me (I think, at all xperias as well) it is / sys / class / leds / torch / brightness. A value of 0 does not shine, 255 - shines. (and all intermediate from 3 to 255 work, but yes, the flashlight is beautifully smoothly turned on, and as I wrote a binary on C for the android right on the phone, this is a separate tale)).
I also needed to find whether the screen is currently on or not, because getting control at the pointecho code: $ codeI resolutely (so far) did not imagine what was happening with the screen. And if it is on, this is a regular system volume change, and at this moment it is not necessary to turn on the flashlight.
Climbing, I found. Beside. / sys / class / leds / lcd-backlight / brightness too, 0-255, or something. At least the turned off screen is "0", turned on - NOT zero.

Iiii .. I gash. The full script you saw at the beginning. Oh, no, that's not all)))

Part 4. The last ambush

Eventuallyusername11 taught me to frame everything with brackets, behind which to write a single ampersand, &. A sign that the script should remain hanging in the memory of the system, remain a resident. And give control to the command line. And then there was the last ambush - it is worth filling the script with a resident, he stopped working! So it works, but the resident does not! As it turned out after the command ps (a list of all processes), that my script is in memory is hanging, but it wants I / O, (I didn’t find what the "wants" command is), so the system slows it down and doesn’t give it anything.
As a result, I had to write at the end to solve this problem (another, last, crutch)):
# (all my strip)</ dev / null>/ dev / null 2>/ dev / null &
(that is, all the eager to communicate before the floor in the toilet).

Now it all worked.

# (rep = 0; script -q -c 'getevent / dev / input / event1' / dev / null | while read code; do torch = `cat / sys / class / leds / torch / brightness`; screen =` cat / sys / class / leds / lcd-backlight / brightness`; (echo "$ code" | grep -q '^ 0004 0004 00000004. $') && ["$ rep" = "0"] && ["$ screen" = "0"] && (torch = $ (expr 255 - $ torch); echo "$ torch">/ sys / class / leds / torch / brightness); rep = $ (expr 1 - $ rep); done)</ dev / null>/ dev / null 2>/ dev / null &
What I do in the script:
- binary switch initial for catching and unlocking
- after while read we fall into the main analysis, that for the line arrived
- I read the current value of the lamp
- I read the current value of the screen
- and further a large condition, concatenated by && from the conditions:
- this is our code
- this is a click (and not release)
- the screen is off
- inversion value lantern
and combat load:
- write a new value of the lamp (if it was turned off - turns on and vice versa)
- inversion of the push-release switch value.

Homework from username11 I haven't done it yet ((, but here it is:
1) find out who wants I / O and eliminate.
2) remove unnecessary parentheses. every brackets is an extra shell running in cascade.


There is no takker here, as you can see. Having coped with half of this case, the absence of a tasker was already a matter of a prince)) why? when everything is "shell" and easy. A huge durilnya-tasker spoil all the beauty. And for what? Blink flashlight?

Tasker, in theory, as the Chief wrote repeatedly, should be called througham broadcastin the "body" of the warhead.

Responsibility of the parties.

Perhaps this is not what the masses have been waiting for)) but in any case, something useful can be learned.
Any tips, edits, possible future _Applications_ to this post, removal of the crumbler, homework decisions are being decidedly accepted!

Post has been editedusername11 - 23.02.20, 15:49
Reason for editing: post is placed in the header

Rep: (947)
In a hat

right away while a handful (then distant, systematizing), I’m exploring various useful things from the accumulated. for in the theme of this, everything was accumulated in the closet and was heard from under the floor, you can immediately exhale with full breastfeeding.

Practices, notes on napkins and stuff ...

We monitor different resources for connection , eg, block devices , team:
# inotifyd - / dev / block
// the shell is “hung up” on this command, and at the time of connecting to the usb otg flash drives it produces such a thing:
n / dev / block sda
e / dev / block sda
n / dev / block sda4
e / dev / block sda4

disassemble it (awk, or as above on a bare shell, into parts, and “auto” - mount the necessary devices)
# mount / dev / block / sda / mnt / usbcard
# umount / mnt / usbcard
When ripping out a flash drive, the lines also fly in, and we react to them.

I will clarify. This was an example of a command for a resident script (no reaction yet). That is, it starts at the start of the android, and hangs until the bodies are cut down. And CAM does various useful things.
And all this is not in C ++, not in “Tasker” and others ... - on a bare shell.

And we do not need any usb otg mount in the form of an android application, if there is no such thing on the phone.

Post has been editedusername11 - 23.02.20, 15:50
Reason for editing: post is placed in the header

Rep: (947)
In a hat

Styl script from a respectedlaytya without permission:

logcat -c; script -q -c 'logcat -s VxTTS_ProxyI: V' / dev / null | awk '/ start / {system ( "am broadcast -a -e task_name tts_start")}; / Completed / {system ( "am broadcast -a -e task_name tts_stop")} '1>/ dev / null &

What the script does: Script hangs and monitor system log to messages from VxTTS service (this is the text reader in voice, vocalizer), and catches in the answers the substring start or completed and responds to it in the appropriate way.

What is useful: in the system log runs a lot of useful information, you can catch it and do your things at certain moments.
1) read from logcata ,
2) restrict reading to the service we need in a particular case, because the catlog sharashit is almost continuous. And then he "hangs" and does not wake the phone, and the lines take off only in the case.
3) catch lines avcom (filter out the entire information from the TTS service only we need) and then call out some of our actions. (in this case, a specific Tasker task is invoked).

Post has been editedusername11 - 23.02.20, 15:49
Reason for editing: a post placed in schapku

Rep: (947)
As i seeschemes for using such things in general:
(and yes, it should be noted, many things are model-dependent, many parameters are unique for sonecs, samsungs, and so on)

1) looking for ways to monitor the parameter of interest
2) minimize phone battery consumption
3) process text streams
4) implement the necessary actions (reaction) on the shell, or by calling intent programs for Android. (popularly “activity”).

A hypothetical example ...
Some Chinese tablet phone doesn’t like us to stubbornly (or on the contrary, quench) the screen during a call. A fix - no way.
We draw a script. It is possible to turn on Tasker, but it can be done without.
We catch through the catlog the fact of lifting the tube | In the polling mode (in the loop), we kick the screen so that it does not go out | At the end of the call, we again go into monitoring mode, and we sleep.
I understand crazy, but in principle ..

We also did not figure out how to catch long button presses (see the example above). But still ahead!

What else can we do?
The guys in the Tasker branch are already easily catching keystrokes on the BT keyboard. (for “debugging” of this case right in the branch from there and “asked”)))) So, we’ll welcome it here.

The thing is that binaries and their bizybox counterparts often do not behave as easily as in native Linux, hence the specific nature of this.

For example, I still do not enjoy my flashlight, ignited with one touch of one physical button. Almost instantly. Here I am in favor of such decisions.
Come up with tasks. Bring your work.

Rep: (1192)
Gentlemen, doesn’t it remind you, "I have a Phillips screwdriver, I can chop wood for her!"?
If you have a "root required" condition, is it not easier to set up the same QPython and subscribe to udev events (pudev lib)? (And in some systems there is even the good old dbus).

Rep: (947)
I will quote interesting things from Tusker, because here this is the place:
pm disable package name Ochchchen cool gizmo ... the goal was this: the phone lives with first graders ... the task is to remove the ability to use non-phone functions in school (games, camera, settings, etc. ...) without deleting them ...
soft recovery record (not removed), game overpm disable"Cleaned" they are not even visible in this way on the menu at a certain time (after school, and so triggered sb.vspm enable) Games and the camera is available and possibility of kerf, cut off remotely (via SMS, because Inet disconnected
VityaPda @ 08/31/2013, 16:36*
"In terms of literacy": is this what is called "freezing"?
aha it is ... in a titanium and a heap of other software it is this feature that is hidden behind the "freeze" button
In all versions of Android in the help -PACKAGE_OR_COMPONENT. Component - is, for example, what is transferredam start / broadcastin the key-n. I must say that Google, of course, all pretty confused. It has different functions to run the activity, service and sending intent, although in all cases the result is sent to intent. Well, yes, programmers, then all one to use these different functions (if they - not SSZB), but the understanding of the internal is not conducive.
In general, we can assume thatpm disable packageIt bans all application components (the difference between the application and the prohibition of the prohibition of all its components is too thin to take it into account). Accordingly, the application will be removed from the launcher menu list Settings application app, all widgets will be banned. It is the visible part of the user. In addition, the application will not be allowed all services (service), activity, broadcast receivers, content providers. Those. all components. And if you deny the individual components, only it can not be called. The most popular is the receiver's ban on intentandroid.intent.action.BOOT_COMPLETED.
VityaPda Yes, "frost" - this is a challenge pm disable<package> .
Okay. Now aboutgetvent/sendevent, dumpsys, logcat, am, pmwe all know. From interesting things leftservice(special,service call). You can hack it. : D And there you can have fun hoo.

Post has been editedusername11 - 01.04.20, 13:00
Reason for editing: quotes synchronized with the source

Rep: (2507)
and it doesn’t remind you "I have a Phillips screwdriver, I can chop wood for her!"?

Not. On the contrary, your offer reminds. : D Compare the sizes of busybox (with inotifyd) and python. And it will almost all be in memory. If for busybox there are still chances that the kernel will not load all the code, then for the python interpreter, whose code is data, the chances are almost zero.
In addition, what are udev and dbus under different Androids? Uh-uh, different. And dismantling with udev (and, especially, with dbus) is clearly not a single line in python, even with pudev.
inotifyd is the same "sanctified" monitoring mechanism. Same unix, here one problem can be solved successfully a bunch of ways.
I am also not against the choice of the tool "which you know / like you and which exists for the bucket". But programs from several lines are better for writing on the shell. That's when the lines are typed a lot, yes, it is better to start to look in the direction of python.
Something like this...
Unfortunately, give a heap of people a ready decision, to understand how it works and what works - they are lazy.

You do not worry. According to the experience of the Tasker theme, no one here will chew much. : D

Post has been editedusername11 - 14.10.13, 20:00

Rep: (947)
I have a question on avku ..
1) How can I read a variable file in the avk-script?
That is, how to replace the shell:
torch = `cat / sys / class / leds / torch / brightness`

2) and how to write a variable to a file?
I decided to transfer my flashlight script from the "read while" shell under awk.

Along the way, I found a unique pressing code and a unique release with a fresh look. and got rid ofrep(for those who are "in the subject").
The piece looks like (on the shell) like this:
(script -q -c 'getevent / dev / input / event1' / dev / null | while read code; do torch = `cat / sys / class / leds / torch / brightness`; screen =` cat / sys / class / leds / lcd-backlight / brightness`; (echo "$ code" | grep -q '^ 0001 0072 00000001. $') && ["$ screen" = "0"] && (torch = $ (expr 255 - $ torch ); echo "$ torch">/ sys / class / leds / torch / brightness); done)</ dev / null>/ dev / null 2>/ dev / null &
and I read off under the hardware, and gave birth to the trap of the sequence I needed:
script -q -c 'getevent / dev / input / event1' / dev / null | awk '{if ($ 1 == "0001" && $ 2 == "0072" && $ 3 == "00000001") print $ 1, $ 2, $ 3; } '
she works. The code is displayed only when the button I need is pressed. (printThis is still a test).

but how to subtract variablesscreenandtorchI don't know yet. How to do it more "awk'ovski"?
In fact, this is reading the file from the avk-script, yes. Well, one record at the end. I understand that it is possible and throughsystem ("echo" $ torch ">/ sys / class / leds / torch / brightness ")- but this is stupid? not?

Still gave birth to a clever idea that parsing in avkovskiy if'e can be flattened up to one comparison, and not concatenated three - change the parameter avka "element separator" by putting there "\ n" - is it necessary to do so, in terms of simplicity / processing speed?
then there will be onlyif ($ 1 == "0001 0072 00000001")

Post has been editedusername11 - 05.11.18, 15:22
Reason for editing: posts merged

Rep: (742)
coolkaas Not really understand your somewhat chaotic post. It is better to write in words what you want to do.
About awk. I still do not understand why you need it :)
awk - '/ 0001 0072 00000001 / {print}'

But if you want to start something easier
grep '0001 0072 00000001' && command
Well, or so if exactly db. line
grep '^ 0001 0072 00000001 $' && command
^ start, $ end of line
coolkaas understand a few simple things:
1. Unix has a lot of simplest utilities and you need to use the most convenient one.
2. All utilities are combined with pipes.
Well, the banal
any problem has an infinite number of solutions. It's a matter of taste

So for example.
cat / sys / class / leds / torch / brightness | awk ...> file

No need to open the file for input in awk. Use stdin
No need to open file for output use>
And combine all the utilities
In 2 words hard to explain - will come with experience

Post has been editedsvs-57 - 14.10.13, 20:43

Rep: (2507)
coolkaas , awk has the getline and print (f) operators.

Post has been editedusername11 - 05.11.18, 15:48

Rep: (848)
In a hat

coolkaas Thanks, the topic is very necessary! ;)
The mind itself is not enough, so I like smart people, such asusername11 and svs-57 ...: rolleyes:

There is a task, you need to compare the output of the channel with the contents of the file and get a match, if there is one. In one line of the script, without organizing the loop in Tasker.
There is a file /sdcard/AudioPlayer.txt in it the names of the stock player packages and Poweramp (the player will be added as needed):

In the background plays Poweramp, perform:
dumpsys statusbar | grep StatusBarNotification | awk '{print $ 2}' | cut -d '=' -f2
I get:

dumpsys statusbar | grep StatusBarNotification | awk '{print $ 2}' | cut -d '=' -f2 | grep -f /sdcard/AudioPlayer.txt
I get:
those. it seems to work ...

In the background playing stock player Music, perform:
dumpsys statusbar | grep StatusBarNotification | awk '{print $ 2}' | cut -d '=' -f2
I get:

dumpsys statusbar | grep StatusBarNotification | awk '{print $ 2}' | cut -d '=' -f2 | grep -f /sdcard/AudioPlayer.txt
I get nothing :(
Why, I can not understand.

In general, I need to get 1 (one) if any player from the AudioPlayer.txt file plays in the background or 0 if there are no matches.
If you specify "grep" and run:
grep -c $ (dumpsys statusbar | grep StatusBarNotification | awk '{print $ 2}' | cut -d '=' -f2 | grepcom.maxmpz.audioplayer ) /sdcard/AudioPlayer.txt
then when working in the background Poweramp I get 1.
But if Poweramp is not in the background, then instead of 0 (zero) I get the hanging process of the script, i.e. no completion.
Similarly with the stock player ...
grep -c $ (dumpsys statusbar | grep StatusBarNotification | awk '{print $ 2}' | cut -d '=' -f2 | ) /sdcard/AudioPlayer.txt

And in this case, it will be necessary to organize a cycle and sort through the package names, which is highly undesirable ...

The same should be organized on navigators, the package names of which are registered in the file /sdcard/Navigators.txt, only in it is somewhat different:
Yandex Maps,,;
Yandex Navigator,,;
Navitel Navigator, com.navitel, com.navitel.Navitel;
Navitel Navigator, com.navitelnavigator, com.navitelnavigator.Navitel;
Rambler Maps, ru.rambler.maps, com.cdcom.naviapps.progorod.ProGorod;
Google Maps,,;
Sygic Aura, com.sygic.aura, com.sygic.aura.SygicNaviActivity;
CityGuide Navigator,,;
iGO Primo, com.navngo.igo.javaclient, com.navngo.igo.javaclient.MainActivity;
PROGOROD Navigator, com.cdcom.naviapps.progorod, com.cdcom.naviapps.progorod.ProGorod;
2GIS, dublgis.dgismobile, dublgis.dgismobile.GrymMobileActivity;
Waze Navigator, com.waze, com.waze.FreeMapAppActivity;
Seven Roads, com.navikey.seven_ways, com.navikey.seven_ways.MainActivity

In Tasker, I parse it all into arrays and process it in a loop, and it takes a lot of CPU time.

Post has been editedusername11 - 23.02.20, 15:51
Reason for editing: post is placed in the header

Rep: (742)
grep -cE `dumpsys statusbar | awk - 'BEGIN {s = "("} /StatusBarNotification/{sub(/.*pkg=/ ,"" ,$2);s=s$2""""ENDENDprintprintr (s, 1, length ( s) -1) ")"} '`/data/local/tmp/AudioPlayer.txt

something like this...
must return 0 or 1
GrAnd1, Only one moment here I did not take into account: if there is nothing at all in the notification. Will work incorrectly. I'll fix it now.
grep -cE `dumpsys statusbar | awk - 'BEGIN {s = "("} /StatusBarNotification/{sub(/.*pkg=/ ,"" ,$2);s=s$2"|"}ENDiet SENDsr_substr(s,1,length (s) -1) ")"; if (s == ")") s = "no_pkg_in_notification"; print s} '`/data/local/tmp/AudioPlayer.txt

GrAnd1 @ 10/18/2013, 14:17*
grep 'template1 | template2 | template3'

grep -cE '(pattern1 | pattern2 | pattern3)'

Rep: (1)
Is it possible to use the script to change the time to the specified one, for example, 08/01/2013, and then return the current time (in the settings of the android in the tab "Date and time" checkmark "Use network time")?

Rep: (0)
Guys will not help, already I’m trying to get / set the clipboard in the terminal for 2 hours already.
In all manuals it:

ClipboardManager clipBoard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
ClipData data = ClipData.newPlainText ("", "");
clipBoard.setPrimaryClip (data);

In this form, it does not work - I tried it in parts - but it does not know the ClipboardManager command.
I looked at the processes the ends led to android.content.clipdata - further a dead end.

Rep: (11)
Saved log Better Battery Stats
Here is a small extract from it:

Bbs (): Wakeups: 22 (): Wakeups: 11
Alarms: 0, Intent:
Alarms: 11, Intent: (): Wakeups: 2
Alarms: 1, Intent:
Alarms: 1, Intent:
Alarms: 0, Intent:

Tell me is it possible to freeze only this one?

Rep: (164)
In a hat

sv41, do you need for console or java code?
From the console:
service call clipboard 1
service call clipboard 2 i32 1 i32 1 s16 "test text"
Access only from root.

Post has been editedusername11 - 23.02.20, 15:53
Reason for editing: post is placed in the header

Rep: (0)
Thanks for the info. I need a code for the terminal, just Google gave me everything java.
I tried the service call clipboard. Produces a strange (text "12345" buffer):
root @ android: / # service call clipboard 1
Result: Parcel (fffffffc ffffffff '........')

root @ android: / # service call clipboard 2 i32 1 i32 1 s16 "eeeee"
Result: Parcel (
0x00000000: fffffffd 00000011 00
6e0055 006e006b '........ U.n.k.n.'
0x00000010: 0077006f 0020006e 00
610070 006b0063 'o.w.n. .p.a.c.k. '
0x00000020: 00670061 00200065 00
000001 'a.g.e. ..... '

In the buffer remained the same.

I'll try to dig a little more ...

Rep: (164)
sv41, Well, as if, Google warned that the internal API can change as you like and without warning, both by Google and vendors. To lay such decisions in any mass products is impossible.
What I brought works on my body (Android 2.3).

Try to see for a start what services are:
service list
The clipboard could migrate somewhere in the manager or somewhere else.

Try also options:
service call clipboard 1
service call clipboard 2
service call clipboard 3

Post has been editedNfc666 - 19.10.13, 17:44
Reason for editing: Completed.

Rep: (0)
Nfc666 Vobschem write that now as before just will not work (I have 4.1 android). As an option, you can add your own simple service, where to write a simple function:
I decided the skin is not worth the dressing - I thought to use a buffer to associate the analysis of pressing the button in the command line and the action in the tasker (through the variable% clip). I decided and made a file change tracking (I will write a log to the file, at the same time the tasker will see).
At first, I thought I would pass the parameter, so there is more flexibility and possibilities, but something wasn’t set with the clipboard (no, everything is different from the tasker ...) - I don’t leave any attempts.
So in such a way I inform the tasker only that I pressed the button.
Now I will add several buttons before reading, it seems that I will have to make a file on each button - not very elegant.
There is also a task for action after several taps or combinations of buttons, but I think this is not a problem. The benefit of the android-radio tape recorder sees only 2 buttons on the steering wheel ... (although this is probably not good)

Post has been editedusername11 - 05.11.18, 15:37
Reason for editing: posts merged

Rep: (947)
sv41, in tusker they solved this question (combo), still, awk / case1 /; / case2 / ...
It is necessary to write a “keyboard driver” in general, to compile codes of pressing, wringing out on condition, and output all this into a beautiful resulting “scan code”. it will be cool)) on separate scripts each button is obvious, but not economical.
sv41 @ 10/20/13, 16:27*
sees only 2 buttons
it's a lot! single presses, consider, we process already. (already two actions can be hung up). pressed both at once - also, in general, the issue is solved.

double clicks (double-pressing the button quickly) can be easily shed - we have an easy way to catch them, double. "getevent -t". Gives us time clicks and wrists.
example of pressing and releasing
# getevent -t / dev / input / event1
getevent -t / dev / input / event1
4682-464818: 0004 0004 00000004
4682-464879: 0001 0072 00000001
4682-464909: 0000 0000 00000000
4682-464909: 0004 0004 0000000c
4682-464940: 0000 0000 00000000
4682-464970: 0004 0004 00000014
4682-464970: 0000 0000 00000000
4682-465001: 0004 0004 0000001c
4682-465001: 0000 0000 00000000
4682-465031: 0004 0004 00000024
4682-465062: 0000 0000 00000000

4683-409184: 0004 0004 00000004
4683-409245: 0001 0072 00000000
4683-409276: 0000 0000 00000000
4683-409306: 0004 0004 0000000c
4683-409337: 0000 0000 00000000
4683-409367: 0004 0004 00000014
4683-409398: 0000 0000 00000000
4683-409428: 0004 0004 0000001c
4683-409459: 0000 0000 00000000
4683-409489: 0004 0004 00000024
4683-409489: 0000 0000 00000000
I do not know what the 46 is in the example, but 82 and 83 are seconds, and the rest is either Linux tact or (roughly) microseconds. Not the point. This is enough for us. From here and dance.
Theory : Catchin avke code itself(no, first we catch svs-57 He washed down the right, we catch))), catch code (squeezing, pressing) - I so do press is unique (the second line in a pack), me and the filter is not necessary. Vertan to $ 1, or as it is right there in avke where "time" is shorter. And compares the current of this press with _otkachennym_ time from the previous pressing (also in variable tsklicheskom our script lives), calculate the difference (taking into account all the "transitions" / cranking numbers through zero), [roll away the new (current) time peremennuyu- rollback] if _raznitsa_ less than a certain number (pick up on the fact) - a double tap (two consecutive pressing-squeezing), for example, within seconds. Otherwise (time more than a second) - are two separate click.
Bad luck (( : you still need to somehow note the time And after any pressing, in order to understand that it is a single one, someone should fly to us “in a blue helicopter” in a second and say that time has ticked, and as we are, the state machine decide where we are and take note of this tick.
Well, I found an example))
TIMELIMIT = 4 # 4 seconds
read -t $ TIMELIMIT variable

if [-z "$ variable"] # Is null?
echo "Timed out, variable still unset."
echo "variable = $ variable"

Chew for yourself-boots:
- we put the desired timeout in the variable in seconds,
- call the construction "read -t $ our_timeout"
- from (our future infinite)while readin now we will fall out anyway! even if no buttons are pressed,
- now we have to check for what reason we fell out - the button or the end of the charged timeout,
- if our variable is zero - timeout,
- if not zero - button.

Um, the question of the boot, again .. And where to draw this "-t" - mostly "infinite"while read? ETOGH he constantly bomb us and will, right? (interrupts). even if we do not “recharge” the tick variable .. or just by pressing start a “separate” wait cycle (timer or release - what's ahead).

Post has been editedusername11 - 05.11.18, 15:43
Reason for editing: posts merged

Full version    

Help     rules

Time is now: 28/06/20, 21:11