Monday, April 29, 2013

Python script to get android phone vibrate while is being answered II

I happen to find that for GSM standard phone, call duration would be created into sql database only if the outgoing call is being answered, or after hanging up if it is not being answered.

So i guess this method is meant for CDMA android phone only. cause we could not detect if outgoing call is offhook by the callee via tasker or sl4a.

Java code would be the solution i think, by monitoring the phone state.


in my earlier entry, i have mentioned the method about how to get it done by python script.

however it doesn't work on android phone but android pad.

i guess the reason is the contacts dabase is encrypted by default, most likely not encrypted in android pad, since it doesn't actually have mobile communication modules built-in.

well, i have been thinking if there is another way to solve this still via python script?

after some testings, problem finally solved.

if you are interested, please read on.



#### script content ###############


import android
droid = android.Android()
import time
time.sleep(3)
a = droid.queryContent('content://call_log/calls',['duration'],'type <= 2',None,None).result  ## returns a list of dictionary
while a is not None:
  b =a[-1]  
  c = b.get('duration')
  d = int(c)      
  if d == 1 or d == 2:
    break
droid.vibrate(200)


How to get contact phone number via contact name?

in some specific situations, if we got a bunch of contacts names, how can we get the matched phone number from the database?

the answer is yes, we may get it done by python sl4a script or sqlite3 command.

for sqlite3 command requirement, please check my previous entry for sure.

hereinafter it is the specific command to get the matches mobile phone number by name.

## type represents the phone number type, 2 means mobile phone number.

## LIMIT 1, cause there might be more than 1 mobile phone number for this contact person.

### %Contact_name is the variable set from tasker

sqlite3 /data/data/com.android.providers.contacts/databases/contacts2.db 'SELECT number FROM view_v1_phones WHERE name="%Contact_name" AND type=2 LIMIT 1';



via python sl4a script, it is also simple that way. if you wanna sepcify the search result for mobile phone number only, you may use for statement combined with find function with regex match.

### %Contact_name is the variable set from tasker
#### script content ###########

import android
droid = android.Android()
contacts = droid.queryContent('content://com.android.contacts/data/phones',['data1'],'display_name = "%Contact_name"',None,None).result
a = contacts[0]['data1']
print a
## returns specific phone number in interger

SL4A python script to manage android default sms message

SL4A python script to manage android default sms message


since i have been studying on sl4a python script these days, i think it could be helpful if i post how sl4a script manages android default sms message.

in my earlier entry, i already posted the script about how to mark specific sms as read via keyword and sender phone number.

if you are interested, you may take a look as well.





## unread sms count  ####


import android
droid = android.Android()

count = droid.smsGetMessageCount(True).result
print count         ## you will see the unread sms count result in there




## send sms ###


# coding:utf-8
import android
droid = android.Android()

number = "........."
message = "........."
droid.smsSend(number, message.encode("utf-8"))




## mark all unread sms as read ####


import android
droid = android.Android()

msgIDs = droid.smsGetMessageIds(True, 'inbox').result
if msgIDs > 0:
  droid.smsMarkMessageRead(megIDs, 1)





### delete all unread sms #######


import android
droid = android.Android()

msgIDs = droid.smsGetMessageIds(True, 'inbox').result
if msgIDs > 0:
  for msgID in msgIDs:
    droid.smsDeleteMessage(msgID)




#### delete specific message in outbox ####

# coding:utf-8
import android
droid = android.Android()

msgIDs = droid.smsGetMessageIds(False, 'sent').result
if msgIDs > 0:
  for msgID in msgIDs:
    message = droid.smsGetMessageById(msgID, ['address','body']).result
    str1 = message['address'].encode('utf-8')
    str2 = message['body'].encode('utf-8')
    if str1.find('XXXXX') >= 0 and str2.find('YYYY') >= 0:    ##XXXX reprents phone number, YYYY represents message keywords
       droid.smsDeleteMessage(msgID)




#### delete specific message in inbox and outbox ####


# coding:utf-8
import android
droid = android.Android()

msgIDs = droid.smsGetMessageIds(False, 'inbox').result
msgIDs.extend(droid.smsGetMessageIds(False, 'sent').result
if msgIDs > 0:
  for msgID in msgIDs:
    message = droid.smsGetMessageById(msgID, ['address','body']).result
    str1 = message['address'].encode('utf-8')
    str2 = message['body'].encode('utf-8')
    if str1.find('XXXX') >= 0 and str2.find('YYYY') >= 0:         ##XXXX reprents phone number, YYYY represents message keywords
       droid.smsDeleteMessage(msgID)
        


Sunday, April 28, 2013

Another version of my Popup SMS notifier

in my earlier entry, i have posted the script about how to make the popup sms notifier via python sl4a script.

and i also said i am wanting to improve it with full screen reply inputting layout.

i am sure python sl4a script can make it, but to do that, i will have to learn how to make the layout done by javascript first.

it is not gonna be easy, since i don't have too much time, so i have to get another easier way.

according to a suggestion of my friend, i have done some modifications for the reply message part.

now you will see full screen layout by then. below it is the screenshot to show you the demostration.

here you go~~~~


 this is the first part you will see while there is any incoming sms messaages.

 this is what happens while you press reply button.                      

Python script to get android phone vibrate while the callee answers

I happen to find that for GSM standard phone, call duration would be created into sql database only if the outgoing call is being answered, or after hanging up if it is not being answered.

So i guess this method is meant for CDMA android phone only. cause we could not detect if outgoing call is offhook by the callee via tasker or sl4a.

Java code would be the solution i think, by monitoring the phone state.


In my earlier entry, i have posted an idea about to your android droid vibrate while the callee answers via sqlite3 command.

according to the feedback from a user, reporting a bug, which indicates the run shell action with root most likely would run kinda slow in some low RAM like 512M or 215M smartphone.

i guess the loop interval is also a problem, which make it worse in such a short while.

so i was thinking of finding another workaround.

after done some homework, i have tested working in my android tablet pad. running kinda fast, however, when i moved it to my HTC droid, it failed, error says "sqlite database disk image is malformed".

i got scared ATM, and quickly run some checks on my database file, whereas everything is fine, i opened it via RE and sqlite editor, both are fine. no corruption at all. when i switched back to the python script, it still ran end up with the same error.

well, i am not sure if there is some kind of secure system preventing me from accessing the database.

if you guys are interested, please run some testings for me, will be greatly appreciated.


First move, change the database file permission to be rw-rw-rw, or else, python could fail to access it.

and then you may run this script with tasker outgoing call context.


###### script content ########


import android
droid = android.Android()
import sqlite3
import time

time.sleep(3)
con = sqlite3.connect("/data/data/com.android.providers.contacts/databases/contacts2.db")
con.isolation_level = None
while True:
  cur = con.cursor()
  cur.execute("SELECT duration FROM calls WHERE type <= 2 ORDER BY date DESC LIMIT 1")
  for i in cur:
    if i[0] == 1 or i[0] == 2:
      break
    print i[0]

droid.vibrate(200)
cur.close()
con.close()


Saturday, April 27, 2013

Popup SMS notifier made via SL4A python script launched by tasker

Popup SMS notifier made via SL4A python script launched by tasker



i didn't play popup sms before, cause i thought it is a waste of battery. but  i have changed my mind right after i saw some introductions about sms popup notifier apps.

i guess it would be much helpful and funny anyway. also it could save a little bit time since i don't have to get into message inbox to read it.

however it seems there is some kind of conflict or bugs maybe for those sms popup notifier apps. everything runs fine until i tap "mark as read" button, it would just crash and FC. i have already tested quite some different kind of simliar apps. same error occurs if i try to mark the message as read.

that makes me thinking of programming or scripting one myself. that is the starting of all of it.

firstly i tried to use tasker scene, or tasker popup alert. however, soon i realized neither of it is working. the reason is either tasker scene or tasker popup alert, they are actually just a scene. popup alert has a displaying timeout limit, if you set it up to forever, it could display right on the screen and never disappear. also the task action would get stuck right there until you stop it manually in the tasker task.

scene has a similar problem too, a scene would not disappear until it got destroyed by tasker.

so either popup alert or scene could not perform if there is more than 1 sms message incoming. it could not display more than 1 popup window.

so i have to figure another way out of it.and sl4a pythong script becomes my testing project.
via this script, i am able to see as many popup sms notifier windows as the sms messages i receive. i may simply tap on the reply button to open up another new window to input the reply message then send it out. also i may tap on mark as read button to mark this current sms message as read.

btw, if you click reply button, it could also mark this current sms message as read too. so i think it could be much more convenient for daily life.

and most funny part is you are able to check your sent message in the default android sms message outbox.


PS. i am still trying to improve this script, to see if i could add contact photo accordingly to the sender phone number. and hopefully i may change the
inputing reply message layout to be fullscreen. i guess that is everybody wants. there is still a long way for me to walk through, wish my poor brain could
still handle it.





========================= script content ===============

# coding=utf-8
import android
droid = android.Android()
import time
Date = droid.getIntent().result[u'extras'][u'%SMSRD']
Time = droid.getIntent().result[u'extras'][u'%SMSRT']
Name = droid.getIntent().result[u'extras'][u'%SMSRN']
.encode('utf-8')
Number = droid.getIntent().result[u'extras'][u'%SMSRF']
.encode('utf-8')
Body = droid.getIntent().result[u'extras'][u'%SMSRB'].encode('utf-8')
count = droid.smsGetMessageCount(True).result
droid.ttsSpeak("you have a new message from" + Name)
droid.dialogCreateAlert(Date +", "+ Time + "unread: "+ str(count), "From: " +Name + "\n" + "Tel: " +Number +"\n" + Body)
droid.dialogSetPositiveButtonText("Reply")
droid.dialogSetNegativeButtonText("Close")
droid.dialogSetNeutralButtonText("Mark as read")
droid.dialogShow()
response = droid.dialogGetResponse()
droid.dialogDismiss()
if response.result["which"] == "neutral" or response.result["which"] == "positive":
  msgIDs = droid.smsGetMessageIds(True, 'inbox').result
  if msgIDs > 0:
   for msgID in msgIDs:
     if (droid.smsGetMessageById(msgID).result['body'].encode('utf-8')).find(Body) >= 0:

      msgRead=[0]

      msgRead[0]=msgID
       droid.smsMarkMessageRead(msgRead,1)
if response.result["which"] == "positive":
 droid.dialogCreateInput(Date +", "+ Time + "unread: "+ str(count), "From: " +Name + "\n" + "Tel: " +Number)
 droid.dialogSetPositiveButtonText("Send")
 droid.dialogSetNegativeButtonText("Close")
 droid.dialogShow()
 response = droid.dialogGetResponse()
 droid.dialogDismiss()
 if response.result["which"] == "positive":
  class Task():
    SET_VARIABLE = 547
    def new_task(self):
        self.action_cnt = 0
        self.extras = {'version_number': '1.0', 'task_name': 'task' + str(time.time()), 'task_priority': 9 }
    def set_var(self, varname, value):
        self.action_cnt += 1
        self.extras['action' + str(self.action_cnt)] = {'action': self.SET_VARIABLE, 'arg:1': varname, 'arg:2': value, 'arg:3': False, 'arg:4': False,
'arg:5': False}
    def run_task(self):
        taskIntent = droid.makeIntent('net.dinglisch.android.tasker.ACTION_TASK', None, None, self.extras).result
        droid.sendBroadcastIntent(taskIntent)
    def set_var_now(self, varname, value):
        self.new_task()
        self.set_var(varname, value)
        self.run_task()


  t = Task()
  t.set_var_now("%REPLY_ID", Number)
  t.set_var_now("%REPLY_BODY", response.result["value"])
  droid.makeToast("message sent!")


============== please name the above python script as "popup sms notifier" or any others you like.==========





======================= tasker profile part ==============

profile 1: (popup sms notifier)

content: event-receive text

task:

action 1: variable-variable clear, name: %REPLY_BODY

action 2: script-run sl4a script, name: popup sms notifier   pass variable: %SMSRD,%SMSRT, %SMSRN, %SMSRF, %SMSRB

Hit Done!



profile 2: (popup sms reply)

context: state-variable value, name: %REPLY_BODY, OP: is set

task:

action 1: phone-send sms, number: %REPLY_ID, message: REPLY_BODY, Store in messaging app Checked

action 2: variable-variable clear, name: %REPLY_BODY

Hit Done!


Thursday, April 25, 2013

Tasker to detect and vibrate once the ougoing call is being answered

Tasker to detect and vibrate once the ougoing call is being answered
as far as we may know, many 3rd party apps have the option for vibrating while the outgoing call is being answer. and this profile below is made for anyone who might not want to install any 3rd party apps and wish to use tasker to make it instead.

I happen to find that for GSM standard phone, call duration would be created into sql database only if the outgoing call is being answered, or after hanging up if it is not being answered.

So i guess this method is meant for CDMA android phone only. cause we could not detect if outgoing call is offhook by the callee via tasker or sl4a.

Java code would be the solution i think, by monitoring the phone state.
If you are interested, please follow my profile instruction below and run some test, please further advise me if it is working or any issues. many thanks!
NB.: to run sqlite 3 command, you must make sure your phone has installed the proper sqlite3 file and you must root your phone first to run sqlite3 command.
Tips:
download the sqlite3 file via the links below and renane it as "sqlite3" if it is not, then put it under the phone root directory /system/bin folder, and don't forget to modify the permission for the sqlite3 file to be
rwxr-xr-x
android 4.0 or earlier: http://bit.ly/sqlite3
profile:

context: state-phone-call, type:outgoing
task:
action 1: script-run shell,
command: sqlite3 /data/data/com.android.providers.contacts/databases/contacts2.db "select duration from calls where type <= 2 order by date desc limit 1;"
use root checked, store result in %VIBRATING
action 2: alert-vibrate, 200ms, if %VIBRATING  ~   1
action 3: task-goto, action number 2, if %VIBRATING    !~   1
Action 4: task-stop, if %VIBRATING  ~   1

 

Wednesday, April 17, 2013

Tasker to auto record incoming or outgoing call


Tasker to auto record incoming or outgoing call



most of time, i was thinking of tasker can do the job like callrecorder? if yes, how to do?
well, after done some homework, i have figured out the method below to share with you guys. via this method, tasker is able to auto record incoming
call and outgoing call, unwanted callee and unreached call will be excluded from recording.

before everything, you should create 1 folder named with english characters, eg. Voice, then create 3 separate folders inside this folder, named it as "Incoming", "Outgoing" and "Temp".

NB. if you are currently using some kind of caller location app, please make sure if it would change the call logs combined phone number and location info with symbol like angle brackets? if yes, tasker would fail to create the new file for outgoing call recording.



Profile 1: (incoming call) 
 
Context 1: Event- Phone- Offhook

Context 2: State: Incoming Call

Task: 

Action 1: variable-Variable Set [ Name:%Oncall To:0] 

Action 2: media-Record Audio [ File: Voice/Incoming/%CNAME_%CDATE_%CTIME  Source: incoming Call/Mic, Code: arm narrowband, format: raw_arm  ]  

Action 3: alert-Notify [Title:Recording Call Icon:(any icon)]

PS. you may put action 2 and 3 together as a separate task, then make it as a pop up alert positive button right after action 1, asking if you wanna
record.


Profile 2: (outgoing Temp)

Context: State: outgoing Call


Task:

Action 1: task-If, %CONUM !~ XXXXX       # XXXX stands for the phone number which you don't wish to record

Action 2: variable-Variable Set [ Name:%Oncall To:1] 

Action 3: media-Record Audio [ File: Voice/Temp/    Source:ouggoing Call/Mic Code: arm narrowband, format: raw_arm  ]   

Action 4: alert-Notify [Title:Recording Call Icon:(any icon)]


PS. you may put action 2 and 3 together as a separate task, then make it as a pop up alert positive button right after action 1, asking if you wanna
record.



Profile 3: (stop recording)

Context: Event-phone-Phone Idle

Task:

Action 1: media-Record Audio Stop

Action 2: alert-Notify Cancel, title: Recording Call

Action 3: task-If %Oncall ~ 1

Action 4: script-run shell, command: sqlite3 /data/data/com.android.providers.contacts/databases/contacts2.db "select duration from calls where type
<= 2 order by date desc limit 1;"    use root checked, store result in %COUNT

# this step is very important, cause we may know, tasker even sl4a script could not detect if the callee has picked up the phone. if duration is 0, i guess you don't wish to waste storage to record the ringtone, right? this shell command would extract the value of duration for the last phone call
you have made.

Action 5: File--Move [ From: Voice/Temp/.amr  To: Voice/Outgoing/%CONAME_%CODATE_%COTIME.amr  If,  %COUNT > 0 ]        # Based on action 4 run result,
tasker may detect and exclude the unreached outgoing phone call. so it would not waste storage space at all. cause the recording would just start
right from the moment while dialing.

Action 6: task-end if

Action 7: variable-variable clear, name: %Oncall




##  duration counting  via sqlit 3 command

if we look into the calllogs within android default call database, we will see some significant columns, which are very useful for us to get this job done.

type: (numberic)

3: incoming missed call,  2: outgoing call(reached or unreached)  1: incoming call(offhook)

duration: (seconds)

order by date desc limit 1: this is to identify and select the last one in record.


Tasker to stop Poweramp control for the headset while there is an incoming SMS

 

 

 

If you usually like to use Poweramp or any other media player to enjoy the music with headset plugged, once you check the option “respond to headset button”, Poweramp will take care of your headset line controller instead, and if you are in the middle of playing a song while there is a sms message incoming? You are not able to press the button to listen to the sms message body, cause it would just pause/resume the song instead.

 

So what is the workaround?


Anyway, there is always another way out, right? Please proceed.

 

 

 am force-stop packagename  this linux command could force stop all process from this package

 

 PM List Packages   -------This Linux command will display all the apps installed on your phone

 

PM disable com.maxmpz.audioplayer     -------this Linux command would disable the application including all process and service. We may call it like frozen. Your device would not recognize this app like it has not been installed.

 

PM enable com.maxmpz.audioplayer     ------this Linux command would enable the application to make the device recognizes this app has well installed.

 

Simply use tasker run shell with root for this command or you may use locale excute plugin for tasker if you prefer.

 

By the way, there is a better tool for you, it is secure settings for tasker. After installed, you will find the option of package state(package manager for some other devices), open this option, select the app of Poweramp, then you will see 3 options below for you to pick. On, Off, Toggle. I guess it might be much more convenient anyway.

 

 

Well, once the app has got frozen, it will not be able to control the headset button anymore. At that time, you may press the headset button to listen to the incoming sms message body.

 

 

Profile 1:

 

Context 1: state-hardware-media button, button: next, Grab checked   ------for android 2.2+, this option is available to grab the control priority for headset button if any other media player installed. PS. You better not pick “play” button, cause if you accidently click twice, it would fire to call back for your last phone call.

 

Context 2: state-app-unread text   ----------this context is used to avoid the normal situation while there is no incoming sms, so tasker would not bother other media player to control the headset button.

 

 

Action: variable-variable set, name: %MEDIABUTTON, to On

 

 

 

Profile 2:

 

Context 1: event-phone-text received, type: sms  ------- I have tested if using unread text as context, if you didn’t read the previous sms, and later there is another new message incoming, it would not fire.

 

Context 2: state-hardware, headset plugged

 

 

Action 1: plugin-secure settings, package state, poweramp set disable  -----------in some othe android device, it could be package manager instead.

 

Action 2: task-wait 5 seconds   -----------this action is to give secure settings enough time to carry on its job, since to do this would require root access.

 

Action 3: misc-say, text: you have got a new message from %SMSRN, press next button to listen, engine: default (if China user, please pick another TTS which supports Chinese.), stream: media

 

Action 4: task-wait 30 seconds until %MEDIABUTTON ~ On  -------this step is to give you enough time to press the play button, if you didn’t, it will go activate poweramp on instead of saying the message body.

 

Action 5: task-If %MEDIABUTTON ~ On

 

Action 6: misc-say, text: %SMSRB, engine: default  (if China user, please pick another TTS which supports Chinese.), stream: media

 

Action 7: variable-variable clear, name: %MEDIABUTTON   -------this is to clear the variable value after done saying the message.

 

PS. You may add one more action here running sl4a script to mark current sms as read. So you don’t have to go back to the message inbox to clear wipe it off.

 

 
 

Action 8: task-goto, action number 10   -------this step is to pass through to activate poweramp after done saying the message

 

Action 9: task-else    ---------if you didn’t press the play button in 30 seconds, this action would fire.

 

Action 10: plugin-secure settings, package state, poweramp set enable

 

Action 11: task-wait, 6 seconds

 

Action 12: plugin-autoshortcut, activity, select: com.maxmpz.audioplayer.StartupActivity    -------I did try to use tasker load app, but it doesn’t work very well most of time.

 

PS. You may use wait 5 seconds, then Go home right there after action 8, optional for you.

 

Action 13: task-end If

 

 
Tasker to answer incoming call by pressing power button



nowadays, the smartphone is getting bigger in size, eg. samsung galaxy note and note 2, sorta big in size, which you will have to use a leather protective case to cover it up.

if so, there will come up with one problem, while there is an incoming call, you would get pretty dizzy to pick up the call.

if you wish there is a way to make this easier, here we go~

this profile will be very helpful for your problem.


simply press the power button, tasker will help you pick up the call immediately. you may just go ahead to talk on the phone.


profile:

context1: state-incoming call
context2: state-Display Off

action1:input-Button, call
action2:task-Stop         # this tasks will be stopped right there after picked up the call.

Tasker to proximity screen on



in my previous entry, i posed an idea how to use the built-in proximity sensor to turn the screen off and locked. hereinafter i will show you how to use it vice versa.


Profile: (proximiy screen on)

context1:state-sensor-not proximity sensor,
context 2:state-display-display off


action: (Android 4.0+) display-turn on, if available (Android 2.3-)plugin-secure settings,configuration -wake device

if you want your phone keyguard off while the screen turns on, use display, keyguard off action, please.


NB. please make sure in tasker preference interface, you have set the proximity sensor option to "Yes", so that, the proximity sensor would stay active after the screen turns off by default.

Tasker to take candid snapshot by pressing volume key


Tasker to take candid snapshot by pressing volume key if desktop toggle widget created by tasker task is tapped

 

-------------Edited on Feb. 28, 13

 

To perform this mission, there would be two parts.

 

first part, create a profile as below.

 

profile: (candid snapshot)

 

Context1: state-variable -variable value, name: %Candidshot, operator:match, value:On

 

Context2: event-variable -variable set, variable: %VOLM, value: %VOLM  -----value must be specified, if any volume amount, the media volume must meet the specified amount to get fired. Here, I set it with %VOLM, so whatever reduce or increase would still fire. if ringer volume, it would give out a ringer tone for each pressing, so, as a workaround, I choose media volume, and set up a muted recording file as source for playback. So that, there would be no pressing tone anymore.

 

 

Task:

 

Action 1:media-take photo, camera:rear, filename:candidshot, naming sequence:chronological, insert in gallery: UN-checked, discreet:checked, resolution:1024*768(or any other options you prefer)

 

Action 2:alert-vibrate,time: 200Ms

 

Action 3: audio settings-media volume, level:11(it is my personal settings, you may set up to the top), display: off, sound: off

 

 

 

Okay, from the first part, we should see the profile would trigger if user-defined variable  %Candidshot got the value On, and ringer volume amount had any change. (whatever reduce or increase)

 

now, let us get to the second part, create a toggle widget which is made by tasker task. In order to make it visible and dynamic, I use the featured set widget icon and set widget label to visualize the on/off status.

 

Tap the tab "tasks", create a task as below.

 

Task: (Candid Shot)

 

Action 1: task-If, %Candidshot !~ On

 

Action 2: variable -variable set, name: %Candidshot, to: On

 

Action 3: tasker-set widget icon, name: Candid Shot, widget icon: (better pick a glowing one to show the status)

 

Action 4: tasker-set widget label, name: Candid Shot, label: candid on

 

Action 5: media-music play, File: Tasker/muted recording.amr, loop: checked

 

Action 6: task-else

 

Action 7: variable -variable set, name: %Candidshot, to: Off

 

Action 8: tasker-set widget icon, name: Candid Shot, widget icon: (better pick a gray one to show the status)

 

Action 9: tasker-set widget label, name: Candid Shot, label: candid off

 

Action 10: media-music stop

 

Action 11: audio settings-media volume, level:11(it is my personal settings, you may set up to the top), display: off, sound: off

 

Action 12: task-End if

 

 

 

well, right now, you may come back to the launcher desktop, add widget-tasker task, select (Candid Shot), done!

 

you may test it with one tap, and then with second tap,to see if the widget would toggle from on to off, or off to on with the pre-defined icon and label.

 

 

Tasker to create toggle widget for ES ftp service


Tasker to create toggle widget for ES ftp service

 

-----Edited on Feb. 28, 13 (Thanks again to RudeboyX, it is his great improvement on my earlier version.)

 

 

To perform this mission, Tap the tab "tasks" of Tasker, create a task as below.

 

 

Task: (ES FTP Toggle)

 

Action 1: task-If, %ESFTP !~ On     -------- here it is set up for the first run, when the variable is not set as blank. Also for the case if the FTP is set off.

 

Action 2: Misc-Send Intent,

Action: android.intent.action.MAIN
Package: com.estrongs.android.pop
Class: com.estrongs.android.pop.ftp.ESFtpShortcut
Target: Activity

 

Action 3: tasker-set widget icon, name: ES FTP Toggle, widget icon: (better pick a glowing one to show the status)

 

action 4: tasker-set widget label, name: ES FTP Toggle, label: FTP on

 

Action 5: variable -variable set, name: %ESFTP, to: On

 

Action 6: task-else    ------------- here is set up for the case if the FTP is set on, then triggers the hereinafter actions.

 

Action 7: Misc-Send Intent,
Action: android.intent.action.MAIN
Extra1: mode:2
Package: com.estrongs.android.pop
Class: com.estrongs.android.pop.ftp.ESFtpShortcut
Target: Activity

 

Action 8: tasker-set widget icon, name: ES FTP Toggle, widget icon: (better pick a gray one to show the status)

 

Action 9: tasker-set widget label, name: ES FTP Toggle, label: FTP off

 

Action 10: variable -variable set, name: %ESFTP, to: Off

 

Action 11: task-End if

 

 

 

well, right now, you may come back to the launcher desktop, add widget-tasker task, select (ES FTP Toggle), done!

 

you may test it with one tap, and then with second tap,to see if the widget would toggle from on to off, or off to on with the pre-defined icon and label.

 

One more thing, via this method, we are able to create toggle widget as many as we like within Tasker. Eg. Wifi, mobile data, etc.

Tasker to detect application running in background

 

 

We used to be told that tasker is only capable of detecting foreground application, if the app gets into background running, it would see it as exit.

 

Is it? Is there anything we can do to work this out?

 

Yes, there is a workaround, actually just sorts this out. It proves again how tasker can change our lives.

 

Okay, let us get into business.

 

First of all, you may launch an application, eg. QQ for Pad, which I usually play it often in my android pad.

 

And then, get back to the system settings, tap on the section of application, check running service, allright, you will see the icon of QQ is currently running, tap again to get into details. Right now, you will be able to see the running process or service for the app. In this case, QQ for Pad, it’s com.tencent.android.pad:service. Apparently it is a background service.

 

Stage 2, since we have got the proper running process/service name, what should we do next? No worries. Open tasker, create a new task, in the action part, select script-run shell, command: pgrep com.tencent.android.pad:service, use root checked, stored result in %PID.

 

Please note, pgrep is a linux command, which could get the process ID from the proper package name. %PID is a user-defined variable to store PID.

 

Once we got the PID, we can move onto the next stage.

 

Stage 3, get back to the launcher desktop, open RE explorer, look into the root folder, find the folder of “proc”, tap to get into and pull down the list slowly, you will see a folder with the name exactly the same as the PID you just got.

 

Okay, get into this folder, and you will find a file name: oom_adj, open it as a text file, you will see one certain digit, most likely it is 2.

 

Based on android default RAM control system, if the digit stored in oom_adj is 1 or 2, it means the app is currently running in background, if it is greater than 2, it means it is nolonger running or already cached.

 

Well, now, you guys may probably get to know my intention on how to detect an app is running in background.

 

Stage 4, from this stage, we will see how to get the digit from the proper oom_adj file. And actually we may simply just put stage 2 which we get PID from app package combined in here. Tasker, create a task, in the action part, select script-run shell, command: Cat /proc/$(pgrep com.tencent.android.pad:service)/oom_adj, use root, checked, stored result in %OOMADJ

 

If you are still confused how exactly to set up the complete profile, please be patient and follow my instruction below.

 

 

 

Example:

 

Profile:

 

Context: application: QQ for pad

 

Action 1: net-mobile data, set on      --------this is to open network once qq is running in foreground which tasker application context fired.

 

Action 2: net-wifi-set on (Optional, depends on if necessary)

 

Action 3: script-run shell, command: Cat /proc/$(pgrep com.tencent.android.pad:service)/oom_adj, use root, checked, stored result in %OOMADJ

 

Action 4: task-if, %    OOMADJ ~ 1/2

 

Action 5: task-wait, 20 minutes     ----------------- loop in 20 minutes, so it won’t drink the battery too much.

 

Action 6: variable-variable clear, %OOMADJ

 

 

Action 7: task-goto, action number 3   --------------- via this action, even if QQ for Pad is running from foreground into background, the whole tasks part would still working in loop until the app has exited.

 

Action 8: task-else

 

Action 9: net-mobile data, set off              --------------if QQ is nolonger running or cached, just cut the network off to save data stream.

 

Action 10: net-wifi-set off (Optional, depends on if necessary)

 

 

 

 NB. if the application has registered system broadcast service, or some apps don't even have an exit/quit button, even if they do, tap exit, some of them would still remain background service and background process. eg. google map, google play store, etc.
 
Conclusion, this workaround is available for the apps which don't remain background service and process after exited.

 

 

 

 

Through tasker to send google talk message command for remote control via SL4A script


Through tasker to send google talk message command for remote control via SL4A script

 

I previously posted an entry about how to remote control android devices even on PC. And now this entry would be around how to send google talk message on your android device by a tasker shortcut created on launcher desktop.

 

Of course, to do that, you firstly need to  install “Python for Android" and the tool “SL4A” in your android device.

 

 

Step 1, please create 3 variables, %IM_USER, %IM_PSWD and %IM_TO in Tasker Variable tab. Each variable denotes the specific meaning referred to the form below.

 

Parameter
Required?
Description
%IM_USER
Yes
Your gTalk user ID, including the @gmail.com part
%IM_PSWD
Yes
Your gTalk password
%IM_TO
Yes
The address to which to send the IM
%IM_TEXT
Yes
The IM text

 

 

Step 2, create a new notepad file in the folder of sdcard/sl4a/script, copy the script context below and paste it all, then rename the file into sendIMupdated.py with .py as postfix. Or you may open SL4A tool and then click Add a new script, then paste the content in it. You may refer to the original post on link as follows to get to know more about SL4A. http://tasker.wikidot.com/sendim

 

 

import sys,xmpp

import android

droid = android.Android()

 

_SERVER = 'talk.google.com', 5223

 

try:

  IM_user = droid.getIntent().result[u'extras'][u'%IM_USER']

except:

  droid.makeToast('IM_USER missing')

  sys.exit(1)

 

try:

  IM_pswd = droid.getIntent().result[u'extras'][u'%IM_PSWD']

except:

  droid.makeToast('IM_PSWD missing')

  sys.exit(1)

 

try:

  IM_to = droid.getIntent().result[u'extras'][u'%IM_TO']

except:

  droid.makeToast('IM_TO missing')

  sys.exit(1)

 

try:

  IM_text = droid.getIntent().result[u'extras'][u'%IM_TEXT']

except:

  droid.makeToast('IM_TEXT missing')

  sys.exit(1)

   

jid=xmpp.protocol.JID(IM_user)

cl=xmpp.Client(jid.getDomain(),debug=[])

 

con=cl.connect(server=_SERVER)

if not con:

  droid.makeToast('ERROR: could not connect')

  sys.exit()

 

auth=cl.auth(jid.getNode(), IM_pswd, resource=jid.getResource())

if not auth:

  droid.makeToast('ERROR: could not authenticate')

  sys.exit()

 

cl.sendInitPresence(requestRoster=0)

 

cl.send(xmpp.protocol.Message(IM_to,IM_text, typ='chat'))



 

 

Step 3, in Tasker, Tasks tab, create 1 or 2 more tasks depending on your needs of message command.

 

e.g.:

 

Task: (Shut Off)

 

Action1: Variable-Variable Set-Name: %IM_TEXT, To: shutoff (or any other specific message command you like, set the corresponding trigger action on the receiver end android device, please refer to my previous entry about remote control part)

 

Action2: Script-Run SL4A Script-[Name: sendIMupdated.py Terminal: Off (means don’t check this option) Pass Variables: %IM_USER, %IM_PSWD, %IM_TO, %IM_TEXT ]

 

 

Step 4, after done, go back to your launcher desktop, create a shortcut, point to tasker cut, then select the task “Shut Off” you just created, select an icon for this shortcut btw.

 

Finally, you may simply press the shortcut to send specific message command to remote control your android device easily.