Guia Tasker PDF

June 17, 2021 | Author: Anonymous | Category: N/A
Share Embed Donate


Short Description

Download Guia Tasker PDF...

Description

Tasker para principiantes

Con autorización expresa del autor, este artículo es una traducción del original : Beguinners guide to Tasker, by Andreas Ødegård ubicado en: http://www.pocketables.com/2013/05/beginners-guide-to-tasker-part-1-5-tasker-basics-new-ui.html

Guía "Tasker para principiantes" Esta guía, titulada, "Tasker para principiantes", es el más completo tutorial que se ha hecho sobre esta aplicación. Emplea ejemplos prácticos, pantallazos, y está escrita de una manera muy asequible. Es el mejor complemento a la guía oficial de Tasker. Ha sido originalmente escrita por Andreas Ødegård y publicada en la Web Pocketables ( http://www.pocketables.com ). Desde aquí nuestro agradecimiento a Andreas Ødegård por autorizarnos expresamente publicar esos artículos traducidos. Ya tenemos varios traducidos y publicados en el foro; en esos hilos puedes añadir tus comentarios o dudas respecto a los temas de cada lección concreta. Tasker para principiantes. Lección 1. Conceptos básicos Aquí se tratan los aspectos más rudimentarios de la aplicación y todo lo relacionado con los conceptos básicos. Escrito para la nueva interfaz de Tasker, versión 4. Ya en 2012, escribí una guía para principiantes de Tasker que en la actualidad consta de 7 partes. Sin embargo, con la nueva interfaz de usuario de Tasker, muchas de las referencias, imágenes, y videos de esa guía ahora son difíciles de seguir, ya que es en muchos sentidos una nueva aplicación. Los conceptos básicos se siguen aplicando igual, pero se visualiza y se organiza de manera diferente. Esta primera parte de la guía es la primera parada de muchos nuevos usuarios Tasker y por eso quería publicar una versión actualizada. Este artículo contiene la misma información que el original (en http://www.htcmania.com/showthread.php?p=7529064) , sólo cambia en lo relativo a la nueva interfaz de usuario. La antigua interfaz de usuario sigue siendo utilizada en versiones anteriores de Android, y sigue estando vigente. Por lo tanto, si usted está utilizando Tasker con la nueva interfaz de usuario, lea esto, y si usted está utilizando Tasker con la antigua interfaz de usuario (es decir, una versión de Android inferiores a 4.0), lea la versión original de este artículo. Si no está seguro de la versión que está usando, mire las imágenes de cada artículo para ver cuál coincide con lo que Vd. tiene. ¿Qué es Tasker? Tasker es una aplicación de automatización para Android. El concepto básico con Tasker es "si ocurre esto, hacer aquello", donde hay muchas opciones para esto y para aquello. Un ejemplo de una configuración de Tasker relativamente simple es "si el teléfono se pone boca abajo mientras suena, silenciar el sonido", pero el cielo es el límite para lo que podemos hacer. La sola acción de conectar el teléfono a la corriente alterna durante la noche inicia una compleja serie de acciones que van desde el oscurecimiento de la pantalla hasta apagar mis monitores de PC. Tasker es un shell, no los contenidos Una de las quejas más comunes que veo con Tasker es algo como esto: "Yo compré Tasker para hacer tal cosa, pero no encuentro la manera de hacerla". Esta es una queja típica de alguien que no ha entendido lo que es Tasker. Tasker puede hacer cosas simples, pero puede hacer mil cosas simples diferentes. Es una envoltura prevista para que el usuario pueda agregar contenido. Tasker requiere que el usuario configure lo que hay que hacer desde cero, y el concepto de "cero" es muy diferente de lo que normalmente te encuentras con aplicaciones móviles. No te dan un panel de configuración con el modo de control coche, es necesario realmente crear ese modo coche estableciendo una manera de decirle a Tasker cuando estás en el coche y qué hacer en dicho caso.

En pocas palabras, el aprendizaje de Tasker lleva tiempo, y un error de usuario no es un error de la aplicación. Si dedicas tiempo y aprendes, puedes revolucionar la forma de utilizar tu dispositivo. Las acciones, tareas, perfiles, proyectos, contextos, escenas y variables Estos siete términos son importantes para comenzar a entender Tasker. Acciones Una acción es la parte más básica de Tasker, una cosa que la aplicación hace. Desconexión WiFi es una acción, ir a la pantalla de inicio es una acción, bajar el volumen es una acción. Tasker tiene más de 200 acciones básicas, y la mayoría de ellas tienen distintas opciones de configuración que les permiten hacer las cosas de diferentes maneras, como por ejemplo, la acción Control multimedia(del grupo Multimedia) tiene cinco opciones diferentes para el botón que debe emular. El hecho de vincular las acciones en su conjunto te permite hacer cosas realmente increíbles con Tasker, cosas que van mucho más allá de cambiar una configuración o dos al salir de casa. Tareas Las acciones se agrupan en tareas. Una tarea puede tener una o muchas acciones, dependiendo de su objetivo. A modo de ejemplo, mi tarea "fuera de casa" tiene tres acciones: una para ajustar el brillo de la pantalla, otra para avisarme de qué tengo en mi lista de la compra, y otra para actualizar un archivo de estado en línea que dice que no estoy en casa. Las tareas también se pueden activar como acciones, por lo que una tarea puede tener varias acciones que ejecutan tareas individuales, cada una con sus propias acciones. De esta manera usted puede agrupar las acciones en conjunto en tareas más significativas, lo que le permite hacer referencia a un conjunto de acciones de las diferentes tareas. Por ejemplo, tengo una tarea con varias acciones que actualizan un widget, y esta tarea de "actualización widget" se utiliza como parte de otros trabajos en los que la actualización del widget es necesaria, como por ejemplo en mi perfil de reiniciar el sistema. Las tareas pueden ser disparadas tanto por los contextos, como directamente a través de accesos directos, widgets y otros métodos. Los contextos y perfiles Un contexto es un disparador. Una notificación entrante, la apertura de una aplicación, o conectarse a una red WiFi, son tres ejemplos de contextos que se pueden usar para activar una tarea. Si desea que el GPS se encienda cuando salga de la casa, se puede hacer, por ejemplo, que al perder la conexión a su WiFi doméstica, según ese contexto, se desencadene una tarea con una acción que encienda del GPS. A diferencia de las tareas, los contextos no pueden "vivir por su cuenta". Son siempre la primera parte de un perfil y un perfil se compone de hasta cuatro contextos y de una o dos tareas. Un perfil es lo que vincula a las tareas y contextos juntos, decide qué tarea se debe ejecutar cuando el contexto se dispara.

Hay dos tipos de contextos: contextos de estado y contextos de evento. Dependiendo del tipo de contexto (de

estado o de evento), un perfil puede estar activo de forma continua o sólo momentáneamente. Un contexto de estado hace que un perfil esté activo siempre y cuando el contexto se cumpla. Por ejemplo, si el contexto es estar conectado a una red WiFi específica, el perfil estará activo durante el tiempo que esté conectado el dispositivo. Los contextos de estado permiten dos tipos de tareas: tareas de entrada y tareas de salida. Por defecto existe la tarea de entrada, que se ejecuta cuando se activa el perfil. La tarea de salida se ejecuta cuando el perfil se desactiva. Es importante entender que, mientras el perfil está activo, Tasker no impone nada de lo que esté especificado en la tarea entrada. Con esto quiero decir que si la tarea de entrada cambia el brillo de la pantalla y luego Vd. lo vuelve a cambiar en la configuración del sistema, Tasker no va a reajustar de nuevo eso hasta que el perfil sea desactivado y reactivado. Otra cosa importante a saber sobre los contextos de estado es que algunos ajustes automáticamente se revertirán cuando el perfil sea desactivado. Así, si la tarea de entrada cambia el brillo, eso será restaurado a su ajuste previo cuando se desactive el perfil; ocurrirá automáticamente, sin que Vd necesite ordenarlo. Puede desactivar esta restauración automática del modo siguiente: haga una presión prolongada sobre el nombre del perfil, luego haga clic en el botón de configuración que aparece en la parte superior y, a continuación, desactive la casilla "Restaurar Ajustes". Pero no todos los ajustes se restablecen automáticamente; en su mayoría se limitan a la configuración del sistema, como el brillo. En los casos en los que hay múltiples contextos de estado en un mismo perfil, la relación entre ellos es Y (por ejemplo, un contexto 1 y un contexto 2), lo que significa que ambos contextos se deben cumplir para que el perfil se active.

Actualizado: Rich del Grupo Tasker Google señala que la tarea vinculada a un perfil con contextos de estado sólo se ejecuta una vez, cuando el perfil se activa. Esto es cierto, y es un punto muy importante. Un perfil que tiene sólo contextos de estado estará activo siempre y cuando el contexto se cumpla; sin embargo, la tarea de entrada sólo se ejecutará una vez. Esto significa que si, por ejemplo, ajustas el brillo de la pantalla mediante la tarea de entrada de un perfil de estado, es posible que otras aplicaciones y tareas Tasker puedan cambiar el brillo de la pantalla, mientras el perfil sigue activo, y sin que el perfil sea consciente de ello. En otras palabras, la configuración sólo persiste si nada más interfiere con ellos. Eso significa que es realmente la tarea de salida solo se puede aplicar a perfiles basados en contextos de estado, y eso incluye la posibilidad de revertir algunos ajustes automáticamente cuando el perfil se vuelve inactivo. Otra cosa importante a tener en cuenta es que una tarea de salida a veces se puede ejecutar antes de la tarea de entrada del mismo perfil, en caso de que la tarea de entrada tenga una acción Espera que provoca demoras en parte de la tarea de entrada y el perfil se puede volver inactivo durante ese tiempo.

Un contexto de evento, por contra, no define un estado continuo. La recepción de un mensaje SMS es un ejemplo de un contexto de evento, activando momentáneamente el perfil para provocar una vez la ejecución de la tarea asociada. Estos perfiles no pueden tener tareas de salida ya que no hay diferencia de tiempo entre cuando el perfil se activa y se desactiva (no hay diferencia práctica entre el momento de empezar a recibir un mensaje SMS y terminar de recibirlo). Además, es imposible tener más de un contexto de evento sencillo unido a un perfil. La razón es que, dado que un contexto de evento, por definición, sólo dura un segundo, y la relación entre contextos es Y, resultaría que el perfil solo se activaría en el caso de que los dos contextos se produjeran en el mismo momento exacto, cosa que probablmente no ocurrirá nunca.

Cuando un contexto de evento se utiliza junto con los contextos de estado en el mismo perfil, el perfil se convierte en un perfil de evento, como he mencionado anteriormente. En esos casos, el perfil se activa momentáneamente cuando ocurra el evento, pero sólo si los contextos de estado se cumplen. Por ejemplo, podrías tener un perfil con un evento de SMS recibido y un estado WiFi conectado a la red WiFi de tu trabajo, con el fin de automatizar lo que sucede cuando se recibe un mensaje SMS en el trabajo. También puede tener hasta cuatro contextos de estado en un perfil sin un contexto de evento, en cuyo caso el perfil es todavía un perfil de estado. Todas las condiciones de estado se tienen que cumplir para que el perfil permanezca activo. Variables Una variable es como un archivo de texto virtual dentro Tasker, o como una variable en matemáticas. Una variable está representada por un símbolo % seguido de un nombre, como por ejemplo %Variable1. Las variables se utilizan para tener acceso al sistema de transferencia de información entre las partes de Tasker, e incluso trabajar con ajustes y opciones. La variable %DATE, por ejemplo, siempre será la fecha actual, por lo que si usted le dice a Tasker que haga una notificación con el texto %DATE, entonces %DATE se sustituye por la fecha real cuando se genere la notificación. Voy a entrar en esto en mucho más detalle más adelante. Escenas Una escena es esencialmente una interfaz de usuario personalizada. Puede usar la escena para crear menús, ventanas emergentes, cajas de valores, y mucho más. Esta es una característica muy útil y compleja que explicaré más adelante con mayor detalle. Proyectos Un proyecto es el último grupo en Tasker. Piense en ello como una carpeta capaz de contener todo lo anterior, de modo que usted puede mantener todo lo relacionado en un solo lugar. Las configuraciones más complejas de Tasker suelen utilizar varios perfiles, tareas múltiples, y escenas, todo funcionando conjuntamente. Puede agrupar todas esas cosas en un mismo proyecto para mantenerse organizado. La pantalla de Tasker Tasker tiene un modo de principiante que está diseñado para hacer la aplicación más fácil de usar para los principiantes, inhabilitando algunas características. Lamentablemente, esto causa problemas porque me voy a referir a características que no serían visibles, por lo que recomiendo su desactivación. Esto se hace en las principales preferencias de Tasker. Por lo tanto, voy a estar basando esta guía en la búsqueda de Tasker normal, no en modo principiante. Dado que este artículo es una reescritura de una guía para la versión pre-ICS de Tasker, también es necesario decir que esto y las versiones futuras de la guía basada en la nueva interfaz de usuario se basa en el diseño de ICS +. Más específicamente, el tema que utilizo es el tema Claro, que se puede seleccionar en la sección de interfaz de usuario de las preferencias de Tasker.

Conocer la diferencia entre los diversos términos que he explicado anteriormente es la mitad de la batalla cuando se trata de entender cómo funciona la interfaz de usuario. La imagen de arriba podría ayudar a explicar donde está todo, pero vale la pena mencionar que mantener la pulsación o solo un toque en las partes de la interfaz de usuario es la manera de acceder a una gran cantidad de características. Es la forma de importar y exportar productos, añadir más contextos a un perfil, cambiar de tareas, a su vez introducir tareas en tareas de salida (o viceversa), y así sucesivamente. Además, para eliminar elementos hay que agarrarlos en la zona de la derecha de la pantalla y arrastrarlos hacia abajo a la papelera que aparecerá. Esto sirve también para ordenar los elementos y transferirlos a otros proyectos: arrastrar y soltar. ¿Qué requiere Tasker para trabajar? Cuando Tasker está activo, habrá un icono de notificación presente en tu barra de notificaciones. Esto es debido a que Tasker, obviamente, tiene que funcionar todo el tiempo para trabajar. Esta notificación también muestra qué perfiles se encuentran activos, que es una forma rápida de hacer un seguimiento del estado de los perfiles. Para evitar que el estado de un perfil sea mostrado así, abra Tasker y, haga una pulsación larga en su nombre, vaya a la configuración y desactive la opción Mostrar en la barra de notificaciones. Algunas características de Tasker, específicamente la capacidad de leer las notificaciones de otras aplicaciones, requieren que Tasker tenga acceso a nivel de sistema; hay que otorgar ese acceso de forma manual en los ajustes del sistema principal del dispositivo, sección accesibilidad. Esto, junto con una larga lista de los permisos necesarios de Tasker, puede sonar aterrador, pero cada permiso Tasker necesita está ahí por una razón muy

buena, y no es nada perverso. Tasker también requiere privilegios de administrador de dispositivos para ciertas funciones, como manipular el estado del código de bloqueo. Esto también debe ser activado de forma manual, y si se activa, también tendrá que desactivarse manualmente para desinstalar Tasker. Puede leer más sobre estos detalles aquí (enlace a página en inglés, The difference between “uninstall” and “deactivate” on Android http://www.pocketables.com/2012/07/t...n-android.html ) Hay docenas de plug-ins de Tasker, que aportan un montón de nuevas capacidades. Estos plug-ins están disponibles en la tienda Play, y se instalan como aplicaciones normales. Además, algunas aplicaciones incorporan compatibilidad con Tasker. No es necesario ser Root para Tasker, pero sí le da más posibilidades. La disponibilidad de determinadas acciones y contextos depende del dispositivo y la versión de software / ROM, y ser Root puede desbloquear características en un dispositivo determinado. Tasker también se puede utilizar para matar aplicaciones, manipular archivos, y otros. Creación de nuestro primer perfil La mejor manera de aprender Tasker es juguetear con ella y explorar. Las configuraciones de cada contexto y de cada acción son diferentes, por lo que es difícil generalizar. En la imagen siguiente se explican algunos de los botones y opciones que son bastante comunes en la pantalla de configuración de las acciones.

Cada acción y contexto tienen diferentes opciones, y con la cantidad de contextos y acciones en Tasker, explicarlos todos y cada uno es una tarea enorme. Sin embargo, existe documentación para más o menos todas las funciones y ajustes de Tasker. Se puede acceder a esta documentación al hacer clic en el signo de interrogación presente en la parte superior derecha en las pantallas de acciones de Tasker, aunque algunas veces sea una explicación breve. Debo enfatizar lo importante del estudio de cada uno para el uso de Tasker. Este artículo y otros muchos que he escrito y los artículos de otras personas que puedes encontrar Internet son un recurso excelente, pero al fin y al cabo, usted es la única persona que sabe lo que necesita de Tasker . ¿Vale la pena el esfuerzo? Porsupuesto. Después de este artículo, ¿por dónde seguir? En el siguiente enlace puedes ver otras partes de este tutorial. http://www.htcmania.com/showthread.php?p=8821039 Hasta ahora, sólo la primera parte está disponible en una versión para la nueva interfaz de usuario, pero te aconsejo jugar con las características básicas de Tasker antes de seguir leyendo. Si bien hay algunos cambios notables en la interfaz de usuario en la nueva versión, Tasker no ha cambiado, por lo que la máxima prioridad de cualquier nuevo usuario Tasker debe entender los conceptos básicos, con el fin de ser capaz de entender la información escrita para la antigua interfaz de usuario. El siguiente vídeo muestra la creación de un perfil con un contexto simple de estado, con una tarea de entrada y (más tarde) una tarea de salida. Mi consejo es jugar un poco con los diferentes contextos y acciones, y ver qué pasa.

http://www.youtube.com/watch?v=5GNXTmZIHFQ

http://www.youtube.com/watch?v=3-Zag6YnTOc#!

Tasker para principiantes. Lección 2. Variables. -Por Lukevalci-, dedicada a las variables ( o sea que básico e imprescindible).

En la primera parte de esta guía traté los aspectos básicos de Tasker, y mencioné que profundizaría en variables y en las escenas más adelante. Ambas son características que requieren un poco más de explicación que los otros aspectos en general, así que me voy a dedicar un artículo a cada uno de estos temas. El primero, las variables. ¿Qué es una variable? Las variables son parte de muchos lenguajes de programación, y Tasker es, en muchos sentidos, un lenguaje de programación. Las matemáticas también utilizan variables y en muchos casos funcionan de la misma manera. Una variable es esencialmente un archivo de texto virtual. Imagina un archivo de texto llamado variable.txt que contiene el texto "Hola Mundo". Sin embargo, en lugar de que sea un archivo físico, puede moverse, existe dentro de Tasker, y en vez de ser llamado variable.txt se llama %variable. El símbolo de porcentaje siempre está presente al comienzo del nombre de una variable y es la forma en que Tasker sepa que algo es una variable (Igual que la extensión del archivo txt permite que los equipos sepan que es un archivo de texto). El nombre que sigue al símbolo de porcentaje es en cierto modo el nombre del archivo. Al igual que un archivo de texto una variable puede contener texto, pero únicamente el texto, no imágenes. Este texto puede ser un único símbolo, un número, una URL, un párrafo de un artículo (cualquier texto, en otras palabras). Cuando se utiliza una variable en cualquier lugar de Tasker, el programa sustituirá la variable por el valor (contenido) que la misma tenga en el momento de ejecutarse. Digamos que tienes una variable %hola que contiene "Hola Mundo". A continuación, haz que Tasker cree una notificación con el texto %hola. Cuando Tasker vaya a crear la notificación, se comprobará el valor de la variable y lo usará en lugar de utilizar el nombre de la variable. Así la notificación final creada por Tasker no leerá "%hola". En cambio el mensaje será "Hola Mundo". ¿Por qué utilizar variables? El propósito de las variables es tener una manera de almacenar información de forma dinámica. Esto permite no sólo la transferencia de información entre las diferentes partes de Tasker, sino también controlar los ajustes y el texto de Tasker de forma remota, sin tener que entrar en cada contexto/tarea y modificarla manualmente. Para entender completamente el propósito de la utilización de variables, lo primero que tienes que saber son las diferentes maneras en que usted puede cambiar el valor (contenido) de una variable. Algunos ejemplos son: • Establecer el valor de una variable mediante una acción. Este valor puede ser utilizado como un contexto para un perfil completamente diferente o como parte de otras acciones. • Convertir el contenido de un archivo de texto real en el valor de una variable. • Operar matemáticamente las variables. Por ejemplo, puedes sumar +1 a una variable cada vez que se ejecuta una acción. El valor de la variable se incrementaría en valor numérico las veces que se ejecute la acción, actuando como un contador • Muchos ajustes del sistema y eventos existen en Tasker en forma variable. El valor de la variable %TIME es siempre la hora actual, %DATE es siempre la fecha, %BATT es siempre el nivel de la batería y así sucesivamente. La Lista completa de las llamadas variables incorporadas se encuentran en la ayuda de Tasker, y saber cómo utilizarlas es una de las lecciones más importantes de Tasker. En resumen, hay muchas maneras de cambiar el valor de una variable. La idea es crear una biblioteca de información a las que las diferentes partes de Tasker tengan acceso, en lugar de tener la información almacenada como texto estático que sólo es utilizable donde está escrito. De hecho, las variables comparten un montón de ventajas con internet: • La información se puede compartir fácilmente entre los participantes conectados

• La información/colaboración es posible teniendo a varios participantes trabajando en la misma información • La información puede ser actualizada en su sitio una vez y aún así llegar a varios participantes sin tener que actualizarlos cada uno de ellos directamente. Con Internet los participantes son usuarios de Internet. Con Tasker y variables, los participantes son diferentes acciones, contextos, y así sucesivamente dentro de Tasker. Creación de variables Los nombres de las variables en realidad cambian (e indican) qué tipo de variable es. Hay tres tipos de variables: globales, locales e incorporada. Para crear variables de un tipo determinado (sólo las variables globales y locales pueden ser creadas por el usuario en Tasker), sólo tienes que utilizar el formato correspondiente. Por otra parte, las variables globales se muestran en la pestaña Variables de Tasker (ver imagen de la derecha), sin embargo ni las variables locales ni las incorporadas se muestran en esta pestaña. • Las variables locales se escriben en minúsculas y sólo están disponibles para el perfil/tarea que las crea. Si tiene una tarea de "Casa" que crea una variable %casa (ojo, todo en minúscula), esa variable no estará disponible para otras tareas. Otra tarea "ajena" no debería ser capaz de utilizar esa variable. • Las variables globales se muestran en la pestaña Variables y estarán visibles y utilizables por todas las partes del Tasker. Estas variables deben comenzar con una letra mayúscula. Si su tarea "casa" crea una variable %Casa (primera con mayúscula), cualquier tarea "ajena" será capaz de verla, modificarla y usarla. • Las variables incorporadas siempre se escriben en mayúsculas. Estas son las variables que hablé anteriormente que están integrados en Tasker y que toman los valores de información del sistema. %TIME, %DATE, y %BATT son los ejemplos que he usado anteriormente. Estos pueden ser leídos por cualquier parte de Tasker, pero no se muestran en la pestaña Variables. Además, no puede ser cambiado por el usuario, ya que, por definición, muestran una parte de información generada por el sistema. La única manera de cambiar %BATT es cambiar el nivel de la batería actual mediante la carga o descarga de la batería. Excepciones No hay reglas sin excepciones. Hay algunas variables que toman la forma de variables locales pero en realidad son variables incorporadas. Un ejemplo es %new_val, que lo veremos al hablar de la creación en escena. Por el momento se puede hacer caso omiso de estos en aras de evitar una confusión innecesaria. Variables para el intercambio de información y de texto dinámico Las variables se pueden utilizar para compartir información entre las partes de Tasker, e incluso entre los plugins y Tasker. Para utilizar el símil de internet de arriba, las variables permiten que una parte de Tasker envíe información a otra parte, al igual que un usuario de Internet envía un email a otro. El concepto de texto dinámico es como la colaboración de documentos en Google Docs u otros editores de documentos en línea. En lugar de ser una creación de texto estático, partes de ella se pueden cambiar por diferentes fuentes independientes. Ejemplo 1: Mi mensaje de la mañana Tengo una elaborada configuración de “modo de reposo” que uso todas las noches. Cuando me despierto por la mañana uso una acción Tasker que se llama “Decir” (que se encuentra en la categoría Misc), que es una conversión de texto a voz. Esta acción tiene un campo de texto en el que yo escribo el texto que quiero decir y entonces el teléfono lee el mensaje en voz alta. En la actualidad, este campo de texto se lee: “Buenos días. Has dormido durante %Smduration horas. %Lazy. El Pronóstico del tiempo para hoy es

%Norweather. %Todomorningnot.” Como puedes ver este mensaje contiene 4 variables. Antes de que la acción decir comience, decenas de otras acciones ocurren, recogen y procesan los datos, y almacenar los resultados finales en estas cuatro variables. • %Smduration es la duración, en horas, durante el cual el modo reposo estuvo activo. Si se activó a 23:00 y se desactiva a 07:00, entonces el valor de %Smduration sería de 8. • El valor de %Lazy depende del valor de %Smduration. Si %Smduration es por lo menos 9, El valor de %Lazy es "bastardo perezoso". Si %Smduration es inferior a 9, no es nada. • %Norweather es el resultado de una tarea que hice para recoger datos meteorológicos noruegos. Su valor es una descripción muy breve del pronóstico del tiempo para ese día, como "sol" o "lluvia". • %Todomorningnot es parte de mi sistema Tasker basado en lista de tareas. Si tengo elementos TODO en la lista marcados como "mañana", su valor es "Tiene elementos que debían presentarse en su lista de tareas." Si no tenemos estos artículos, su valor no es nada. Mediante el uso de estas cuatro variables el mensaje de teléfono varía en función de éstas y habla por la mañana (y esta es la razón para el nombre de "variable"). Si me levanto después de 8,5 horas, en un día lluvioso que no tengo nada que hacer, el teléfono dirá el siguiente mensaje: “Buenos días. Has dormido durante 8,5 horas. Pronóstico del tiempo para hoy es lluvia.” Si me levanto después de 10,2 horas en un día soleado en el que tengo artículos en mi lista de tareas, el teléfono dirá el siguiente mensaje: “Buenos días. Has dormido durante 10,2 horas. Bastardo perezoso. Pronóstico del tiempo para hoy es soleado. Usted tiene cosas en su lista de tareas” Utilizando aquí las variables de esta manera, me da dos opciones muy importantes: • Mi mensaje de la mañana es dinámico. A pesar de que nunca entro y cambio manualmente el campo de texto de la acción Decir, el mensaje sigue los cambios. • Puedo transferir información de una parte a otra de Tasker. Las cuatro variables en el mensaje son cada una el resultado del trabajo realizado por otras tareas y acciones, y el uso de variables me permite transmitir dicha información a donde lo necesito. Ejemplo 2: AutoRemote AutoRemote es un plug-in de Tasker del que estoy especialmente encariñado. Permite que los diferentes dispositivos se comuniquen uno con el otro mediante el envío de mensajes entre sí que no son visibles para el usuario. Permite hablar a Tasker en un dispositivo, con Tasker en otro dispositivo, sin necesidad de utilizar un método de comunicación que sea para otra cosa - como SMS o correo electrónico. Los mensajes entrantes a través de AutoRemote se pueden utilizar de dos maneras: como disparadores, o como fuentes de información. Si se utiliza como disparador, se puede por ejemplo configurar un perfil Tasker que se activa si un mensaje que dice "hola" es recibido a través de AutoRemote. Esto podría servir, por ejemplo como una característica "encontrar mi tableta", donde el envío de un mensaje con un "hola" desde el teléfono a la tableta activa una tarea que hace la tableta pitar. Si el mensaje se utiliza como una fuente de información, el contenido real del mensaje se puede transferir a una variable Tasker. Digamos que usted quiere que su tableta sea capaz de decirle a su teléfono el estado de la

batería. Su tablet podría enviar el siguiente mensaje a su teléfono: “Nivel de batería de la Tablet es %BATT por ciento” Donde %BATT es una variable incorporada. Cuando la tableta envía este mensaje, reemplazará %BATT por el nivel de batería propia. Así el mensaje que llega al teléfono contendrá el nivel de batería de la tableta. El teléfono se puede configurar para buscar un mensaje que contenga "nivel de batería Tablet". AutoRemote tiene una opción para que sea una coincidencia exacta, que en este caso no queremos. Este filtro de mensajes actuaría como el contexto para el perfil, lo que significa que el perfil se activará cuando un mensaje con "nivel de batería Tablet" fuese recibido. Esto es similar al ejemplo anterior "encontrar mi tablet", pero queremos ir un paso más allá aquí - en realidad usando el contenido del mensaje también, no sólo el uso del mensaje en sí mismo como un disparador. Para ello debe configurar AutoRemote para convertir el mensaje en una variable - digamos %tabletbattery. Esa variable podría ser utilizado en una notificación, acción “Decir” o similar. Basta con crear una acción “Decir” con %tabletbattery como texto y utilizarla en el perfil que se activa por mensaje entrante, para que entonces su teléfono leyera el estado de la batería de la tableta en voz alta cuando recibe un mensaje de ella. Ya que %tabletbattery es una variable local, sólo estaría disponible dentro de ese perfil, pero fácilmente se podría utilizar la acción “Establecer Variable” en la categoría de Variable para crear una variable global. Esto se hace mediante el establecimiento de la acción “Establecer Variable” para crear una variable con una capitalización de variable global, como %Tabletbattery, y estableciendo su valor a %tabletbattery. Luego en realidad estas creando una copia global de la variable local. En este ejemplo de AutoRemote, el valor de una variable incorporada en la tablet es enviado a otro dispositivo a través de un plug-in, donde se convirtió en una variable que se puede usar en ese dispositivo. Este es sólo otro ejemplo de transferencia de información a través de las variables, pero uno más avanzado, ya que transfiere información entre dispositivos. Ejemplo 3: Minimalistic Text y Make Your Clock Widget Minimalistic Text y Make Your Clock Widget son dos apps independientes de Android para creación de widgets que ambos tienen la capacidad de recibir información de Tasker. Ambos interactúan con Tasker de forma muy similar, utilizando una acción que transfiere información desde Tasker (ya sea texto estático o el valor de una variable) en variables de las aplicaciones propias. Yo uso ambas aplicaciones y las dos con Tasker. Uso Minimalistic Text para mi lista de compras, al tener un widget en la pantalla de bloqueo en el que Tasker puede escribir información. El widget sólo muestra algo si estoy fuera y tengo artículos en mi lista de la compra, de lo contrario está en blanco. La lista de la compra está manejada por mi propio sistema basado en Tasker. La imagen de la pantalla de configuración de abajo muestra cómo está configurada la acción que hace de puente entre Tasker y Minimalistic Text. Se transfiere el valor de la variable de Tasker %Todoshopping en la variable de Minimalistic Text TODO, la cual es una variable en una aplicación completamente diferente y, como tal, no utiliza el símbolo % para indicar que es una variable. Una vez que esta tarea se ejecuta, en cualquier lugar donde se utilice la variable en TODO en Minimalistic Text (entonces se mostrará el valor de %Todoshopping. Cada vez que %Todoshopping cambie en Tasker, la acción de puente tiene que ser ejecutado con el fin de transferir esa información a Minimalistic Text.

Variables como ajustes Las variables tienen otro uso que es quizás menos aparente, pero sigue siendo muy importante a tener en cuenta: se pueden utilizar como ajustes. Esto se realiza mediante la asignación de valores a variables que entonces se utilizan como referencias más adelante. Si tienes un perfil para cuando estás en casa, puede utilizar la acción “Establecer variable” para establecer un variable %Hogar a "on" cuando se activa (tarea de entrada), y en "off" cuando se desactiva (tarea de salida). Cualquier otra parte de Tasker entonces será capaz de comprobar el valor de %Hogar y, a su vez, saber si estás en casa. Si lo piensas bien es así como funcionan los ajustes fuera de Tasker también. Si usted entra en la configuración del sistema y apaga el WiFi, básicamente estás estableciendo una variable WiFi en "off" - es sólo una forma más visual de hacerlo. Si está conectado a una red WiFi llamado McDonald, es como tener una variable para la red WiFi con un valor de "McDonalds". Hacer referencia a las variables: contextos Cuando digo que otras partes de Tasker pueden comprobar el valor de las variables y actuar en consecuencia, hay muchas maneras de hacer esto. Por contextos el valor de una variable es su contexto propio. Se encuentra ubicado en la sección Estado, categoría Variable, contexto Valor de Variable. La pantalla que se obtiene al seleccionar este contexto pide un nombre, Operador y Valor. Nombre es el nombre de la variable, como %Casa. El nombre de la variable que se pone aquí es simplemente el nombre de la variable que contiene la información que desea que el perfil tenga en cuenta y reaccione.

Op es un poco más complicado. Significa Operador, y se refiere al método que Tasker utiliza para comprobar el valor de las variables, usando una versión simplificada de las expresiones regulares. Se puede configurar para cosas como coincide, no coincide, matemáticas: Menor que, y así sucesivamente. En resumen, el operador se refiere a la relación entre el tercer campo del valor y el valor real de la variable. A modo de ejemplo, digamos que usted quiere un perfil que se activa cuando %Casa está establecido en "on" y se desactiva cuando está en "off". Luego usaría %Casa como el nombre, coincide como el Operador , y "on" (sin las comillas) como el valor. El contexto resultante se puede leer así: “Active el perfil si el valor de la variable %Casa coincide con "on" Por poner otro ejemplo, piense en el ejemplo anterior del mensaje de la mañana. La variable %Lazy tiene un valor diferente dependiendo de si %Smduration es menor que o mayor que 9. Si desea crear un perfil que reaccione de la misma manera, el nombre sería %Smduration, Operador sería mayor que, y el valor sería de 9. El contexto resultante se puede leer así: “Activar el perfil si el valor de %Smduration es de al menos 9” Para terminar con un ejemplo del mundo real, utilizo este sistema para los perfiles de ubicación. Tengo tres perfiles que son mutuamente excluyentes y que utilizan diferentes contextos. Mi perfil Casa se activa cuando estoy conectado a mi WIFI de casa, el perfil Escuela se activa cuando hay una entrada de calendario en mi calendario escolar, y mi perfil exterior se activa cuando los otros dos no están activos. Para asegurarse de que todos los perfiles son mutuamente excluyentes, uso mis propias variables como parámetros. Tanto los perfiles Escuela como Casa tienen ajustes de variables tanto en la tarea de entrada como en la de salida. Cuando el perfil Casa está activo, se establece la variable %Casa a 1, y cuando se desactiva, se establece en 0 (tarea de salida). El perfil de la escuela hace lo mismo para la %Escuela. El perfil exterior tiene entonces dos contextos Valor de Variable: %Escuela coincide a 0, y %Casa coincide a 0. En otras palabras, sólo se activa si ambas variables se establecen en 0 (que a su vez sólo ocurre cuando los otros dos perfiles están inactivos). El perfil de la escuela también tiene dos contextos Valor de Variable, %Casa coincide a 0 y %Caminoalaescuela coincide a 0. El primero hace que el perfil de la escuela no está activo cuando estoy en casa (lo que podría suceder si terminamos temprano), mientras que esta última variable se ajusta mediante un botón en una escena que tengo. Voy a tratar las escenas en el próximo artículo, pero para hacer boca, presiono un botón que dice "Desactivar escuela" y desactiva el perfil de la escuela. Esto es para situaciones en las que termine pronto, pero no vayas directamente a casa, lo que me permite activar manualmente el perfil exterior (desactivando el perfil de la escuela) para aquellas raras ocasiones. Hacer referencia a las variables: acciones No sólo los contextos pueden ser controlados por variables; las acciones también. Una de las imágenes en mi primer artículo señala la casilla de verificación “Si” en una pantalla de configuración de la acción. Esta casilla de verificación está presente en la mayoría de las acciones, y te permite controlar la acción en función de las condiciones del “si”. Una condición “Si” es simplemente una condición que debe cumplirse para que la acción se ejecute. Para todos los supuestos y propósitos, las condiciones “Si” y los contextos de “Valor de Variable” funcionan de la misma manera. Tienes un nombre de variable, un operador y un valor que se ha de comparar con el valor de la variable. En la sección anterior, expliqué cómo el contexto Valor de Variable trabaja usando la configuración %Smduration superior a 9 como ejemplo. Eso sucede en mi perfil de “modo de reposo”, pero en realidad no es

utilizado como un contexto en ese perfil: se utiliza para limitar una acción con una condición “SI”. La imagen de la derecha muestra cómo se configura. Como se puede ver la casilla de verificación “si” está activa; %Smduration se introduce en el primer campo, 9 en el segundo, y el operador >, que es el símbolo de mayor que. Con la acción configurada de esta forma, la acción sólo se ejecutará si el valor de Smduration% es mayor que 9. Si no lo es, la tarea simplemente se salta esa acción.

Puedo usar el mismo sistema para limitar las acciones individuales basadas en la variable %Casa creado por mi perfil Casa. Si quiero una acción que se ejecute sólo cuando estoy en casa, lo único que tienes que hacer es marcar la casilla “si”, escribir %Casa en el primer cuadro, seleccione = (coincide) como operador y escriba 1 en el segundo cuadro. De esta forma sólo se ejecutará cuando el valor de la %Casa es de 1, lo que sólo ocurre cuando estoy realmente en casa. Ten en cuenta que la decisión de establecer %Casa / %Escuela a 1 o 0 en lugar de on o off es una opción personal. Tú decides cómo deben ser los diferentes estados de un ajuste, y si tuvieras que crear tu propio perfil Casa con una variable %Casa, no hay absolutamente nada que nos impida usar tanto el valor "Cachivache" como "on" y "huracán" como "off". Simplemente significa que tendrías que establecer el contexto / condición Si de %Casa coincide "Cachivache". También es posible agrupar varias acciones en la misma condición “Si”. Para ello utilizas la acción “Si” que se encuentra en la sección Tarea; configúralo como lo harías con un sistema integrado de condición “Si” y luego se coloca antes de la primera acción que deseas en la agrupación. Cualquier acción que siga a la acción “Si” se anida debajo de él y sigue su condición. Se cierra el grupo mediante la inserción de una acción “Fin Si”. Esto es simplemente un método más sencillo para la aplicación de la misma condición “Si” para múltiples acciones Por último, hay una acción en la misma categoría llamada “Else”. Esta es una acción opcional que puedes utilizar entre una condición “Si” y un “Fin Si” para crear un nuevo grupo de acciones (anidadas bajo la acción “Else”) que se ejecutará si la condición “Si” no se cumple, pero sólo si no se cumplen. La ilustración de arriba muestra esto con uno de mis perfiles, donde he insertado una acción “Else” para la demostración. La forma de leer esta configuración es como sigue: “Si la condición SI se cumple, ejecute la acción 3 (Notifíqueme de sonido) y 4 (Minimalistic Text)

Si no (Else), ejecute la acción 6 (Stop)” La acción “Else” es opcional, y realmente sólo te ahorra añadir un segundo grupo “Si” que sea exactamente lo contrario del primero. Escribí un artículo sobre el control de perfiles utilizando variables, que se puede encontrar aquí. Gran parte de ese artículo es lo mismo que lo que has leído aquí, pero fue escrito para usuarios avanzados de Tasker, no para principiantes. Los caracteres especiales Cuando se realiza la coincidencia de patrones utilizando este método, es importante ser consciente de la tres caracteres especiales *, / y +. * Es un comodín, lo que significa que se puede utilizar para que coincida con una parte de un fragmento de texto. Si escribes Android en el campo de valor y coincide como operador, sólo coincidirá el texto exacto de Android. *Android* por otro lado coincidirá con cualquier uso de la palabra Android, como “me gusta Android mucho”. *Android coincidirá con “me gusta Android” pero no con “me gusta Android mucho”, ya que el comodín está sólo delante de la palabra, no detrás de ella. En algunos casos es mejor utilizar *ndroid* en lugar de *Android*, porque el primero captura tanto Android y android. Actualizado: Sean señala en los comentarios que se pueden utilizar todas las letras minúsculas en concordancia con el modelo y funcionará con todo. Por ejemplo, *ndroid* aquí no es necesario porque *android* coincidiría tanto con Android como con android. Sin embargo no funciona al revés, por lo que *Android* no va a coincidir con los dos. Yo no era consciente de ello, y es más cómodo cuando se trata de mayúsculas y minúsculas. / Actúa como O, lo que significa que permite la inserción de varios valores en un solo campo. Introduciendo 1/2/3 en el campo de valor y utilizando coincide como operador, captaría los valores de variables de 1, 2, y 3. Esto es muy útil, ya que permite crear contextos y condiciones “Si” que reaccionan a varios valores de variables diferentes. + Significa "al menos un carácter" Se puede ver el uso de esta en el “Si / Else / Fin si” de la captura del apartado anterior, en la primera acción, en el caso de la acción se configura como %Todoshopping coincida ++. Tasker lee esta condición como "Si %Todoshopping contiene al menos dos caracteres, no importa los que sean" Las variables vacías Las variables vacías no se sustituyen por espacios en blanco, sino que mantendrán su nombre de variable completo de referencia. Si se crea una notificación con %Variable como texto y esa variable no contiene nada, entonces la notificación literalmente dirá %Variable. Para hacer que aparezca un espacio en blanco en su lugar, creamos una acción “Establecer Variable” de esa variable y establecerla a un espacio. Utilice una condición “Si” con la variable en cuestión como la variable, coincide como operador, y *nombre variable sin símbolo %* como el valor (ver la imagen de abajo para ver lo que quiero decir con esto). Ejemplo para la variable %Home:

Esto escribe un espacio como valor de la variable si está vacía, que se detecta por ver si el valor de la variable es el nombre de la variable. Tenga en cuenta que usted debe insertar el espacio en el último campo de texto y guarde inmediatamente sin seleccionar nada más. De lo contrario, probablemente obtendrá un mensaje de error diciendo que el campo no puede estar vacío. Procesamiento de datos utilizando variables Hasta ahora he hablado sobre todo acerca de las formas simples de usar variables para transferir las acciones de información y control y contextos, pero eso es sólo la mitad de la historia. Para aquellos que han leído mis artículos mayores acerca de Tasker, probablemente habrás visto algunos artículos que procesan datos internamente en Tasker. Los ejemplos son un locutor de pronóstico del tiempo y locutor de evento del calendario. Lo que tienen en común es que procesan la información después de que se haya importado en Tasker, esencialmente tomando una sola variable llena de información y cortándola en trozos pequeños que se pueden utilizar como valores o como texto dinámico. Para ello, se utilizan muchas de las herramientas disponibles en la categoría de variables en la lista de acciones. “Separar Variable” es una de las más poderosas, pero también encontrarás “Sección de Variable”, “Variable Buscar y reemplazar”, y otros. Saber utilizar estas te da la posibilidad de que Tasker haga prácticamente cualquier cosa, ya que más o menos cualquier fuente de información basada en texto, online u offline, se puede utilizar con Tasker. Desafortunadamente este es un tema enorme, y ya estoy pasando de 4000 palabras en esta explicación "sencilla" de las variables. Por lo tanto, quiero dedicar un artículo entero a este tema, más adelante en la guía, después de que algunas otras cosas básicas estén aclaradas por el camino. He querido mencionarlo brevemente aquí para no dar la impresión de que falta algo. Nelly se basa en variables de coincidencia de patrones Para terminar esta parte de la guía, quiero mencionar que mi asistente DIY Tasker basado en voz, Nelly, está construido (más o menos) enteramente en el concepto de variables y comparación de patrones. Puede ser una buena idea leer este artículo (antiguo) después de esta parte de la guía, para ver cómo se aplica en la práctica y en una escala tan grande.

Tasker para principiantes. Lección 3. Escenas. Tercera parte de la guía dedicada a las escenas con las que podrás crear interfaces, botones, imágenes, y todo manejado con Tasker. ¿Qué son las escenas? Las escenas son interfaces de usuario que se pueden crear en Tasker. Piense en una escena como una caja que contiene diversos elementos que normalmente se encuentran en una interfaz de aplicación, como los botones, el texto, la introducción de texto, imágenes, barras de desplazamiento, etc. Acciones normales de Tasker pueden estar vinculadas a estos elementos, de modo que usted puede tener un botón que ejecuta una tarea, un campo de texto que le permite escribir texto en una variable, o un regulador que controla el brillo de la pantalla. Las escenas pueden ser de todo tipo de tamaños y se pueden mostrar en diferentes formas: como un cuadro de pop-up, la pantalla completa como una aplicación, como una capa superpuesta sobre otra aplicación, y así sucesivamente. El tamaño y el tipo de escena que depende de lo que necesite que la escena haga.Iré rápidamente tratando los fundamentos de cómo crear una escena, y luego voy a ir tratando múltiples ejemplos para mostrar cómo funciona todo en la práctica y con diferentes usos. Creación de una escena

Las escenas tienen su propia ficha en cada proyecto. La forma de agregar una escena nueva es clicando en el signo más. Tras poner un nombre a la escena que se está creando, lo primero que se ve es una pantalla con un recuadro en el centro, y en la parte inferior hay iconos para confirmar/volver y para cancelar, y también el icono de una lupa. Cuando el icono de la lupa no se ilumina con un trazo verde (o tiene sobre su centro una cruz), es porque se está en la pantalla para editar la base "lienzo" de la escena. Se pueden arrastrar los bordes de la escena hasta que tenga el tamaño deseado, indicado en píxeles en el borde. En la actualidad no hay manera de

establecer el tamaño en píxeles directamente, algo que probablemente va a cambiar ahora que las escenas tienen un papel mucho más importante debido a la funcionalidad de creación de aplicaciones de Tasker. También tenga en cuenta que algunos aspectos de cómo la escena se verá son controlados por la acción que desencadena la escena, de la que me ocuparé más adelante. Al hacer clic en el botón de menú, aparecerán algunas opciones como el tamaño de cuadrícula y el color de fondo. El selector de color de fondo es bastante explicativo por sí mismo, pero debo mencionar que el regulador sin etiqueta controla la transparencia / opacidad. La opción de tamaño de la cuadrícula controla la red o cuadrícula que se utiliza para editar la escena, lo que afecta a la precisión de la colocación de los elementos de la escena. Si quieres tres botones uno al lado del otro y del mismo tamaño en el escenario, tendrás que tener un tamaño de cuadrícula que permite tres botones de idéntico tamaño. Tocar la lupa hace visibles algunos botones nuevos, y también muestra la red que acaba de establecer el tamaño de la escena. Aquí es donde puede editar el contenido de la escena, añadir botones, imágenes, etc. Algunos nuevos botones también aparecen en la parte inferior, en concreto iconos que representan un osito de peluche (una mano con el dedo índice levantado) y un símbolo más. El botón del oso/mano le permite ajustar el modo táctil, con las tres opciones que son normal, mover y redimensionar. Normal significa que se puede mover y redimensionar elementos en la escena, todo dependiendo de en qué parte del elemento que toque (en el centro es movimiento, en el borde cambio de tamaño - pero en pequeños elementos a menudo sólo se puede redimensionar). Los otros dos se limitan a la edición en movimiento o re-dimensionado de un elemento. El signo más es para añadir nuevos elementos a la escena, pero también puede hacerlo si simplemente mantiene pulsada la pantalla para obtener esta opción. Si mantiene presionado en elementos existentes le permite hacer cosas como copiar, borrar, ocultar, pin, profundidad establecida, y así sucesivamente. Puede duplicar un elemento, colocar un elemento para que aparezca debajo de otro, bloqeuarlo para que no pueda ser movido accidentalmente, etc. Configuración de los elementos Hay 11 elementos diferentes que se pueden agregar a una escena, y no todos comparten las mismas opciones. Cuando se agrega un elemento, una pantalla de configuración aparece, y hay varias pestañas de configuración que se necesitan para manejar cada elemento. La pestaña IU de interfaz de usuario (y pestaña en segundo plano en su caso) suele ser bastante autoexplicativa para todos los elementos, ya que trata de cómo el elemento aparece o es mostrado. Tamaño del texto, nombre, texto, color, posición, el icono y la etiqueta son sólo algunos ejemplos de las opciones que se encontrará en esta ficha. Observe que el nombre es lo que Tasker utiliza para referirse a un elemento internamente en Tasker, mientras etiqueta o texto (en función del tipo de elemento) son los campos que controlan lo que el elemento realmente mostrará. Las Variables funcionan bien en estos campos, y voy a mostrar cómo se pueden utilizar en la práctica en ejemplos posteriores. Las otras pestañas en la pantalla de configuración varían en gran medida dependiendo del tipo de elemento. En su mayor parte, cada pestaña es esencialmente una tarea, capaz de contener acciones, y cuyo nombre indica lo que desencadena la acción. Por ejemplo, al agregar un botón a una escena aparece una pantalla de configuración con tres pestañas: UI,Clic, y Clic-largo. Clic y Clic-largo son cada una acciones que desencadenan sus propias tareas dependiendo de si se toca el botón o si deja se presionado. Cualquier cosa que usted quiera que suceda (acciones Tasker) cuando el botón se pulsa está en la pestaña Clic, y de manera similar con la pestaña Clic-largo. Por ejemplo, se puede actuar sobre el modo avión mediante un botón: eso dará lugar a un botón en el que el modo avión se activa y desactiva alternativamente cuando se hace clic. Aparte de estar en las pestañas, las acciones funcionan como usted está acostumbrado. Es posible utilizar múltiples acciones, limitarlas

utilizando condiciones Si(if), etcétera. Con 11 tipos de elementos todos los cuales funcionan de manera distinta, hay una gran cantidad de diferentes pestañas con las que hay que familiarizarse. Al igual que con las acciones individuales, hay también demasiados detalles como para tratar cada uno, pero el botón de ayuda Tasker está disponible en las pantallas de elemento de configuración para explicar cómo funciona cada elemento. Los ejemplos al final de este artículo entrarán en detalles sobre cómo están configurados los usos específicos de algunas escenas. Las escenas se pueden utilizar para hacer muchas cosas y los ejemplos son la mejor manera de tratar de explicar su potencial en lugar de tratar de explicar cada componente individualmente. Activación de escenas Entre las acciones disponibles, la categoría escena incluye 20 diferentes acciones utilizables. La mayoría de ellas tienen que ver con la manipulación de elementos mediante acciones normales, pero hay cuatro acciones especiales que controlan la existencia de una escena. Estas cuatro acciones son: Crear-escena, Destruirescena, Ocultar-escena, Mostrar-escena. Una escena puede estar activa incluso si no se muestra. Se puede comparar con cómo una aplicación puede ejecutarse en segundo plano, y de la misma manera, una escena que está activa en el fondo ocupa recursos del sistema. Crear la escena y Ocultarla se refieren a este estado de visibilidad, porque la creación no implica que la escena sea mostrada y la acción de ocultarla sirve para que una escena deje de estar visible sin llegar a cerrarla. Mostrar la escena y Destruirla son las dos opciones más utilizadas, y los únicos de estas cuatro que realmente yo utilizo. Mostrar escena muestra la escena, y la crea (la inicia) si es necesario. La acción Destruir cierra la escena, de modo que no se ejecuta en el fondo tampoco. El nombre de "destruir" puede ser confuso ya que suena como que borra la escena que ha creado, pero en realidad no afecta a la escena, a la"plantilla" que creó en Tasker en absoluto - es simplemente que cierra la escena por completo. Para hacer esto perfectamente claro, he aquí una breve vocabulario de términos utilizados a menudo con escenas:



Crear escena: Inicia una escena en el fondo, en segundo plano sin mostrarla.



Mostrar escena: Muestra una escena creada (y la crea si es necesario).



Ocultar escena: Oculta una escena, pero todavía permite que se ejecute en segundo plano.



Destruye escena: Cierra la escena completamente.

Esto puede ser confuso ya que la mayoría de la gente asume que "crear escena" se refiere a lo que haces en el editor de escenas. De hecho significa a menudo eso, la edición de una escena, por lo que sólo hay que tener en cuenta el doble uso de la palabra. Activar y desactivar habrían sido mejores opciones para los nombres, pero esto es fácil de decir en retrospectiva. Normalmente se usará Mostrar escena para hacer aparecer una escena y Destruir escena para que desaparezca y no se ejecute en segundo plano. Los ejemplos al final van a mostrar algunas maneras de utilizar estas acciones en la práctica. Opciones de Mostar-escena La acción Mostrar escena es el método que más probablemente utilice para activar sus escenas y hacer que aparezcan. Como dije anteriormente, esta acción realmente controla algunos aspectos de cómo la escena se verá. En concreto, hay una opción o display, “Mostrar como”, que en esta acción tiene 9 estados diferentes:



Superposición



Superposición, bloqueo



Superposición, bloqueo, muestra completa



Diálogo



El diálogo, sin-definición, detrás



El diálogo, definido, detrás



Actividad, ventana completa



Actividad, muestra completa



Actividad, muestra completa, sin título

Estas 9 opciones “Mostrar Como” deciden cómo se mostrará y actuará la escena. De la guía de usuario Tasker: Todas las superposiciones se muestran sobre la aplicación actual y persisten hasta que son escondidas o destruidas. Superposiciones de bloqueo sólo bloquean toques en la parte de la pantalla que cubren. Superposiciones de no-bloqueo también se muestran en el bloqueo del teclado. Los diálogos son pequeñas ventanas emergentes que interactúan con todas las entradas de usuario a la vez que se muestran y pueden ser despedidas con la tecla Atrás. Las actividades son vistas estándar de aplicaciones Android. Lo que tenemos aquí es esencialmente tres tipos de pantalla, cada uno con tres variaciones.



Las superposiciones son para las escenas que muestran una parte de otra aplicación. Digamos que usted quiere tener controles de música visible durante la navegación. A continuación, podría hacer una pequeña escena con controles de música, y mostrar estos como una superposición en la parte inferior de la pantalla cuando el explorador está activo (utilizando un Perfil de app).



Los diálogos son esencialmente cajas pop-up, como los cuadros de diálogo tipo sí/no y similares. Es posible que desee tener un perfil que se activa al enchufar los auriculares, y que luego aparezca un cuadro con varias opciones para lanzar aplicaciones. Una escena que se muestra con una opción de diálogo sería perfecto para esto. Ten en cuenta que hay una acción llamada Menú en la categoría de alerta que proporciona una manera alternativa de crear una escena de diálogo.



Escenas de actividad son para las escenas que funcionan más o menos como las aplicaciones. Como resultado, se suele utilizar estas opciones para las escenas que quiere hacer actuar como aplicaciones. Con la nueva capacidad de exportación de app de Tasker, muchas personas se encuentran utilizando escenas como las pantallas de configuración de aplicaciones exportadas.

Si utiliza cualquiera de la pantallas como opciones que no son a pantalla completa, usted también tendrá algunas opciones adicionales que ajustan la posición de la escena. Esto es particularmente útil para las escenas de superposición que a menudo tienen que ir en una cierta parte de la pantalla. Ten en cuenta que las opciones de visualización a veces actúan de manera diferente en diferentes dispositivos y versiones del sistema operativo. Mi consejo es probar las opciones y ver cuáles funcionan mejor para usted. La acción Mostrar escena también tiene una opción de "mostrar botón de salida", que está activado por defecto.

Esto muestra un botón de salida rojo en la esquina inferior derecha que cerrará la escena al tocar ese botón. Este es un mecanismo de seguridad para evitar que alguien haga una escena y no haya forma de cerrarlo. Usted puede generar un problema si utiliza ciertos tipos de visualización y desactiva esto sin que haya creado otra opción de salida, así que asegúrese de que usted tiene algún tipo de forma de destruir u ocultar la escena desde dentro de la escena antes de desactivar esta opción. En los ejemplos que siguen, preste atención a cómo la acción Mostrar escena rara vez es la única acción en la tarea que activa la escena. Muy a menudo, usted tiene que hacer una preparación adicional en la misma tarea con el fin de crear correctamente la escena, como el establecimiento de un valor de elemento (ejemplo 1), la carga de archivos de texto en variables (ejemplo 2), y la descarga de las imágenes de la web (por ejemplo, 3). También hay que prestar atención al orden de estas acciones. Ejemplo 1: tiene la acción de Mostrar escena primero, porque la otra acción actúa sobre un elemento de la escena, lo que requiere que la escena tiene que existir previamente. Ejemplo 2 y 3: tienen la acción Mostrar después, ya que las otras acciones en la tarea que desencadena la escena, tienen que reunir información y ponerla en su lugar antes de que la escena puede ser creada. Como he dicho, la parte difícil de las escenas tiene que ver con la fabricación de todas las partes trabajan juntas correctamente, no con la configuración de los elementos individuales. Ejemplo 1: menú de configuración pop-up Mi menú emergente de configuración se ha ido desarrollando paralelamente a como le he ido añadiendo cosas con el tiempo. Yo lo uso como una forma de acceder rápidamente a lasconfiguraciones que uso a menudo, la mayoría de las cuales son los ajustes para mis propios perfiles de Tasker y tareas. Hay un control deslizante y los botones de control de brillo de la pantalla, los botones para activar varios perfiles que tengo, y más botones que hacen todo tipo de cosas. ¿Cómo se activa?

Este menú de configuración se puede activar mediante dos accesos, uno en la pantalla del escritorio, y otro en mi pantalla de bloqueo. Tasker tiene una función incorporada que le permite ejecutar tareas desde accesos directos, que es lo que yo uso en este caso. Cuando se toca en cualquiera de los accesos directos, se ejecuta una tarea llamada “Mostrar Psett”. Este contiene

dos acciones, Mostrar escena: Popupsett, y realizar tarea: “Actualizar Br.”. La acción Mostrar escena es lo que he descrito más arriba, y en este caso se utiliza la opción diálogo oscureciendo lo de detrás. Actualización del control deslizante: una lección de cómo tratar con los elementos genéricos La segunda acción, que ejecuta la tarea independiente de actualización de Br, tiene que ver con el control deslizante del brillo de la pantalla en la escena. Para entender por qué está ahí, primero hay que entender cómo trabajan los elementos genéricos de una escena, así como cómo funciona el elemento deslizante. Un elemento deslizante en una escena tiene que ser configurado con un mínimo y un valor máximo, que es lo que el valor de la corredera tendrá cuando el mango deslizante este todo el recorrido hacia un lado o el otro. El brillo de la pantalla tiene 255 niveles en Tasker, así que mi regulador de brillo está ajustado para ir de 0-255. Al deslizar el cursor hasta la mitad, el valor es de 128, cuando lo deslice hasta el final, será de 255, y así sucesivamente. Esto es una configuración que está en la pestaña de la interfaz de usuario (UI) del elemento “control deslizante”. La otra pestaña en la configuración para el control deslizante es el Valor-seleccionado. Valor-seleccionado es la versión del elemento regulador de las pestañas Clic / Clic-largo que he mencionado anteriormente para los elementos de botón. Cada vez que se mueve la palanca deslizante, Tasker ejecuta las acciones añadidas a la ficha valor-seleccionado. Además, el valor que los terrenos deslizantes toman en cuando se suelta el mango se escribe automáticamente en la variable local %new_val. En mi control deslizante de brillo, moviendo la palanca hasta el final a la derecha se ajusta el valor de %new_val a 255, y se ejecutan todas las acciónes que están en la ficha Valor-seleccionado. En este caso, esta pestaña contiene una sola acción: Brillo de la pantalla, donde se establece el campo Nivel a: %new_val. El resultado es que si muevo el deslizador hasta el final, establece el brillo de la pantalla a 255, que es 100%. Es importante entender que el control deslizante no sabe que es un control deslizante de brillo. Lo único que hace es convertir la posición del control deslizante en un valor, y eso es todo. Por tanto, el control de deslizamiento se iniciará a 0 cada vez que se crea la escena, porque la corredera no conoce ni le importa cuál es el nivel de brillo actual. Con el fin de hacer al indicador deslizante estar en la posición correcta cuando la escena aparece, usted tiene que decirle al control donde se coloca el indicador. Esto es lo que hace la tarea de actualización Br. Como se puede ver arriba, esta tarea consiste en dos acciones: Establecer variable y Valor del elemento. Valor del elemento es una acción en la categoría de escena, y le permite manipular el valor de un elemento mediante una tarea. En este caso, queremos decirle al control deslizante que coloque el indicador deslilzante en el mismo nivel al que el brillo de la pantalla se encuentra actualmente en. Si usted tiene un 25% de brillo, desea que el control deslizante este a 1/4 del máximo del recorrido, y para que esto suceda, es necesario indicar al control deslizante que empiece por ahí. Mediante la ejecución de una acción de Valor del elemento que establece el valor del control deslizante hasta el nivel de brillo actual como parte de la misma tarea que activa la escena, el indicador estará en la posición correcta cuando el cuadro de pop-up aparece. Así que, ¿qué pasa con la acción Establecer variable? Bueno, el desarrollador de Tasker debía estar un poco fiebroso cuando creó la acción de Valor del elemento. El valor de campo sólo acepta variables y números globales creados por el usuario, por lo que no se puede utilizar la variable interna%BRIGHT (que siempre contiene el nivel de brillo actual) en ese campo. Para evitar este "bug", copio el valor de %BRIGHT en mi propia variable %Brait, y utilizo esa variable en el campo Valor. Es un poco tedioso tener que dar este rodeo, pero vale la pena porque un control deslizante de brillo es una cosa útil para tener en una escena y es necesario inicializarlo al nivel adecuado.

Para poner todo esto en palabras, las tareas de Mostrar escena y Actualizar Br se podrían verbalizar del siguiente modo: Mostrar una ventana emergente con la escena de ajustes y situar el indicador de control deslizante de manera que coincida con el brillo de la pantalla actual. Donde el texto en rojo indica lo que hace Mostrar-escena y el texto en azul indica lo que hace la tarea de actualización-Br. La lección importante de esto es que los elementos de una escena son genéricos, y eso significa que no siempre funcionan de la manera que usted piensa que podrían funcionar. En este caso, el control deslizante se utiliza para controlar el nivel de brillo, pero el regulador no sabe eso, por lo que necesita que se le diga que el nivel de brillo ha cambiado con el fin de mostrarlo correctamente. En el ejemplo 5 encontrará un uso para el control deslizante que prueba bastante concluyentemente que no tiene por qué ser un regulador de brillo. En cuanto a por qué las dos acciones dentro de la tarea de Actualizar Br. están en su propia tarea, en lugar de ser parte de la tarea Mostrar Psett, esto originalmente era para referirse a la misma tarea de actualización desde otros lugares que sólo requerian esa tarea. Terminé cambiar el sistema y ya sólo la tarea Mostrar Psett utiliza realmente esa tarea, lo que significa que no es necesario que esté en su propia tarea separada. Sin embargo, en el ejemplo de “Lista de tareas” a continuación, voy a mostrar un ejemplo en el que tal separación tiene un uso. La escena:

Esto es lo que la pantalla de edición de escenas muestra desde la pantalla de configuración de escenas y lo que se muestra cuando se activa. Es una colección de elementos de botón, elementos de texto y un elemento deslizante. Como puedes ver, estoy usando una malla que me permite espaciar botones de distintos tamaños distribuidos equitativamente, por medio del tamaño adecuado de la rejilla. En este caso, el cuadro Configuración en realidad parece que es pantalla completa, a pesar de que el tipo es Mostrar comodiálogoocultandoelfondo. Esto se debe a la propia escena cubre la mayor parte de la pantalla, pero todavía se puede ver la barra de estado brillando, y el efecto de la opción de ocultar el fondo. También tenga en cuenta la posición del mando deslizante. El brillo se fija en un 25% en esa imagen, y el deslizador refleja esto por la tarea de actualización Br. Sin esta tarea, el brillo real seguiría siendo del 25%, y el deslizador también habría sido capaz de controlar el brillo, pero inicialmente no habría mostrado el nivel de brillo correcto. Los siete botones de arriba:

Los siete botones de arriba hacen todos cosas diferentes, pero todos son bastante básicos. La mayoría de ellos tiene dos acciones: Realizar tareas y Destruir la escena. Destruir-escena cierra la escena “ajustes”, mientras Realizar-tarea ejecuta una tarea independiente de Tasker. Dos de los botones, “imagen de la webcam” ("WebCam image") y “lista de tareas” ("Todo list"), ponen en marcha nuevas escenas que serán tratadas como ejemplos separados. La razón por la que la tarea TeslaLED no usa Destruir-escena es porque la uso como linterna momentánea: cambia el flash LED en el teléfono, a encendido o apagado, así que quiero la escena permanezca activa (que no se cierre) cuando hago clic en el botón, y así no tengo que iniciar la escena de nuevo para desactivarlo después. La funcionalidad real de las tareas detrás de las acciones de Realizar Tarea, no es importante aquí, lo importante es usar estos botones para ejecutar otras tareas desde una ubicación central. Para que quede constancia, sin embargo, los siete botones hacen lo siguiente: Ejecutar una tarea que archiva los artículos que he escrito en este sitio ese día, abrir una escena: "ventana virtual", con imágenes de webcam, deshabilita o deja inactivo el perfil activo de la escuela utilizando una variable, cambia el flash LED, abre la escena de mi lista de tareas, enciende el monitor de mi ordenador de forma inalámbrica (N.T: esta ultima frase puede no ser del todo correcta). Botones perfil

Los tres botones de perfil controlan un sistema de perfil que está separado de mis perfiles automatizados de los que hablé en la parte 2 de esta guía. Están diseñados para ser activados manualmente, por lo que tengo botones para ellos. Cada botón cierra la escena (usando Destruir escena), le da un valor específico a la variable %Profile ("perfil"), y en el caso del botón de modo normal, se desactiva el modo silencioso. Los valores que se establecen para %Profile en el presente caso son literalmente "Modo normal", "Modo silencioso" y "Modo película". Modo de película y el modo Silencio son perfiles separados por completo, los cuales utilizan como contexto: Valor de la variable. Para que el perfil de modo de película este activo, el valor de %Profile literalmente tiene que ser "Modo película." En el artículo anterior hablé acerca de las ventajas de la

utilización de los valores numéricos en lugar de valores de texto para las variables que se utilizan como parámetros, pero en este caso, utilizando un valor de texto (complicado) tiene una gran ventaja. Esta ventaja se puede ver en la imagen de la derecha, donde se establece el elemento de texto para que aparezca "Profile: %Profile" ("Perfil: %Perfil"). Dado que el valor de %Profile es el nombre completo del perfil activo, el elemento de texto acabará mostrando el nombre de modo activo (esto se puede ver en la captura de pantalla anterior. Si hubiera empleado como valores 0/1/2 en lugar del Modo normal / Modo silencioso / Modo película, el elemento de texto sería por ejemplo "Perfil: 1". Dejando a un lado esta pequeña lección de cómo nombrar los valores de las variables, esta configuración de botón de perfil muestra cómo se puede activar y desactivar los perfiles completos utilizando elementos de la escena. Los elementos de la escena (botones en este caso) establecen una variable en valores diferentes, y luego activan varios perfiles en función de ese valor. Controles de brillo Ya he explicado cómo funciona el regulador, pero como habrás visto, también hay botones presentes que fijan el brillo a valores específicos. Estos botones sólo ajustan el brillo al nivel especificado (medido desde 0-255, por lo que el 50% es 128), y luego destruyen la escena. En cuanto al botón OK, sólo hace una cosa: destruir la escena. Ese botón está ahí para cuando se utiliza el botón de LED o el control deslizante de brillo, ya que esos dos elementos no incorporan su propia acción Destruir-escena. Como he explicado antes, la decisión de no incluir un Destruir-escena con ellos es porque espero seguir utilizando la escena después de interactuar con ellos, y por lo que si desapareciese la escena sería molesto. Ejemplo 2: lista de tareas Hace un mes me di por vencido en los sistemas comerciales de lista de tareas e hice uno propio en Tasker (N.T: enlace al artículo original referenciado, en inglés). No entro en detalles sobre cómo lo hice en ese entonces, pero lo haré ahora, ya que la mayoría de lo que sucede está una escena. ¿Cómo se activa?

El sistema de lista de tareas en la actualidad consta de tres listas, cada una para una situación diferente. Puedo recibir notificaciones de los elementos de la lista de la compra cuando salgo fuera, de la lista de por la mañana cuando me levanto, y de la lista de casa (que aparece como "after school" en algunas partes del sistema) cuando llegue a casa. Estas listas se almacenan como archivos de texto físicos en mi teléfono, pero Tasker necesita convertirlos en variables para mostrar su contenido. Como tal, las tres primeras acciones en la tarea que activa la escena “lista de tareas” son acciones de Leer archivos. Estas acciones leen los archivos de texto y los convierten en variables, una para cada lista. La cuarta acción es una acción Espera, con un propósito que voy a tratar más adelante. Esta simplemente retrasa el resto de la tarea durante medio segundo. La acción quinta y última es Mostrar escena, que en realidad hace que la escena aparezca. Al igual que el ejemplo anterior, la casilla Mostrar-Como está establecido en Dialogo ocultando el resto. La misma tarea se ejecutará desde el cuadro emergente de configuración del ejemplo 1, utilizando la acción de Realizar Tarea. La escena:

Esto es lo que la escena muestra en el modo de edición y en el uso real, con algunos ejemplos arrojados a este último por si acaso. El campo entre el título y la etiqueta es un campo de entrada de texto, y los tres campos de la parte inferior son campos de texto. Editar Texto, Botones y el botón Guardar:

Los campos de Editar Texto trabajan muy parecido a los controles deslizantes. Cada vez que se introduce algo en el campo de texto (por ejemplo, para todas y cada una de las letras ), se escribe el contenido del campo en la variable local %new_val. También se ejecutan todas las acciones en la pestaña Texto-modificado, en su pantalla de configuración, al igual que cómo el control deslizante ejecuta todas las acciones en la pestaña valor modificado cuando el deslizador se mueve. El problema con esto es que si usted está escribiendo, usted va a ejecutar esas acciones un montón de veces. Por lo tanto, le aconsejo que se mantenga el número de acciones en esta ficha al mínimo. Para mí, sólo hay una acción, que transfiere el valor de %new_val a mi propia variable, %todotitle. Yo en realidad no creo que ni siquiera necesitara hacer eso, pero tengo una vieja costumbre de utilizar variables creadas por el usuario. Cuando he terminado de escribir en el campo de texto, habrá una variable %todotitle que contiene todo lo que se teclea en el campo. Lo siguiente son los botones. Estos son botones muy simples y establecen la variable %Todotag a lista de la compra, lista de casa o lista de la mañana respectivamente.

El botón Guardar ("Save") es donde sucede la magia realmente. Cuando se hace clic, se anexa el archivo de texto correspondiente con el valor de %todotitle (más un cambio de línea) en función del valor de %todotag. En otras palabras, todo lo que escribió en el campo de entrada de texto se añade al archivo de texto para la lista que haya seleccionado mediante el boton guardar. Se filtra esto usando Si(If) en las acciones de escritura de archivos.

La lección importante aquí es cómo el uso de un botón Guardar independiente significa que puedo poner la acción de Escribir archivo fuera del elemento Editar texto y su rápida sucesión de textos modificados. Si yo hubiera puesto Escribir archivo en la pestaña de Texto modificado en el elemento Editar texto, habría escrito en el archivo cada vez que se pulsa una nueva letra. No sólo eso podría causar problemas para el sistema, si no que no se podría haber utilizado la opción de anexar para añadir el texto al final del archivo, así como también repetiría todas las letras precedentes, tan pronto como escribiera otras nuevas. Escribiendo "manzana" en el campo se traduciría en un archivo de la siguiente manera: mmamanmanzmanzamanzana Debo resaltar que lo difícil con las escenas es hacer que todo funcione en conjunto, y esto es sólo otro ejemplo. Después de que se ha guardado el texto en un archivo, se destruye la escena, y se ejecuta la tarea que activa la escena de nuevo (el que se describe al principio de esta sección). La función de esto es para actualizar la escena completa de la manera más sencilla posible, dejando libre el campo de entrada de texto y actualizar los elementos de texto, de manera que se muestren los nuevos contenidos de los archivos de texto. Aquí es donde la demora de 500 milisegundos entra en juego. Tuve problemas con la escena, no cargaba correctamente al hacerlo sin espera, por lo que añadí esa demora. A veces hay que dar a las tareas un poco de respiro, empleando las acciones de Espera.

El botón de guardar también tiene un segundo uso, dejándolo pulsado en lugar de hacer un clic corto. Esto se hace mediante la adición de acciones a la pestaña de Clic-largo, en este caso una simple acción de Destruir escena. Mientras que hacer clic en el botón hará que se recargue la escena, también necesitaba un botón que realmente cerrara la escena. En lugar de añadir un botón por separado, simplemente añadí un segundo uso para el botón Guardar. Los elementos de Texto:

La parte inferior de la escena se compone de seis elementos de texto: campos que lista el contenido de las tres listas de tareas pendientes y las etiquetas correspondientes en la parte superior. Las etiquetas son estáticas, pero las listas son dinámicas. En primer lugar, cada lista tiene una variable como contenido del campo de texto. Son las variables que se crean por la tarea inicial que crea la escena, y guardan el contenido de cada una de las listas de tareas pendientes. En otras palabras, cada uno de los tres elementos de texto contienen el texto almacenado en los archivos de texto. Cada vez que la primera tarea se ejecuta mediante la destrucción de la escena y de ejecutar la tarea de nuevo inicio, estas variables se actualizan. La acción Clic para cada elemento de texto en la parte superior abre el archivo de texto correspondiente. Estos se abren en cualquier aplicación establecida para la apertura de los archivos de texto, y esto es una forma muy rápida y sencilla de añadir una forma de editar las listas de tareas pendientes. Muy rara vez he tenido que hacerlo, ya que normalmente borro la lista entera de una vez, pero es bueno tener la opción.

La tarea Clic-largo para de cada elemento hace tres cosas. En primer lugar, se muestra una nueva escena de diálogo, la forma más rápida y sucia, mediante la acción Menú a la que antes me he referido brevemente. La acción Menú técnicamente crea una escena, que uno puede modificar, pero se configura a través de opciones propias de la acción, no en el editor de escenas. Es más rápido cuando sólo tiene que crear una escena de diálogo rápido, como aquí. Esta escena-Menú me pregunta si deseo borrar la lista de tareas correspondiente. Hay dos opciones en esta escena Menú, Sí y No. No destruye la escena Menú y, a continuación, continúa la tarea inicial del Clic largo: cierra la escena de Lista de tareas, y se reinicia/refresca utilizando el mismo método que con el botón Guardar. La opción Sí escribe un espacio en blanco en el archivo de texto de la correspondiente lista, con la opciónAñadir sin marcar. Si estuviera marcada esa opción Añadir (en la acción Escribir Archivo) ocurriría que el nuevo texto se añada al final del archivo; si no esta marcada se sobrescribe el archivo sustituyendo todo lo que contuviera. En el botón Guardar, en la acción Escribir Archivo está marcada esa opción Añadir , pero en éste no lo está, dado que se supone que debe borrar la lista.

Hay un par de razones por las que escribo un espacio vacío para el archivo de texto en lugar de escribir nada o eliminarlo. Si hubiera usado Eliminar archivos para eliminar el archivo, a continuación, Tasker me habría dado un error al intentar leer el archivo en una variable como parte de la iniciación de la escena. Si yo hubiera escrito nada en el archivo, a continuación, las variables creadas por Tasker al iniciar la escena hubiera quedado en blanco. Como se explica en el artículo anterior, esto provoca que Tasker muestre literalmente el nombre de la variable en la que se utiliza la variable. En otras palabras, una lista vacía, no se mostrará como vacío en la escena, en cambio, se mostrará el nombre de la variable, como%Todoshopping. Después de hacer clic en Sí, la escena “Lista de Tareas” será destruida, a continuación, la vuelve a crear para actualizarla. La parte no-escena de esta lista:

Como sé que es un hecho que hay gente por ahí que trataron de hacer un sistema de lista de tareas como la mía y no lo consiguieron, voy también a mencionar brevemente la parte de este sistema que no está relacionada con la

escena -por completar esta explicación. Lo que hace esta escena es darle una interfaz para la creación y gestión de la lista de tareas, pero el otro componente del rompecabezas es una forma de Tasker para verificar y actuar con base en ella. La imagen de arriba muestra mi tarea “Lista de por la mañana”. El propósito de esta tarea es comprobar la lista de tareas por la mañana y notificarme si hay elementos contenidos en ella. Empieza por leer el archivo de texto que contiene la lista en una variable. Si la lista está vacía, la variable contendrá sólo un espacio (como he explicado antes). Como tal, puede utilizar una instrucción If %Todomorning coincide con ++ para comprobar si hay algún elemento en el mismo. ++ Significa "al menos dos caracteres", lo cual es cierto cuando hay elementos reales de la lista, pero no es cierto si sólo hay un espacio. La acción 4 en la lista anterior crea una notificación con %Todomorning como texto, pero está limitado por esta condición Si (If). Como resultado, sólo se crea la notificación cuando hay algún elemento en la lista. Las acciones 2 y 3 no son muy relevantes, pero las voy a explicar en aras a no dejar ninguna pregunta. Esta tarea “Lista de por la mañana” se ejecuta como parte de una tarea mucho más grande que se ejecuta cuando me levanto por la mañana, y quiero que el mensaje hablado que me sale cuando me levanto mencione si tengo artículos en mi lista de tareas. Hago esto estableciendo la variable %Todomorningnot a "Hay artículos en su lista de tareas" usando la misma condición de la acción 4 anterior. %Todomorningnot se inserta en la acción Decir en la tarea principal de la mañana. La acción 2 se asegura de que esta variable no contiene nada si la condición Si (If) no se cumple. El resultado final es que si la lista no contiene ningún elemento, una notificación será creada, y mi mensaje de la mañana me informará de esto. Si la lista está vacía, no habrá ninguna notificación y no habrá mensaje. Ejemplo 3: Escena con ventana virtual webcam:

Mi ventana virtual ya fue tema de un artículo (N.T: enlace al artículo original referenciado, en inglés), pero no entré en muchos detalles. ¿Cómo se activa? Esta escena también es desencadenada por una tarea asociada a uno de los botones en el ejemplo 1. La propia escena contiene imágenes que han de ser descargados de la web, y debido a esto, la acción de Mostrar escena está al final de la tarea. Las tres acciones que le preceden son Obtener HTTP GET, que se utilizan para descargar

las imágenes; las imágenes se guardan en una ruta específica, por lo que cada vez que se ejecuta la tarea sobrescribe las imágenes existentes. Por eso es imprescindible que la acción Mostrar escena se ejecute después; en otro caso la escena cargará las imágenes antiguas. La opción Mostrar-Como es, esta vez, Superpuesta Bloqueada. En este caso, en realidad no importa. La escena:

La escena es tan simple como parece. Cuenta con tres elementos de imagen, cada uno de los cuales utiliza una de las imágenes descargadas de su fuente. Las imágenes han sido movidas y redimensionadas en el editor, y a pesar de que carga las imágenes recién descargadas cada vez que se muestra, se mantiene el mismo diseño. Cada imagen también tiene como acción al hacer clic el Destruir-Escena. Eso significa que al tocar cualquiera de las imágenes hará que la escena desaparezca. Esta es una escena muy simple desde el punto de vista técnico, pero la uso mucho. También se muestra el uso de imágenes dinámicas, que tienen muchas aplicaciones. Usted podría, por ejemplo, crear una escena que -al hacer clic en un botón- muestre nuevos cómics aparecidos hoy en la web. Ejemplos 1-3 en la práctica:

http://www.youtube.com/watch?v=BO7OD...layer_embedded

Los ejemplos 2 y 3 se activan con botones en el ejemplo 1, por lo que decidí crear un solo vídeo para mostrar cómo funciona todo esto en la práctica. Hay muchas cosas que van a hacer que todo en una escena funcione como debe, sobre todo cuando hay muchas cosas que tienen que trabajar juntas. Como se puede ver en el vídeo, sin embargo, todo es muy simple cuando usted realmente sabe cómo quiere llegar a utilizarlo. Ejemplo 4: notificación de Gmail: Los tres primeros ejemplos son todos usos bastante estándar para las escenas. Este no lo es. Todo comenzó con el deseo de añadir una notificación más visible para los correos electrónicos entrantes, de forma similar a los LEDs de notificación en algunos dispositivos. He experimentado con el uso del LED de la cámara, y funcionaba bien, pero no era tan elegante ... como podría ser. Mi Galaxy S II tiene una pantalla AMOLED, y una de las ventajas (N.T: enlace al artículo original referenciado, en inglés), de una pantalla así es que el color negro se crea apagando los pixeles. Los píxeles negros son por lo tanto sólo la pantalla apagada. Se me ocurrió la idea de tener un logotipo Gmail que se muestra en la pantalla, de tal manera que parezca como si sólo la parte de la pantalla con el logo se encendiera (que es en realidad lo que realmente sucede, debido a la forma en que funciona la tecnología AMOLED). El vídeo a continuación es el resultado de esta idea, y toda la magia que se hace con las escenas en Tasker.

http://www.youtube.com/watch?v=Mb2EH...layer_embedded

¿Cómo se activa?

Parte de lo que hace que este ejemplo sea tan especial es cómo se activa (o tal vez "cómo se controla" es una expresión más adecuada en esta situación). En primer lugar, esta escena se activa automáticamente mediante un perfil y un contexto. Cuatro contextos, para ser exactos. El principal es un contexto de evento para cualquier notificación de la aplicación Gmail. En otras palabras, este contexto se activa si Gmail recibe una notificación, que es sólo cuando se recibe un correo electrónico en mi caso.

Este evento de notificación se ve filtrado mediante tres contextos de estado. La variable %Sleepmode no puede ser igual a "on", el perfil del hogar tiene que estar activo, y la pantalla tiene que estar apagada. El primero de estos es para evitar que el perfil se active cuando duermo. La segunda es para asegurarse de que sólo se ejecuta cuando estoy en casa (tengo un sistema diferente notificación de Gmail para otros sitios). El tercero es para asegurarse de que sólo se ejecuta cuando la pantalla está apagada, para que no interfiera conmigo cuando estoy utilizando el dispositivo. Ahora veamos la tarea que crea la escena. La primera acción muestra la escena Notificación Gmail, que es el logotipo de Gmail en un fondo negro. El tipo de pantalla esSuperpuesta bloqueada, a pantalla completa. La segunda acción es otra Mostrar-escena, esta vez para un escenario completamente negro, con el tipo de pantalla deActividad a Pantalla completa, y sin título. ¿Por qué dos escenas? En mis pruebas, me di cuenta de que (en mi dispositivo y ROM, esto podría muy bien ser dependiente del dispositivo) el tipo de pantalla Superpuesta no era capaz de girar en la pantalla de mi dispositivo. El tipo de pantalla de Actividad sí lo hace, pero su definición de pantalla completa no incluye la barra de estado, dejándola visible. Mediante el uso de dos escenas - uno de cada tipo - me las arreglé para conseguir un escenario donde la escena se enciende la pantalla, y que en realidad cubre toda la pantalla con un recuadro negro, es decir, los píxeles se quedarán apagados en una pantalla AMOLED. Después de crear este sistema, he rooteado mi dispositivo, y ahora podría usar el plugin Secure Settings para despertar el dispositivo. Sin embargo, yo no tiendo a arreglar algo que no está roto, y el método descrito (sin root) es el mejor ejemplo de cómo se pueden utilizar las escenas de manera creativa. La acción 3, es una acción Espera que decide cuánto tiempo la pantalla permanecerá encendida (como la acción 5 en el bloqueo del sistema). En el logotipo de Gmail se puede hacer clic y eso te llevará a la aplicación de Gmail, por lo que la acción 4 está ahí para evitar que el resto de la tarea se ejecute (y al hacerlo, apague la pantalla) si en efecto hace clic en el logo. Más adelante veremos la variable que la acción de Detener usa como condición Si (If) cuando se hace clic en el logo. La acción 6 es una espera de nuevo, esta vez para asegurarse de que la animación de la pantalla de bloqueo tiene tiempo para terminar antes de que las dos escenas se destruyen con las acciones 7 y 8. Cuando todo esto trabaja en conjunto, se obtiene el resultado en el vídeo de arriba. La escena:

Las dos escenas aquí no son muy interesantes en sí mismas. La escena Notificación Gmail tiene el logo de Gmail, y eso es todo. Sin embargo, hay bastantes pocas acciones vinculadas a la tarea cuando hago Clic para la imagen. En primer lugar, se establece la variable %Gmailactive, que a su vez controla la acción de parada que he mencionado anteriormente. Entonces destruye las dos escenas utilizadas para crear la notificación. A continuación, se carga la app de Gmail, lo que me permite leer el correo electrónico que en entró. Finalmente, espera 6 segundos, y luego borra la variable %Gmailactive, reiniciándola para la próxima vez. Como he dicho, este es un uso bastante peculiar de escenas, pero también es una de mis configuraciones favoritas en Tasker. Cuando estoy en casa, mi teléfono está normalmentecolocado en un dock en mi escritorio, con la pantalla apuntando hacia mí, así que tener una notificación visible es estupendo. La posibilidad de limitarla a cuando estoy en casa y cuando no estoy usando el teléfono hace que sea mucho más útil. Para que conste, cuando no estoy en casa, en lugar de esta configuración, la notificación cambia a tres vibraciones deun segundo. Ejemplo 5: Bloqueo de pantalla con escenas

http://www.youtube.com/watch?v=JNtne...layer_embedded

Los ejemplos anteriores han sido de mi propia configuración de Tasker, con escenas y sistemas que conozco bien. Para éste último que voy a cumplir una petición de un lector de un artículo anterior (N.T: enlace al artículo original referenciado, en inglés) creando una pantalla de bloqueo con el uso de escenas. ¿Cómo se activa? Ya que estamos hablando de una pantalla de bloqueo, lo lógico sería hacer que se active al encender la pantalla, con el contexto de evento Pantalla encendida. El problema con esto es que, ya que toma unos pocos milisegundos para mostrar la escena, usted consigue este efecto de retraso cuando se utiliza ese contexto - por lo menos en mi antiguo Galaxy S II. La alternativa es dispararlo con el contexto Pantalla apagada. Esto puede parecer al revés, pero la ventaja es que la escena está preparada para mostrarse al encender la pantalla de nuevo, por lo que se visualiza con mayor rapidez. Este método sin embargo también tienen sus desventajas. En primer lugar, todos los elementos de la escena se habrán creado cuando la pantalla se apaga, y podrían luego estar desfasados cuando se enciende de nuevo. Como veremos más adelante, he añadido un elemento de texto simple con %TIME como el texto de la pantalla de mi prueba de bloqueo, que resulta en un "reloj estático" que muestra la hora en que la escena fue creada (pero no cambia por si misma). Mostrar la hora es útil para comprobar rápidamente la hora encendiendo la pantalla, pero eso solo vale si la escena se crea al mismo tiempo, no si se muestra la hora de cuando la pantalla se apagó. Sin embargo, es posible arreglarlo a medias si agregamos un perfil que se dispara con el contexto Pantalla Encendida, y lo utilizamos para actualizar los elementos relativos al tiempo, mediante el uso de diversas acciones en la categoría de acciones de la escena. A continuación, obtendrás una escena que aparece rápidamente, pero con los datos erróneos, y que se actualiza después de una fracción de segundo. El segundo problema con el uso de Pantalla apagada es que usted puede tener una pantalla de bloqueo de seguridad (por ejemplo, pantalla de patrón de desbloqueo) por debajo deesta pantalla de bloqueo creada en

Tasker; en tal caso, es necesario utilizar la visualización de tipo diálogo para hacer que pantalla de bloqueo de Tasker esté en la parte superior, si eso es lo que quiere, por supuesto. Desafortunadamente, cualquier escena de diálogo también se convierte de nuevo en la pantalla, así que cuando se bloquea la pantalla, se creará una escena que convierte la pantalla de nuevo. (¿? "Unfortunately, any dialog scene also turns the screen back on, so when you lock the screen, it will create a scene that turns the screen back on.") Usted también puede medio solucionar este problema, añadiendo en la tarea una acción de bloqueo del sistema después de la acción Mostrarescena. Y a continuación, terminar con un bloqueo de pantalla que parpadea brevemente cuando se enciende la pantalla. Así que, en resumen, ambos métodos tienen problemas. La fracción de segundo que tienes que esperar cuando se utiliza la pantalla del contexto no es una opción mala, salvo que seas muy exigente. Creación de un escenario de bloqueo de pantalla. Ahora es donde comienza la diversión! Hay bastantes cosas que usted puede hacer para crear una pantalla de bloqueo en Tasker, y el resultado final puede ser bastante impresionante. Empecé poniendo un control deslizante, para moverel deslizador (o el pulgar como Tasker lo llama), y llevarlo de 0-100. Luego me fui a la pestaña de Valor seleccionado y añadíuna acción Destruir-escena con la condición Si(If) %new_val es mayor que (>) 90. ¿Por qué? Para desbloquear deslizando! Al mover el deslizador más a la derecha del 90%, se destruye la escena y la pantalla se "desbloquea". A continuación, agregué el "reloj." Es un elemento de texto simple con %TIME como texto, como he explicado anteriormente. Con un tamaño de texto de gran tamaño hace que se vea como un widget. Usted también tiene %DATE (fecha), %BATT (batería), y un montón de otras variables integradas para ayudar a poblar su escena pantalla de bloqueo. Sólo recuerde que a más dinámico el contenido que desea añadir, más se tiene que actualizar utilizando un segundo perfil si usted elige la opción Pantall-apagada para activar la escena. A continuación he añadido un logo de Gmail mediante la inserción de un elemento de imagen y el uso del logo aplicación Gmail. He añadido una acción para abrir la aplicación Gmail como una acción de Clic, así como una acción de Destruir-escena para cerrar la pantalla de bloqueo antes de hacerlo. Ya que no voy a utilizar este sistema de bloqueo de pantalla yo mismo, añado texto estático para mostrar correos electrónicos nuevos al lado del icono. Añadir un contador de correo electrónico real o contador de SMS no es un problema (N.T:enlace al artículo original referenciado, en inglés). Por último, he añadido una imagen estática de mi perro, sólo para llenar la pantalla. Si yo fuera a utilizar realmente esto, sin embargo, habría utilizado el resto del espacio para otra cosa, como la información del propietario y otras preferencias personales. Una vez que la escena está preparada, todo lo que tienes que hacer es vincularla a una tarea que se ejecute con tu contexto preferido. Pantallas de bloqueo dependiendo de la situación: Si bien no voy a sustituir mi pantalla de bloqueo de WidgetLocker por este sistema, hay una ventaja de este sistema de escena que me hace estar muy tentado de usarla: Tener pantallas de bloqueo dependiendo de la situación. Usted puede crear fácilmente múltiples escenas para diferentes ocasiones, dependiendo de que esté en casa, en las afueras, en la escuela, el trabajo, y así sucesivamente. Mucha gente, yo incluido, tiene perfiles para distintos lugares y situaciones, y utilizarlos para controlar qué escena se muestra es tan fácil como tener múltiples acciones de Mostrar escena con condiciones Si (If). No puedo entender por qué WidgetLocker no tiene perfiles, pero no hay muchas esperanzas al respecto, por lo que he visto de la respuesta del desarrollador a comentarios de los usuarios. A pesar de ello, sin embargo, el uso

de escenas como las pantallas de bloqueo no se ha llegado todavía, si usted me pregunta, pero está ridículamente cerca de algo que no fue diseñado para ello. Para terminar, esta ha sido una parte muy larga de la guía (N.T: que me lo digan a mi !!!), con un mayor énfasis en ejemplos que en la teoría. Eso es simplemente porque la característica de escena tiene tanto potencial que creo que es más fácil entender cómo funciona viendo ejemplos de la vida real. Como te habrás dado cuenta, sin embargo, hay un montón de cosas de menor importancia aquí y allá, que hace cada escena única, desde la obligación de pre-carga de datos antes de crear una escena a usar varias escenas para combinar sus ventajas. La siguiente parte de la guía se referirá a los datos de proceso con variables, lo cual es algo que abre toda una gama de nuevos usos para Tasker.

Tasker para principiantes. Lección 4. El procesamiento de datos en variables. Obtención de datos externos y su tratamiento para extraer la información que necesitamos.

Una vez vistos los conceptos básicos, las variables en general y las escenas ( http://www.htcmania.com/showthread.php?p=8821039 ), es el momento de profundizar en algo un poco más específico: Procesamiento de datos utilizando variables. Es más bien una característica implícita de los temas anteriores, pero también es (en mi opinión) una de las características más poderosas de Tasker. ¿Procesamiento de datos en variables? En cierto modo estoy inventando esta expresión, pero es un buen término para referirnos a este aspecto de Tasker. Mediante el procesamiento de datos en variables me refiero a cómo se puede trabajar con los datos almacenados en las variables, extraer información de ello, creando sus propios contextos, y así sucesivamente y así sucesivamente. En mi Tasker tengo varios perfiles y tareas que utilizan esta característica, y algunos de ellos han sido publicados antes. El locutor de eventos del calendario y el sistema de anuncios meteorológicos son ejemplos de procesamiento de datos variables. Se trata de tomar algunos datos -texto, en otras palabras- y trabajar con ellos hasta que usted consigue lo que necesita.

Fuentes de datos Para entender realmente el poder de procesamiento de datos variables primero tiene que darse cuenta de cuántas posibles fuentes de datos hay por ahí. Más o menos cualquier cosa que se almacena en forma de texto se puede utilizar en Tasker, si se sabe manejar. Son fuentes potenciales de datos las páginas web, los datos del calendario, los documentos de texto, etc. Si ve algún texto, lo más probable es que pueda utilizarlo en Tasker, es así de simple. Los datos meteorológicos, noticias locales, fases lunares, horóscopos, artículos, lo que sea. ¿Quiere crear un perfil que se active cuando su horóscopo cite la palabra dinero? No hay problema. También es importante entender la diferencia entre lo que ve y lo que un ordenador ve. Una página web es vista por el ordenador como texto puro, una mezcla de referencias a imágenes, textos, normas sobre cómo diseñar la página, etc. En la mayoría de navegadores, pulsar CTRL+U nos lleva al “código fuente” de la página, lo que mostrará lo que el ordenador ve: la página web en forma de texto puro. El caos de texto que te saluda cuando nos fijamos en la fuente puede ser aterrador al principio, pero como se verá más abajo, también puede ser de gran utilidad. La lectura de datos en variables La primera parte de cualquier sistema basado en fuentes de datos externas es poner los datos en una variable, para que podamos trabajar con ella. Hay muchas maneras de hacer esto, pero algunas de las acciones más relevantes son Leer-archivo, HTTP-Get, Captar-voz y Consulta-de-variable. Sin embargo, en los ejemplos nos centraremos en los datos recopilados con HTTP-Get, ya que es el más difícil de trabajar, y el más poderoso.



Leer-archivo lee un archivo almacenado en la memoria interna y coloca su texto en una variable.



HTTP-Get se utiliza para obtener (el texto de origen de) una página web y colocar su texto en la variable %HTTPD.



Captar-voz se usa para escuchar para la entrada de voz, que luego se convierte en texto y se almacena en la variable %VOZ. Esta es la base de un asistente de voz casero como mi Nelly.



Consulta-de-variable muestra un cuadro de diálogo pidiendo un valor variable. Excelente para cosas como entradas rápidas para la lista de tareas pendientes, tareas relacionadas con contabilidad, archivo, etc.

HTTP Get HTTP Get (que se encuentra en la categoría de acciones de Red) es quizás la acción de recogida de datos más versátil, ya que le permite cargar páginas web en variables. Pero tiene sus peculiaridades. En teoría, se carga el contenido de la página web en la variable incorporada (interna) %HTTPD. Sin embargo, en algunos dispositivos, como el mío, %HTTPD simplemente no contiene los datos correctos (o cualquier otro dato) después de usar HTTP Get. En estos casos, una solución excelente es usar HTTP Get con la opción de guardar el resultado en un Archivode-salida, seguida de otra acción Leer-archivo que pase el texto a una variable. Esto se verá así en varios ejemplos a continuación, aunque debo señalar que la forma correcta de hacer las cosas (cuando funciona bien) es el uso simple de HTTP Get para llenar directamente la variable %HTTPD. Por otra parte, para trabajar libremente con los datos, normalmente necesitaremos tenerlos en variables de usuario, lo que significa tener que copiar el contenido de %HTTPD a otra variable, y eso también son dos acciones, igual que si utilizamos HTTP Get y luego Leer-archivo. En la pantalla de configuración de HTTP-Get, verá varios campos, los dos primeros son del servidor: Puerto y Ruta.

Como regla general, en la casilla del Puerto pondremos el dominio (como por ejemplo .COM) y cualquier otra cosa que le preceda; y el resto en la casilla de Ruta. Por ejemplo, la URL http://www.pocketables.com/2012/09/beginners-guide-to-tasker-part-3-scenes.html Se dividiría en estos dos campos: Servidor: Puerto: http://www.pocketables.com Ruta de acceso: 2012/09/beginners-guide-to-tasker-part-3-scenes.html En teoría, tras ejecutar la acción, el contenido de esa URL debe quedar en %HTTPD. Si eso no ocurre, utilice el campo Archivo-de-salida para guardar el texto en un archivo (por ejemplo pocketables.txt) y luego use la acción Leer-archivo para obtener la información de ese archivo. Herramientas de procesamiento de datos Una vez que tenemos los datos en una variable, comenzaremos con el trabajo para utilizarlos. A menudo, especialmente si carga las páginas web enteras en una variable, la variable se convierte en un barullo de texto. Siempre es una buena idea hacer estas configuraciones de Tasker delante de un ordenador, de modo que usted pueda tener el texto completo delante. Si está trabajando con una página web, por ejemplo, es buena idea tener el código fuente (CTRL+U) de la página a la vista, para obtener una mejor perspectiva de lo que hay en la variable de Tasker. Vas a verme hacer esto en el vídeo del ejemplo 2. A continuación voy a explicar algunas de las herramientas más comunes que se utilizan trabajando con datos. Todas son acciones que manipulan el contenido de una variable, y como tales, se encuentran en la categoría de variable. No voy a describir todas las posibilidades, pero sí las más importantes. Separar-variable

Felicidades, usted acaba de conocer la acción más importante que existe para este tipo de configuración de Tasker. Separar-Variable bien podría llamarse Rebanar-variable o Despiezar-variable, porque lo que hace es que separa el contenido de una variable en partes más pequeñas. Cuenta con dos campos de configuración relativamente simples: Nombre y Separador. Nombre es el nombre de la variable que desea cortar en trozos, ySeparador es el carácter o expresión que se usa como referencia para dividir el contenido de la variable.

Por ejemplo, digamos que usted tiene una variable %Aficiones que contiene el texto "fútbol,hockey,natación". En ese caso, usar una coma (,) como separador, hará que la "motosierra" se dirija a todas las comas y cortará el texto en esos puntos. Los separadores se destruyen en el proceso. Esto crea nuevas variables derivadas de la original y que están numeradas, conteniendo cada una un trozo del texto inicial. En el caso del ejemplo, se llega a las siguientes variables: %Aficiones1: fútbol %Aficiones2: hockey %Aficiones3: natación Usted acaba de utilizar las comas como puntos para separar una sola variable en pequeñas partes individuales. Este método es el alfa y el omega del procesamiento de datos en variables. Al elegir los separadores correctos puedes cortar variables enormes que contienen las páginas web enteras, obteniendo trozos más pequeños y manejables que contienen sólo la información que necesitamos. Puede separar una página web meteorológica para obtener solo el pronóstico del tiempo, o separar un sitio de noticias para usar los titulares. Aquí es donde resulta útil todo el texto "raro" que hay en una página web. Con mucha frecuencia podemos usar como separadores las etiquetas que se utilizan para asignar formato a partes específicas de una página web, lo que nos permite coger de la página web las partes que nos interesan. Encontrar un buen separador es algo fácil si se tiene la fuente en un ordenador junto con CTRL+F (buscar texto en la página). Como ejemplo, echemos un vistazo a pocketables.com. Supongamos que queremos crear una lista de los artículos que aparecen en su página principal, con los títulos y sus enlaces. Cargamos la página en la variable %Pocketables. Poniendo esa fuente en un navegador (que es también lo que hay en %Pocketables), vemos cómo cada artículo aparece en el código fuente:

Las etiquetas (como ) que hay en ese texto son las que le dicen al navegador cómo mostrar la página normalmente. Tasker ve este código cuando se carga una página web en una variable como esta. Todo lo cual es una ventaja, ya que podemos utilizar estas etiquetas como separadores. En este caso, vemos que el enlace a cada artículo está inmediatamente precedido por queda el título al principio de la variable %lbnews22, pero todavía lleva un poco de basura al final. Otra división sobre %lbnews22 usando el separador nos deja con una variable %lbnews221 conteniendo sólo el titular buscado, que puede ser utilizado directamente en acciones dentro de la misma tarea, o transferidos a una variable global para utilizarlo en otros lugares. Dado que la división inicial creado varios hijos que compartan el mismo formato que %lbnews2, sólo con un artículo diferente, podemos copiar las acciones de división de %lbnews2 y %lbnews22%, y simplemente reemplazar las variables con %lbnews3 y %lbnews32, respectivamente. Tras eso tendremos %lbnews321, que contiene el segundo titular -y nada más. Copiar de nuevo y hacer lo mismo con el número 4 nos daría el titular

tercero en %lbnews421, y así sucesivamente para todos los titulares que se deseen. Cada titular estará en su propia variable puede ser utilizado en una acción Decir u otra. Como he dicho antes, hay maneras de automatizar esto más allá de copiar manualmente las acciones para cada hijo, pero en aras de la simplicidad no voy a entrar en eso. Tarea de descarga: Las descargas a continuación contienen la tarea final con 5 variables-titulares completos. Se puede editar para cambiar el número de titulares si fuera necesario. Siga las mismas instrucciones del ejemplo 1 para descargar e importar esto en Tasker. La acción final, que es un decir, tiene que modificarse para especificar un motor de voz diferente si el motor Amy UK Inglés Ivona que estoy usando para mi texto a voz no está instalado. Descarga:Lpnews.tsk.xml Descarga:Lpnews.tsk.xml.zip Ejemplo 3: Locutor de eventos del calendario de Google Esta es otra tarea similar. Esta vez obtiene datos de Google Calendar aprovechando la capacidad de Google Calendar para acceder a la agenda con un enlace web, en formato XML. Al igual que con el ejemplo 1, te voy a dar una tarea que se puede descargar e importar y, a continuación, voy a explicar cómo funciona. Preparación Descargar la tarea de la parte inferior del artículo. Hay cuatro versiones disponibles: descargas directas XML y versión comprimida para cada una de las dos versiones de tareas básicas, DDMM y MMDD. La versión básica que se necesita depende del formato de fecha que se tenga establecido. Esta tarea sólo funciona con los formatos de fecha DD/MM/AAAA y MM/DD/AAAA. Esto está establecido en la configuración del sistema del dispositivo, en la sección de fecha y hora. Se tiene que utilizar uno de los dos indicados, o no funcionará. Si usted lee 12/07/2012 como 12 de julio, necesita establecer MM/DD/AAAA. Si lo lee como 07 de diciembre, utilice DD/MM/AAAA. Siga las instrucciones que aparecen en el ejemplo 1 sobre cómo descargar e importar la tarea. http://www.youtube.com/watch?feature=player_embedded&v=b5aR9BozbQA Una vez importado, abra la tarea, vaya a la acción HTTP Get. En el campo Ruta, verá XXXX y YYYY como parte de la ruta: calendar/feeds/XXXX%40gmail.com/private-YYYY/full?singleevents=true&futureevents=true&orderby=s tarttime&sortorder=ascending&max-results=1 Hay dos cosas que tiene que cambiar. XXXX necesita ser reemplazado con su nombre de usuario de Google, por ejemplo, "fulano" si su correo electrónico de acceso para Google es [email protected]. Si su dirección de correo electrónico de Google no termina en @gmail.com, también hay que cambiar lo que sigue al %40 con lo que sea el dominio de su correo electrónico. Ejemplos: calendar/feeds/fulano%40gmail.com/private-YYYY/full?singleevents=true&futureevents=true&orderby=s tarttime&sortorder=ascending&max-results=1 calendar/feeds/fulano%40googlemail.com/private-YYYY/full?singleevents=true&futureevents=true&orderby=s tarttime&sortorder=ascending&max-results=1

YYYY necesita ser reemplazado con una clave de acceso privado para el calendario de Google. Para conseguir esta clave hay que empezar por ir a la página web de Google Calendar. Entre en la configuración, haga clic en la ficha Calendarios y elija el calendario que desea utilizar. En la parte inferior de la pantalla de calendario, haga clic en el botón naranja XML que está junto al rótulo Dirección Privada. Debe obtener un cuadro emergente con una dirección URL similar a la siguiente: https://www.google.com/calendar/feeds/fulano%40gmail.com/private- 1234567812345678/basic La clave de acceso es la parte que se destaca en negrita. Debe copiar esto en lugar de YYYY, en el campo Ruta de Tasker. Un ejemplo de una ruta acabada sería: calendar/feeds/fulano%40gmail.com/private1234567812345678/full?singleevents=true&futureevents=true&orderby=s tarttime&sortorder=ascending&maxresults=1 Guardar los cambios realizados en la acción HTTP Get y luego buscar la acción Decir del final. Seleccione un motor de voz que tenga instalado en su dispositivo. Nota: Calendarios (de Google Calendar) creados recientemente utilizan un formato diferente, con una dirección de correo electrónico [email protected] en la URL. Esta tarea ha sido probada para funcionar con el nuevo formato, pero es necesario especificar tanto a la dirección de correo electrónico como la clave del botón XML mencionado anteriormente. Tarea de descarga Descargar (DDMM, xml.):CalendarDDMM.tsk.xml Descargar (DDMM, zip.):CalendarDDMM.tsk.xml.zip Descargar (MMDD, xml.):CalendarMMDD.tsk.xml Descargar (MMDD, zip.):CalendarMMDD.tsk.xml.zip Explicación Esta tarea se hizo a demanda para un propósito muy específico: Leer el próximo evento del calendario, si es del mismo día. Esto significa que no voy a enumerar varios eventos, aunque se podría utilizar un método similar cambiando la URL de origen. Acciones 1-2: Lee los datos en una variable, como antes. Acción 3: Copia la variable en otra variable, ya que va a ser su división en múltiples ocasiones. Lo hicimos antes también, con otra variable. Acción 4: Hace una división de la variable %Ceventdate, que es la copia de los datos de la agenda de origen, utilizando como separador startTime='. Esto delimita la fecha y hora de inicio del evento. Por tanto, esa información queda a la derecha de la primera división, en %Ceventdate2. Acción 5: Copia el valor de %Ceventdate2 en una nueva variable, %Eventdate. Al igual que antes, esto se debe a que vamos a utilizar múltiples fragmentos de variables, y no quiero perder el contenido original.

Acción 6: Divide la recién creada copia de %Ceventdate2, %Eventdate utilizando el separador – (guión). %Eventdate contiene datos en el formato 2012-09-12T21:30:00.000+02:00, lo que significa que la división con un guión pone el año en su propia variable, el mes en su propia variable, y en otra variable pone el día del mes añadiendo un poco de texto basura al final. Acción 7: Esto divide %Eventdate3, que es el tercer hijo de la acción 6 (el que tenía el día del mes, más basura), utilizando la T como separador. Esto es puramente para limpiar esa última variable de la acción 6, eliminando la basura. Acción 8: Crea una variable %Samedayevent y establece su valor a "no." Esto es para asegurarse de que el valor predeterminado de esta variable es "no", en caso de que la condición Si(If) en acción 9 no se cumpla. Previene que esta variable arrastre valores resultantes de ocasiones anteriores en que se haya ejecutado la tarea. Acción 9: Sobrescribe el valor de la variable creada en la acción 8 en "yes" si la fecha coincide con %Eventdate31%Eventdate2-%Eventdate1. Esto requiere un poco de explicación para dejar claro lo que se pretende. %DATE es una variable insoportada de Tasker que contiene la fecha. Está en un formato específico, lo mismo que la configuración del sistema del dispositivo - por lo tanto ¿por qué hay varias versiones de la tarea según el formato de fecha utilizado? %Eventdate31-%Eventdate2-%Eventdate1 contienen el día, mes y año que se obtuvieron en las acciones 6-7 y reorganiza esa información para que coincida con el formato que tiene %DATE. De esta manera, estamos en condiciones de comparar la fecha actual (%DATE), con la fecha del próximo evento, a pesar de que originalmente están en formatos diferentes! Después de la acción 9, tenemos una variable %Samedayevent que es o "no" (si la condición Si(If) en el 9 no se cumplió) o "yes" (si es que se cumplió). Esta variable es una configuración que usaremos más adelante para controlar si la acción Decir debe mencionar el siguiente evento. Tenga en cuenta que, como he dicho, esta tarea se creó originalmente para alguien que quería esta característica específica. Muchas personas preferirán que se muestre el evento siguiente, sin importarles que sea de otro día. Sin embargo, es un gran ejemplo de cómo se puede procesar un lío de datos para adaptarlos al mismo formato que utiliza Tasker. Acción 10: Ya hemos terminado con las acciones que servían para comprobar si el evento es en el mismo día. Hemos estado trabajando con otra variable para obtener la fecha del evento, y ahora volvemos a la variable %Calendar original, que habíamos reservado desde el principio. No creo que hubiera importado si no la hubiéramos copiado desde el principio, pero siempre es una buena práctica hacerlo para estar seguro. La acción 10 hace Separar-variable sobre %Calendario con el separador . Este es el texto que precede inmediatamente el título del evento, y aunque no es único (se usa una vez antes en el texto original), está bien para aprovechar este tiempo porque siempre tendremos sólo una aparición de ese texto antes de la que queremos. Eso sólo significa que en lugar de utilizar el hijo %Calendar2, usamos %Calendar3. Acción 11: De nuevo hacemos Separar-variable %Calendar3 con el separador . Esto es sólo para la limpieza de la basura en el texto final de %Calendar3, un procedimiento que hemos usado muchas veces a estas alturas. Acción 12:

Divide la variable %Ceventdate2 con el separador T . No hemos utilizado la "familia" %Ceventdate aún, pero todavía está ahí para lo que necesitemos. Esta vez estamos después de la hora, no la fecha, por lo que estamos empezando de nuevo. La razón por la que copió %Ceventdate2 a una nueva variable en la acción 5 iba a ser capaz de hacerlo ahora. %Ceventdate2 es idéntica a la %Eventdate original, por lo que su valor empieza con datos en el formato 2012-0912T21:30:00.000+02:00. Creo que podríamos haber utilizado %Eventdate32 directamente en lugar de empezar de nuevo desde este momento con %Ceventdate2, pero la tarea original fue hecha con un poco de prisa, y no quiero cambiar la tarea en este ejemplo para mantenerla igual a la que se descargaba antes. Es difícil hacer un seguimiento de todas estas variables hijo, y a veces se las confunde. Por eso es mejor prevenir que curar. Acción 13: Un ejemplo real de Sección-de-variable aplicado a %Ceventdate22, que ahora contiene datos en el formato 21:30:00.000+02:00*basura*, donde sólo nos interesan 5 caracteres. Eso significa que obtenemos las horas, los dos puntos, y los minutos - el tiempo, en otras palabras. Esta es una buena aplicación de la acción Sección-devariable mencionada arriba, y nos evita tener que volver a montar el tiempo como se hubiera tenido que hacer si antes hubiéramos dividido con los dos puntos. Acción 14-15: Estas dos acciones establecen la variable %nextEvent a cualquiera "Su primera cita es hoy %Calendar31 a las %Ceventdate22" o "No tiene citas programadas para hoy", dependiendo del valor de %Samedayevent, lo que puede ser "Yes" o "no" . Todo esto es un poco redundante, ya que podíamos haber puesto las acciones 8-9 aquí para que lo hicieran directamente, pero de nuevo la culpa es de las prisas con que se hizo la tarea. Acción 16: La acción final que culmina las 15 anteriores. Simplemente nos Dice el valor de nextEvent%, que se establece en las dos acciones anteriores. El resultado es que tiene un mensaje para un día sin citas, y por supuesto, para los otros días dice el mensaje dinámico con el título del evento y el momento. Esta tarea es larga y complicada, debido al uso de diferentes mensajes para diferentes situaciones (evento / ningún caso). Sin esta característica, habría sido un asunto de dividir el título del evento, el cual es bastante simple (acciones 10-12, básicamente). A menudo los pequeños detalles son los que llevan tiempo, como este ejemplo demuestra, y a veces eso es una molestia adicional que no vale la pena para algunas personas. En conclusión Ser capaz de procesar datos variables en Tasker abre un montón de posibilidades, pero también hay que trabajar mucho en el seguimiento de las variables cuando se está dividiendo a diestra y siniestra. Hay que mantener la cabeza fría, tener abierto el código del texto como referencia, y usar la depuración mediante una acción de Flash (ver ejemplo 2) son cosas esenciales para alcanzar el objetivo sin volverse loco en el proceso. En la siguiente parte de la guía voy a cubrir algunos consejos y trucos en la utilización de Tasker, cosas que en realidad no se parecen naturales, y que no fueron incluidos en ninguna de las partes anteriores, pero que merecen ser mencionados. Más adelante en la serie que voy a hacer otras partes dedicadas a ejemplos de todo tipo, así que si tiene un perfil o una tarea que no es capaz de resolver, hágamelo saber y quizá podría convertirlo en ejemplo de otro artículo, al igual que ocurrió con el ejemplo 2 de este artículo.

Tasker para principiantes. Lección 5: Trucos y consejos. Algunos “trucos” y maneras de hacer cosas en Tasker que pueden ser de mucha utilidad, y que no están descritas en otras partes de la guía. Las cuatro anteriores partes de esta guía (http://www.htcmania.com/showthread.php?p=8821039) han sido exhaustivas, pero así es Tasker. A veces las cosas no son tan simples como parecen, y otras veces las cosas son más sencillas de lo que parecen. Esta parte se dedica a varios consejos y trucos para utilizar Tasker, cosas que no son tan obvias. He tratado de recopilar todos aquellos de los que me he acordado, pero si se me ocurren más puede haber una segunda serie de consejos y trucos en el futuro. Tiempo en segundos

Operar con el tiempo puede ser molesto, porque las horas y los minutos no se llevan bien con las operaciones matemáticas. Eso crea un problema cuando hay acciones que requieren saber cuando ocurre algo en términos de tiempo desde o hasta ahora, o entre dos momentos en el tiempo. Ejemplos de ello son la acción Insertar-encalendario, que requiere que se ingrese la fecha y la hora en cuestión de minutos a partir de ahora, o mi perfil de modo “durmiendo”, que me dice el tiempo que he dormido. La solución es usar la menor medida del tiempo que utilizamos normalmente: segundos. Referenciar todos los tiempos en segundos permite aplicar las operaciones matemáticas normales como sumar y restar para calcular sin problemas los periodos de tiempo. Esto, por supuesto, requiere que todos los tiempos se conviertan a segundos. Las mediciones reales de tiempo, tales como minutos, horas, días, semanas, o meses, se pueden convertir fácilmente con la multiplicación o división. Hay 60 segundos en un minuto, por lo que 1000 segundos es (1000/60) minutos, y así sucesivamente. Pero las fechas del calendario son otra cuestión porque -en principio- no podemos convertir una fecha a segundos. Pero, afortunadamente Tasker tiene un sistema que sí lo permite, mediante el uso de su propia

cronología que se inició en enero de 1970. Así cualquier instante o fecha puede expresarse como un (gran) número de segundos transcurridos desde aquel momento inicial. A este número se puede acceder de dos maneras. La variable incorporada %TIMES contiene la fecha/hora actual en segundos, de forma similar a como %TIME y %DATE contienen la hora y fecha. También se puede utilizar la acción Convertir-Variable, de la que hablaré enseguida, para convertir las horas y fechas a este formato. Tras eso, ya se pueden aplicar las herramientas matemáticas a este sistema de tiempo. El resultado estará en segundos, que se pueden convertir en minutos, horas, días, semanas, etc, dividiendo por 60, otra vez por 60, luego dividiendo por 24, y así sucesivamente para moverse a través de los formatos. Para tomar un ejemplo concreto, he mencionado mi perfil de modo “durmiendo”. Cuando se activa, copia el contenido de %TIMES a una variable de usuario %smactivation. Cuando se desactiva, hace una simple operación(%TIMES-%smactivation)/3600, dándome %smduration. Haber dividido por 3600 es lo mismo que dividir por 60 y luego de nuevo por 60, convirtiendo los segundos en horas. De este modo, %smduration contiene el tiempo total (en horas) que el perfil estuvo activo. Tenga en cuenta que el resultado no convierte decimales en minutos, por lo que me da 8,5 horas, no 8 horas y 30 minutos. Yo podría hacer que me diera horas y minutos, pero lo entiendo bien así. Convertir-Variable

Convertir-Variable es una acción que siempre se debe tener en cuenta. Se puede convertir el contenido de una variable a otro formato, siempre que el contenido de la variable sea compatible con ese tipo de conversión particular. Tienes cosas cotidianas como pies a metros, cosas más especializadas como hex a decimal, y la conversión de la que he hablado anteriormente: tiempo en segundos. Este último es quizás el sistema más importante de conversión de los que hay disponibles en Convertir-Variable, y tiene asociadas cuatro funciones de conversión diferentes. Fecha-Hora-a-Segundos es la función de conversión que se usa para convertir el tiempo a segundos. La guía-delusuario-de-Tasker, disponible a través del signo de interrogación que hay en la pantalla de configuración de Convertir-Variable, muestra una visión general de cual formato de fecha y hora es compatible con ConvertirVariable; quizás el más sencillo sea AAAAMMDD HH.MM. La fecha puede estar sola, en cuyo caso se supondrá que la hora es 00:00; en cambio no se puede convertir una hora sola, siempre hay que especificar una fecha, aunque sea la fecha actual. A veces usted se encontrará con una fecha que está en otro formato incompatible con los requisitos de ConvertirVariable, por ejemplo, si usted obtiene de datos de un calendario en línea o similar. Aquí es donde entran en juego sus habilidades usando Separar-variable, también Sección-de-variable y en algunos casos las matemáticas.

A modo de ejemplo, digamos que usted tiene una %fecha en el formato DDMMAAAA y necesita cambiarla al formato AAAAMMDD. Una forma muy simple de hacerlo sería: 1. Sección-de-variable Nombre: %fecha Desde 1, Longitud 2 Almacenar Resultado en %dd 2. Sección-de-variable Nombre: %fecha Desde 3, Longitud 2 Almacenar el resultado en %mm 3. Sección-de-variable Nombre: %fecha Desde 5, Longitud 4 Almacenar el resultado en %aaaa 4. Establecer-variable %Nuevafecha a %aaaa%mm%dd Tras eso, la variable %Nuevafecha puede ser utilizada en Convertir-Variable. Tenga en cuenta que algunos de los formatos aceptados de Convertir-Variable dependen de la configuración del formato de fecha en la configuración del sistema. Es importante recordar que usted tiene las herramientas para hacer prácticamente cualquier cosa con el valor de una variable, por lo que no hay nada imposible. Sin embargo, es también importante comprobar que el contenido de las variables de entrada es compatible con el tipo de conversión que se va a usar. Conversión del tiempo en segundos a fecha y hora Las otras tres funciones de hora/fecha se encargan de hacer la conversión a un formato legible por humanos. La única diferencia entre ellos es la cantidad de información que contiene la variable resultante. La imagen siguiente muestra las diferencias entre el formato breve y los formatos de presentación mediana y larga.

Un uso muy típico de esto sería devolver una fecha legible después de haber hecho algunos cálculos con el tiempo en segundos. Usted podría, por ejemplo, hacer una tarea en la que se introduce un número de días a partir de

hoy, y luego devuelve la fecha que corresponda. Sería tan sencillo como sumar X * 24 * 60 * 60 (donde X es el número de días, y los cálculos de convertir eso en segundos) a la variable %TIMES, y pasar la variable resultante por el proceso de Convertir-Variable. Variable-aleatoria

En Tasker, la acción Variable-aleatoria es el alfa y omega para la fabricación de cualquier cosa al azar, pero no es la acción más intuitiva que hay. En cuanto a su configuración, podrás ver algunas opciones bastante simples para Nombre, Min y Max. En pocas palabras, da a la variable de Nombre un valor entre Min y Max. Suena bastante simple, pero ¿cómo diablos se utiliza para, por ejemplo, leer un archivo al azar, o una línea al azar en un archivo de texto? Bueno, la clave es obtener un número al azar, y luego usar ese número en otros lugares. En otras acciones de Tasker hay muchos ajustes que permiten utilizar variables para el ajuste, en lugar de un valor estático, y la clave es usar estas dos funciones juntas. Por ejemplo, la acción Leer-línea permite leer una línea de un archivo de texto. El número de la línea a leer se especifica en el ajuste Línea de esa acción. Obteniendo primero una variable aleatoria y, a continuación, utilizando la variable creada en el campo Línea, usted obtiene la lectura de una línea al azar! Esto se puede utilizar en muchos lugares, por ejemplo en la selección de archivos diferentes si se ha puesto a esos archivos nombres con números. Pero todavía hay más. En la acción Variable-aleatoria , los campos Min y Max también pueden ser sustituidos por variables, lo que significa que usted puede controlar a distancia el rango del valor que será elegido al azar. Un ejemplo práctico se puede encontrar en mi propuesta de cena aleatoria (http://www.pocketables.com/2012/07/a...g-message.html), donde la tarea se ve así: 1. Leer-archivo: Archivo: dinner.txt A la variable: %dinnertext 2.Separar-variable: Nombre: %dinnertext Separador: | 3. Establecer-variable: Nombre: %dinnerrandom A: %dinnertext(#)

4. Variable-aleatoria: Nombre: %dinnerno Min: 1 Max: %dinnerrandom 5. Establecer-variable: Nombre: %Dinnersuggestion A: %dinnertext(%dinnerno) La tarea comienza por la lectura del contenido de un archivo de texto, y dividiéndolo por el carácter |. Este carácter | ha sido añadido intencionalmente al final de cada línea en el archivo de texto con el propósito específico de actuar como un divisor. Dividiendo así, nos da una variable para cada línea que hay en el archivo de texto. La acción 3 establece %dinnerrandom a %dinnertext(#). Mediante la adición de (#) al final de una variable de base (también conocida como matriz) con varios hijos (%dinnertext1, %dinnertext2, etc), en realidad obtenemos el número de variables hijo que hay para esa matriz. Si el archivo de texto contiene 5 líneas, se obtienen variables %dinnertext1-5, y %dinnertext(#) será 5. Esta es una manera rápida y tosca de contar el número de líneas que hay en el archivo, contando cuántas variables se crean al dividir. La acción 4 crea una variable aleatoria con rango desde 1 hasta %dinnerrandom. En otras palabras, un rango igual al número de líneas en el archivo de texto original. Esto nos genera un número al azar con garantías de que estará dentro del rango adecuado para el archivo de texto, incluso si el archivo de texto se ha modificado externamente, ya que el rango se determina leyendo primero el archivo de texto! La acción 5 utiliza este número generado de forma aleatoria para recoger la variable secundaria correspondiente, y transferir el resultado a una variable global. Esta variable puede ser utilizada en una acción Decir,Notificación, etc. Al hacerlo de esta manera, la tarea es completamente independiente de los cambios en el archivo de texto. No es necesario actualizar la tarea por cada vez que se actualiza el archivo de texto, ya que la tarea contará el número de entradas en sí, y escogerá un número al azar de ese rango. Esto le ahorra tener que cambiar el campo Max en Variable-aleatoria cada vez que cambia el número de líneas en el archivo de texto. Haciendo Matemáticas

Tanto las condiciones Si(If) como la manipulación de variables permiten aplicar las matemáticas a cualquier situación. He mencionado algunos usos anteriormente, con la conversión de las diferentes medidas de tiempo. La buena noticia es que el enfoque es bastante simple: utilizar variables de Tasker con valores numéricos en lugar de los números reales (como se utilizan las incógnitas en matemáticas), y luego utilice las reglas normales matemáticas. La mala noticia es que usted todavía necesita saber matemáticas para ser capaz de hacer esto, y en muchos casos esto puede ser un desafío más grande que cualquier otra cosa en Tasker. Si usted no sabe cuándo poner algo entre paréntesis en matemáticas, Tasker no va a entender lo que está tratando de hacer. En algunos casos las matemáticas también se puede utilizar como un sustituto para reemplazar acciones Separarvariable / Sección-de-variable, pero hay que tener cuidado al hacerlo. Si usted tiene un tiempo en el formato HHMM, como 1435, en realidad se puede hacer esto compatible con Convertir-Variable dividiendo por 100. Esto le da 14.35, que es un número decimal desde una perspectiva matemática, pero también puede ser interpretado como horas y minutos con un punto separador, y así es compatible con Convertir-Variable. La razón por la que hay que tener cuidado es que hacer lo mismo con un cero al principio o al final, como 0930, dará lugar a 9.3, ya que no almacena los ceros innecesarios tras hacer matemáticas. Convertir-Variable no va a entender lo que significa 9.3 en términos de tiempo. Puedes tratar de resolver el problema a utilizando condicionesSi(If) que chequan la longitud de la variable y añaden ceros, pero fácilmente tendrás que añadir decenas de acciones para cubrir todas las posibilidades. Contando las cosas

Algo tan simple como contar tiene muchos usos en Tasker. Por ejemplo, puede contar los SMS entrantes, mensajes de correo electrónico, el número de horas que ha estado trabajando, durmiendo, o conducido en su coche. Puede utilizar esta información en Notificaciones, en acciones Decir, en widgets, o para controlar contextos disparadores. La acción Sumar-a-variable es una herramienta muy útil en estos casos. Se añade un valor numérico a una variable especificada cada vez que se ejecuta la acción, esencialmente haciendo que la variable se convierta en un contador. Si esto se vincula a un contexto de eventos, como Texto-recibido, usted tiene un sistema que incrementará la variable cada vez que algo sucede. Al hacer esto, es importante recordar cuándo y cómo reinicializar la variable. Nunca confunda un contador de Tasker con un contador interno de aplicación, ya que no tiene que ser lo mismo. Por ejemplo, puedo añadir un perfil que cuenta cuántos SMS he recibido, mediante la adición de 1 a una variable cada vez que recibo un SMS. Entonces, si yo entro en la aplicación de SMS y leo todos los SMS, la aplicación de SMS reiniciará a cero el contador de mensajes pendientes de leer, pero el contador Tasker seguirá con el mismo valor que tenía. Para poner a cero el contador de Tasker, podría, por ejemplo, crear un perfil que ponga a cero la variable contador

cada vez que abro la aplicación de SMS, asumiendo que abro la aplicación para leer los mensajes. Pero si salgo de la aplicación sin haber leído todos los mensajes pendientes, el contador de Tasker estará otra vez descuadrado. Normalmente esto no es un gran problema, al menos no si se mantiene al día con la lectura de todos los mensajes. Con Tasker, un contador de este tipo no es tan preciso como el contador interno de una aplicación, pero por otro lado, puede contar con casi todo lo que sucede en su teléfono. También se pueden combinar diferentes contadores, como la combinación de las llamadas perdidas, SMS y correos electrónicos en un único contador de eventos nuevos. Prueba La acción de Prueba está semi-escondida en la categoría Misc. La palabra Prueba se refiere aquí a probar el valor de algo, como una variable, datos estáticos, o un archivo. Se puede elegir entre una larga lista de tipos de prueba, que van desde la longitud de una variable a la fecha de modificación de un archivo. Yo no tengo mucho trato con esta acción, y cuando lo hago, lo que utilizo normalmente es el tipo de Prueba de Longitud-de-variable (*). Esto cuenta el número de caracteres en una variable, que puede tener usos enSección-de-variable. Esta acción de Prueba es una de esas acciones que usted debe conocer y estar familiarizado con lo que puede buscar allí si alguna vez necesitas una de sus herramientas, del mismo modo que con la acción Convertir-Variable. (*) Nota del traductor: En realidad, los tipos de prueba están en inglés, incluso en el Tasker en español. Por tanto, lo correcto sería decir que el tipo es Variable Length. No tenga miedo de usar múltiples tareas y perfiles para lograr algo

Una cosa que me ha sorprendido observando las solicitudes de ayuda para Tasker es como muchas personas sienten la necesidad de meter la máxima funcionalidad en el menor número posible de tareas y perfiles. Parece un deseo de mantener Tasker organizado y funcionando sin problemas, pero a menudo esto perjudica la funcionalidad real. Usaré mi perfil de modo “durmiendo” como ejemplo una vez más. El 98% de las veces es activado por la conexión del cargador, que Tasker puede leer mediante un contexto de estado de energía. Pero en realidad el perfil no está directamente vinculado a ese contexto. Está vinculado a un contexto de variable, %Sleepmode, que a su vez se

establece por un perfil independiente que sí está vinculado al contexto del estado de alimentación. Esto significa que enchufar la carga hace que se active un perfil que establece una variable, que a su vez activa otro perfil. Así que, ¿por qué utilizar el doble de perfiles de los que son necesarios aparentemente? La respuesta es simple: Para que el perfil principal sea controlable con diferentes métodos. Mi asistente de voz basado en Tasker, Nelly, también tiene la posibilidad de configurar %Sleepmode, por medio de una entrada de voz que contenga "buenas noches" o "buenos días." Si el perfil principal hubiera sido directamente vinculado a la carga eléctrica, yo no habría sido capaz controlarlo también utilizando Nelly. Ya he mencionado antes las ventajas de convertir variables en contextos, y esto es un claro ejemplo de ello. También debo recordar a todos que la adición de múltiples contextos a un perfil hace que la relación entre ellos sea Y, no O. Todos los contextos se han de cumplir, no basta con que se cumpla uno u otro. No hay manera de hacer esta relación O, ya que francamente no hay razón para hacerlo, por lo siguiente. Los perfiles están vinculados a contextos y a tareas, pero la misma tarea puede ser utilizada en varios perfiles. Por lo tanto, puede tener dos perfiles distintos, cada uno con diferentes contextos, vinculados a la misma tarea, y aún así sólo tiene que editar una tarea. Puede parecer que esto pone un poco de desorden en su Tasker, pero en la práctica no hay diferencia. Pero no hay que confundir la falta de una relación O entre los diferentes contextos con las distintas posibilidades de configuración dentro del mismo contexto. Por ejemplo, puede haber un único contexto de conexión WiFi que reaccione a varias redes diferentes mediante el uso de una barra en los campos de configuración, como el SSID. Si quieres un perfil que esté activo cuando está conectado a una red WiFi llamada Casa y también cuando está conectado a una red WiFi llamada Trabajo, puedes poner en el campo SSID Casa/Trabajo. Las tareas también se puede dividir en partes, utilizando la acción de Realizar-tarea para ejecutar otras tareas como partes de una tarea. Este cambio no sólo ayuda a mantener las cosas organizadas sino que permite compartir grupos de acciones entre las tareas. Un ejemplo es mi tarea de actualización de widget. Contiene acciones que en conjunto obtienen la información necesaria y la utilizan para actualizar mi widget Make Your Clock Widget. La actualización del widget es algo que tengo que hacer en situaciones distintas, incluso cuando el dispositivo se inicia, y también cuando cambia alguno de los valores utilizados en el widget. En lugar de insertar el mismo conjunto de acciones en las diferentes tareas independientes, solo inserto una acción que sirve para llamar a otra tarea que contiene el grupo de acciones comunes. Esto ahorra tiempo tanto en la configuración inicial como cuando se necesitan modificar las acciones. Hablando de acciones de edición, tengo en mi Tasker varias acciones individuales bastante complicadas. Por complicado, quiero decir que su configuración implica rellenar muchos campos, a menudo con una gran cantidad de información, y tal vez incluso una condición Si(If) que añade aún más información. Si usted necesita la misma acción en varios lugares por supuesto puede copiar y pegar, pero también se podría considerar la posibilidad de poner esa acción en su propia tarea separada, y luego usar Realizar-tarea para referirse a ella. De esta manera, usted sólo tiene que editar las acciones complicadas en un solo lugar y los cambios se aplican a todos las tareas que correspondan. Diablos, ni siquiera tiene que ser una acción complicada: si es algo que se utiliza en bastantes lugares, hacer los cambios se vuelve tedioso, salvo que se pueda editar en un solo lugar. Eventos sucesivos de calendario que se superponen en Tasker Existe la capacidad de tener perfiles activos mientras duran los eventos del de calendario, pero hay un peligro con este sistema. Si usted tiene dos eventos del calendario sucesivos, digamos uno de 9.00 a 10.00 y otro de 10.00 a 11.00, se podría suponer que el primero se desactiva al mismo tiempo que se activa el segundo. En la práctica eso no ocurre así. Un evento de calendario que dura hasta las 10.00, en Tasker se mantiene hasta que el tiempo

supera las 10.00, y eso ocurre a las 10.01.00. Por lo tanto, desde las 10.00.00 a las 10.00.59 ambos eventos estarán activos y eso puede provocar colisiones. Para evitar esto, los acontecimientos contiguos tienen que ser configurados de forma que el primer evento termine un minuto antes de que el otro comience, en este caso 9,59. Así, el primer evento dejará de ser activo en 9.59.59, y el segundo evento se activará a las 10.00.00. Contextos de notificación

Hay un puñado de aplicaciones que se integran con Tasker, pero todavía queda una gran cantidad de aplicaciones y servicios a los que Tasker no tiene acceso directo. El contexto de evento Notificación a menudo puede ayudar en este tipo de situaciones, porque permite a Tasker reaccionar a las notificaciones creadas por otras aplicaciones, suponiendo que Tasker tenga accesibilidad (un ajuste en la configuración principal del sistema). Puede filtrar por qué aplicación envió la notificación y el título de la notificación, pero por desgracia, no por la descripción. El título notificación también se almacenarán en la variable incorporada %NTITLE, lo que permite utilizarlo en Tasker. La utilidad del campo de título depende de la aplicación, e incluso la versión del SO. La app de Gmail para Gingerbread crea un título de notificación diferente que la app de Gmail para ICS, y no contiene realmente la información que uno probablemente necesita (como el asunto del mensaje, que se almacena en la descripción de notificación). Esto significa que usted puede crear perfiles que actúan sobre las notificaciones de Gmail, pero olvídese de filtrar por detalles como el asunto (Sin embargo, K-9 Mail es una aplicación de correo electrónico alternativa que tiene la necesaria integración con Tasker). Como he dicho, la utilidad del título de la notificación depende de la aplicación y la versión del sistema operativo. Además, Tasker sólo es capaz de ver la notificación cuando aparece. No hay contexto de estado para las notificaciones que permanecen activas, lo cual sería útil para detectar la instalación de aplicaciones, la carga de archivos, las sincronizaciones y otros procesos que muestran notificaciones mientras están activos. Tampoco hay evento ni forma de detectar que una notificación desaparece. Es culpa de Android. A pesar de estas restricciones, el evento Notificación es genial. Yo personalmente lo uso para personalizar las notificaciones de Gmail de correo electrónico dependiendo de la localización (visuales en casa, fuertes vibraciones en la calle), y se puede imaginar usos similares con otras aplicaciones. Retrasar la activación/desactivación del perfil

A veces uno puede no querer que su perfil se active o desactive en el mismo momento en que el contexto es detectado. Un ejemplo típico sería si usted tiene un perfil de conexión Wi-Fi que no desea desactivar si se queda fuera de cobertura durante unos segundos, o quizás usted quiere que su perfil de reunión se desactive unos minutos después de que termine el plazo indicado en el evento del calendario, dándole margen para salir antes de los sonidos empiecen a molestar. El retraso de una tarea es simple con la acción Esperar, aunque en relación con los perfiles de este tipo es un poco más difícil -pero no mucho. Supongamos que desea crear un perfil que se activa cuando se conecta a una red WiFi, pero quiere hacerlo de modo que el perfil no se desactiva hasta que el dispositivo se ha desconectado durante 5 minutos sin haber vuelto a conectar en ese tiempo. Para ello, el verdadero desencadenante para el perfil debe ser otro perfil propio, ambos con sus respectivas tareas de entrada y salida. La tarea de entrada utiliza una acción Establecer-variable %Wifiactive a 1, y luego añade una acción Detener-tarea con el nombre de la tarea de salida (1). La tarea de salida primero usa la acción Esperar 5 minutos, y a continuación Establecer-variable %Wifiactive a 0. Tras eso ya puede crear su perfil original utilizanado el contexto de estado Valor-de-variable con la variable %Wifiactive igual a 1. Así resulta que su perfil original está comandado por una variable del otro perfil. Ese otro perfil contiene el contexto original pero sus tareas controlan al primer perfil. De esa manera usted puede utilizar la acción Esperarpara retrasar realmente la desactivación del perfil principal en 5 minutos. Si el dispositivo se vuelve a conectar durante esos 5 minutos, la tarea de entrada contiene una acción acción Detener-tarea que aborta la tarea de salida para evitar que se desactive el otro perfil. En conclusión Probablemente hay cientos de consejos y trucos que ayudan con el uso de Tasker, y estos son sólo los que vinieron a la mente. (1) Hemos comprobado que en Tasker versión 4+ no se puede usar la acción Detener-tarea de la forma indicada: desde la tarea de entrada no se puede detener la tarea de salida (o viceversa). Más información sobre ello en http://www.htcmania.com/showthread.php?p=12354445 .

Tasker para principiantes. Lección 6. Autoremote. Esta parte de la guía está dedicada plenamente dedicada al plug-in de Tasker, Autoremote.

Aquí os dejamos la parte de la guía que se refiere a Autoremote, un plug-in de Tasker y más...Hay que decir que este plugin desde la publicación de esta guía ha tenido una actualización bastante importante: "Novedades de esta versión: - Enviar mensajes y notificaciones a usted mismo sin utilizar internet. - Posibilidad de cambiar puerto de Linux. - Solución de error en el que todos los botones de una acción tenían la misma etiqueta. - Solución de error en los mensajes de notificaciones si se tenía establecida una contraseña. - Otras correcciones de errores." Sobre todo tener en cuenta que ahora Autoremote también integra el plugin Autonotification, con el que puedes tener notificaciones interactivas con Tasker y Jelly Beam: https://play.google.com/store/apps/d...ZmljYXRpb24iXQ.. Los últimas 5 partes (http://www.pocketables.com/tag/begin...uide-to-tasker ) han demostrado lo mucho que hay que saber sobre Tasker en sí mismo, pero eso es sólo la mitad de la historia. La amplia selección de terceros y/o plug-ins para Tasker extiende su funcionalidad en todo tipo de formas, hasta la activación de etiquetas NFC para el control de los sistemas de automatización del hogar. Una de las últimas incorporaciones entre los Tasker plug-in del mercado es también uno de los más poderosos, y se llama AutoRemote (http://www.pocketables.com/tag/autoremote ). En pocas palabras, se permite que los dispositivos Android puedan comunicarse unos con otros, y con los ordenadores. La era en la que el teléfono no sabía lo que estaba haciendo su tableta termina aquí. Nota: Esta guía está escrita basada en la versión beta del software que se publicó justo antes de esta guía (intencionalmente). Inconsistencias menores en las capturas de pantalla serán debido a esto, y hay que asegurarse de que se tiene la versión más reciente de todo el software para ver el mismo conjunto de características que las que se muestran aquí. ¿Qué es AutoRemote? Los dispositivos móviles pueden comunicarse entre sí, pero en formas que están diseñadas con el usuario en mente. SMS, correo electrónico, chat de vídeo, mensajería instantánea, etc, son todos servicios diseñados para que los maneje el usuario, no el back-end. AutoRemote por otro lado es un sistema de comunicación diseñado para los dispositivos de comunicación, sin que el usuario tenga que ser parte de ella. Permite el envío de mensajes entre los dispositivos que se han registrado como grupo,de manera instantánea y sin molestar al usuario. ¿Alguna vez su teléfono puede avisarle de la batería de la tableta de agotarse después de días de inactividad? AutoRemote da a los dos, el canal necesario para comunicar este tipo de información. Sin embargo, Autoremote, no lo hace enteramente por su cuenta. Mientras AutoRemote ha crecido más allá de su dependencia original de Tasker en algunas cosas, sigue siendo en gran medida un Tasker plug-in. Después de todo, algo tiene que gestionar los mensajes, actuar sobre ellos, y enviarlos. Tasker ya tiene la capacidad de recoger prácticamente cualquier dato, así que con AutoRemote instalado para que pueda comunicar esos datos a otros dispositivos, usted tiene lo que necesita para crear configuraciones que hacen que los dispositivos IOS parecezcan que son de principios del siglo pasado. Primeros pasos con AutoRemote AutoRemote se puede tener de Google Play por 1´99 Euros (https://play.google.com/store/apps/d...toremote&hl=en ). (N.T: existe una versión gratuita). Una vez instalado y

abierto, vaya a buscar a su URL personal, que estará en los formatos http://goo.gl/RandomCharacters. Esta URL se utiliza tanto para el registro de su dispositivo con otros dispositivos, y para acceder a AutoRemote de acceso web. Abrir la URL en un navegador le presentará una página donde usted puede enviar mensajes a su dispositivo, así como instrucciones para acceder al segundo código personal de AutoRemote, la clave que se utiliza para algunas partes del sistema eco AutoRemote. De vuelta en la aplicación, se puede acceder al menú para entrar en la lista de dispositivos registrados. Aquí se puede registrar un nuevo dispositivo utilizando la dirección URL personal de ese dispositivo, y así conectar dispositivos entre sí. Vas a tener que hacer esto en ambos dispositivos para que los dos se puedan enviar mensajes entre si. Los dispositivos registrados en esta lista estarán disponibles como una opción cuando se va a enviar un mensaje. Una vez hecho esto, las características de Autoremote que son independientes de Tasker estarán listas. Trate de ir a Google Play, entrar en una página de aplicaciones, seleccione Compartir y, a continuación, abrir URL remota. Esto abrirá la misma página en el otro dispositivo, mostrando que está configurado correctamente. Contexto de Tasker AutoRemote agrega ambos, contextos y acciones para Tasker, así que vamos a empezar con el contexto. Está disponible en la categoría Tasker Estado contexto, en la sección de Plugins. Hay pocos ajustes disponibles en la pantalla de configuración, así que vamos a ir a través de todos ellos. Opciones de plug-in: Comportamiento de evento (Event Behaviour): El contexto de AutoRemote es un contexto de estado por defecto, pero como se puede imaginar, usted querrá que se comporte como un evento en muchas situaciones. Marcando esta casilla hace eso. Tenga en cuenta que Tasker sigue pensando que el contexto es un estado, sólo uno que se enciende y apaga rápidamente, así que si usa esta opción para cambiar la configuraciónes de Tasker que normalmente revierten automáticamente - como el brillo de la pantalla - es necesario desactivar "restaurar la configuración" en las opciones de perfil . Objetivo (target): Uno de los métodos para el filtrado de mensajes. Especificación de un destino en el contexto y el mensaje le permite controlar qué mensajes desencadenan el contexto sin que tenga que coincidir con el mensaje en sí. Opciones de concordancia Filtro de mensajes (Filter Message): El método principal para el filtrado de mensajes. Éste le permite especificar el texto que debe ser parte del mensaje para que pueda desencadenar el contexto. Es un sistema de coincidencia parcial, por lo que "mensaje" coincidirá con "este es un mensaje". Limpiar filtro de mensajes (Message Filter Clear): Borra el filtro de mensajes, que no es lo mismo que simplemente hacer el blanco del filtrado de mensajes, ya que en realidad crea un filtro de mensajes en blanco que hará reaccionar a todos los mensajes. Mayúsculas y minúsculas (Case insensitive): Si está marcada, el filtro de mensajes diferencia mayúsculas y minúsculas Mensaje Exacto (Exact Mensaje): Hace que el filtro de mensajes requiere una coincidencia exacta, mientras que el valor predeterminado es un sistema de coincidencia parcial como se ha mencionado anteriormente.

Usar Regex: Permite usar este sistema de coincidencia en el filtro de mensajes Variables de Tasker (Tasker Vars): Mensaje ( Message): El nombre de la variable que va a contener el mensaje que enviamos. Por defecto es % armessage Parámetros y comandos (Comm Params Prefix): Parte de un sistema que le permite enviar comandos más avanzados utilizando AutoRemote. La sintaxis básica para esto esparametros =:= comando. Para usar un ejemplo que viene en la descripción de Autoremote en el Google Play, esto se puede utilizar de esta manera:

”Puede utilizar AutoRemote con condiciones Tasker, tales como la fecha y las condiciones del tiempo. Crear una "tienda =:=" comando y combinarlo con una condición 17:00. Luego, comparta su URL AutoRemote personal con su esposa y que ella envíe cosas que necesita usted para comprar como "tienda =:= zanahorias y helado". Luego, a las 17:00 el teléfono podría decir la lista en voz alta: "¡Tienes que ir de compras! Usted necesita comprar zanahorias y helado " También puede haber múltiples parámetros en un único mensaje, separadas por un espacio antes del separador de comandos =:=. Esta configuración controla el nombre de la variable de parámetro (s), y el valor predeterminado es arpar. Este sistema será más fácil de entender con los ejemplos de más abajo. Comando (Command): Controla el nombre de la variable de comando creado al usar el sistema =:=. Ajustes principales (Main settings): Para acceder a la configuración general del AutoRemote. Tasker acción 1: Mensaje AutoRemote El contexto AutoRemote le ayuda a disparar perfiles de activación basada en mensajes entrantes, y la acción del mensaje le permite enviar mensajes. Al igual que el contexto, tiene algunas opciones también. Dispositivo ( Device): Seleccione el dispositivo para enviar el mensaje o alternativamente, un canal (ver más abajo) o el mandar el mensaje a el último remitente. Tipo de dispositivo ( Device Type): Seleccionado automáticamente en función de la configuración anterior Mensaje ( Message): El mensaje que desea enviar Canal (Channel): Los canales son grupos de conexión que varios dispositivos pueden unirse para formar parte de la misma red. Si se utiliza esta opción, una conexión de canal se realizará con el dispositivo receptor. Esto permite al dispositivo simplemente responder a un canal en lugar de tener que especificar un dispositivo. No hay que confundir esto con la opción Canal en Dispositivo - éste le permite enviar un mensaje a un dispositivo específico y al mismo tiempo permitir un canal, mientras que el envío de un mensaje a un canal envía un mensaje a ese canal. La siguiente descripción de los desarrolladores AutoRemote podría ayudar a comprender mejor los canales:

”Para entender mejor lo que es un canal, imagina los canales como salas de chat. Al entrar en una sala de chat, usted comenzará a recibir todos los mensajes en esa sala de chat. Lo mismo sucede con los canales. Además, al salir de una sala de chat, usted dejar de recibir mensajes de la misma.”

Configuración avanzada Tiempo de vida (Time To Live): La cantidad de tiempo que el sistema intentará entregar el mensaje antes de abandonar Grupo de Mensajes (Message group): Permite realizar la parte del mensaje de un grupo de mensajes, básicamente, mediante la categorización del mensaje. Puedes especificar cómo manejar múltiples mensajes de un mismo grupo. Un ejemplo sería si su tablet le permite a su teléfono sabe lo que está haciendo, pero el teléfono ha estado apagado, por lo que hay varios tipo de mensajes en cola, y sólo quieres el último. Objetivo (Target): Corresponde a la opción Destino ( Target) en el contexto Contraseña (Password): Si AutoRemote se ha protegido con contraseña en la aplicación principal, en el dispositivo de recepción, es preciso especificar la contraseña aquí para ver el mensaje. Enviar mensaje (Send Message): le permite enviar el mensaje de prueba Tasker acción 2: Canales AutoRemote Las segundas opciones son para la gestión de canales. Las opciones disponibles son las siguientes: Nombre (Name): Nombre del canal para gestionar Dispositivo ( Device): Por defecto estarán todos los dispositivos de forma predeterminada. Si se especifica, los cambios se aplican sólo a un dispositivo específico. Dispositivo elegido Borrar ( Clean cosen device): Borra la configuración anterior Incluir-Quitar (Entero or exit): Hace que el dispositivo especificado entre o salga del canal especificado Salga de todos (Exit all): Hace que el dispositivo especificado se excluya de todos los canales Aplicar ahora ( Apply now): Vamos a aplicar la configuración de inmediato en lugar de tener que esperar a que se ejecute la acción.

AutoRemote para Windows

Hay programas disponibles para equipos con Windows que amplían la red AutoRemote en los mismos. http://dl.dropbox.com/u/9787157/auto...lkthrough.html Por otro lado, el programa es muy similar a AutoRemote en Android. Puede agregar dispositivos, enviar mensajes y recibir mensajes. Las URLs se pueden abrir en un navegador cuando se reciben, y encima de eso, usted puede crear reglas para los mensajes entrantes, de forma similar a los perfiles de Tasker. Esto le permite ejecutar comandos al recibir ciertos mensajes, por ejemplo mediante la vinculación a programas como nircmd.exe (http://www.nirsoft.net/utils/nircmd.html ) usarlo para apagar el PC por la noche (que es lo que hago). AutoRemote EventGhost plug-in El programa Windows también tiene una ficha que le permite instalar y gestionar un plugin EventGhost (http://www.eventghost.org/ ) . EventGhost se puede describir mejor como Tasker para Windows, un programa que automatiza el ordenador casi de la misma manera que lo hace Tasker su dispositivo Android. El modo de funcionamiento es similar, pero todavía es lo suficientemente diferente para que básicamente tengas que aprender toda una nueva aplicación como Tasker para poder usarlo correctamente. Hay un ejemplo más abajo que muestra una configuración muy básica con EventGhost, pero no puedo empezar a explicar EventGhost en detalle aquí - especialmente ya que no he utilizado el programa mucho yo mismo. Con el plugin instalado EventGhost, habrá un par de nuevas acciones disponibles en EventGhost. Uno es para el registro de EventGhost, lo que básicamente significa que la acción le permite a su red AutoRemote saber que está ahí. Debe ejecutarse en el arranque EventGhost, a continuación, hará EventGhost un dispositivo disponible en su dispositivo Android. La otra acción es para enviar un mensaje. Las opciones disponibles son idénticas a los otros lugares en que usted puede enviar mensajes AutoRemote, así que no voy a entrar en detalles. Tenga en cuenta que EventGhost tiene que estar registrado en el dispositivo al que desea enviar los mensajes. Para disparar en realidad una macro EventGhost (similar al perfil de Tasker), es necesario el evento que cree un mensaje. La forma más sencilla de conseguir esto es crear el mensaje que desea enviar desde su dispositivo, configúrelo para enviar a EventGhost, y luego envielo. Esto hará que el evento aparezca en el registro de EventGhost, lo que le permitira arrastrarlo en una macro. Como he dicho, EventGhost es bastante diferente de Tasker como parecer un marciano a los nuevos usuarios, y no voy a convertir esto en una guía EventGhost.

AutoRemote Chrome extensión

AutoRemote también tiene una extensión de Google Chrome disponible. Es relativamente nuevo, pero de la beta se hizo un cameo en el vídeo con el ejemplo 2 en la parte 4 de este manual, en el que abro un URL en el teléfono haciendo clic derecho en mi navegador PC. La extensión añade una opción para enviar mensajes de texto a uno de sus dispositivos al hacer clic derecho en Chrome, que se puede utilizar para enviar URLs o partes enteras de una página web. Ejemplo 1: Un dispositivo dejando que otro sepa lo que está haciendo Cuando hablé de cómo Android ha arruinado iOS para mí, he mencionado que estoy esperando que mi teléfono sepa que estoy en mi iPad, y a su vez dejar que el ipad me notifique los mensajes de correo electrónico en lugar de hacerlo mi teléfono. Era una referencia a una posibilidad muy real en Android, que utiliza Tasker y AutoRemote. Así es como que iba a funcionar. Opción 1: Cuando la tableta se encuentra en uso en absoluto Crear un nuevo perfil de Tasker en la tableta. Como contexto, use la opción: Estado/ Pantalla/ Estado de la Pantalla. Configúrelo para cuando la pantalla esté encendida. Esto hace que el perfil se active cuando la pantalla de la tableta está encendida. Como tarea de entrada, agregue una acción AutoRemote/mensaje. Configúrelo para enviar el mensaje "tabletstatus activo =:=" al teléfono. A continuación, agregue una tarea salida, y configurar un mensaje similar a "tabletstatus inactivo =:=." En el otro dispositivo, cree un nuevo perfil. Seleccione AutoRemote, habilita el comportamiento de eventos y filtro de mensajes se ajusta a "tabletstatus." En la tarea, agregue una acción de establecer variable: %Tabletstatus a %arpar2. Ahora tendrá una variable global que podrá estar "activo" o "inactivo", basada en el estado de la tableta. Ahora puede hacer lo que quiera con eso. Si tiene un perfil de notificación por correo electrónico, por ejemplo, puede agregar una variable % Tabletstatus que si coincide con inactivo haga que no se active si está usando la tableta. También puedes añadir una acción de Decir al perfil AutoRemote activado, u hacer que éste diga por ejemplo "La Tablet esta ahora arpar2", lo que le daría un mensaje de voz para cuando el tablet está en uso. Este último ejemplo se muestra en el siguiente vídeo (puede que no sea obvio que es el teléfono el que habla, pero lo es). VIDEO YOUTUBE: http://www.youtube.com/watch?feature...&v=v8YkWrUVm88 Entonces, ¿qué está pasando con todos los =:= % arpar2 y todo eso? Bueno, queremos enviar un mensaje de la tableta que es único, al escenario de pantalla de activación / desactivación, y queremos que contenga información sobre el estado de la tableta. Mediante el uso de los mensajes en el formato "tabletstatus activa( o inactiva) =:=," estamos activando el sistema de comandos de AutoRemote, que pone los parámetros antes de la =:= y después los comandos. No necesitamos comandos aquí, pero necesitamos dos parámetros. El primero

(tabletstatus) es estático, y simplemente nos permite filtrar este mensaje en particular para su uso en el contexto en el teléfono. El segundo parámetro es "activo / inactivo", basada en el estado de la tableta. Al habilitar el sistema de comandos con =:=, AutoRemote divide el mensaje en (esto por defecto): %arpar y las variables %arcomm. %arpar2 es el segundo parámetro, que está aquí "activo / inactivo". A continuación, puede transferir este "ajuste" a una variable global en el teléfono y utilizarlo en otras partes de Tasker, o simplemente podemos usar la variable local %arpar2 en el mismo perfil (que es el caso con el ejemplo Decir). Cuando la tableta se enciende, el contexto de pantalla encendida se activa, ejecuta las tareas de entrar, y entonces envía un mensaje al teléfono de que la tableta está activa. Cuando la pantalla se apaga, el perfil se desactiva, y las tareas de salida envían un mensaje diciendo que está inactivo. En realidad, es un perfil muy simple, pero en la práctica, se da a un dispositivo la capacidad de actuar sobre el estado de la otra. Tenga en cuenta que este perfil puede convertirse en una molestia si se va constantemente cuando te encuentres, por ejemplo, tratando de saber el tiempo (n.t: el clima) en su tablet. La parte 5 de esta guía cubre cómo configurar y tratar los retrasos en un perfil correctamente, un sistema que probablemente debería ser implementado en una configuración como esta. Opción 2: Cuando una aplicación o función específica está siendo utilizado Hacer que el teléfono esté al tanto de cuando la tableta está en uso es grande, pero…¿Y si sólo queremos que sea consciente de cuándo las aplicaciones específicas o características están en uso? El concepto es prácticamente el mismo que el anterior, en función de qué es exactamente lo que usted quisiera que se tenga en cuenta. Si usted quiere que su teléfono sepa cuando la tableta está conectada a una red Wi-Fi específica, o cúando los auriculares están enchufados, o cosas como esas, lo único que necesita hacer es cambiar el contexto estado/pantalla de la tableta por cualquier contexto que funcione. Si usted quiere que sea consciente de cuándo una aplicación específica se utiliza, sin embargo, es un poco más complicado - pero no mucho. Tasker ha construido en un variable para la etiqueta de ventana que esta siendo utilizada, que es el nombre de la ventana (es decir, aplicación) que se está visualizando. Esta variable es WIN%, y se actualiza tan pronto como la ventana cambia de nombre. Si usted hace un perfil con el contextol de evento/establecer Variable, siendo la variable a monitorear %WIN y lo vinculan a una tarea que tenga como acción Flash : %WIN, puedes mover por tu dispositivo y ver el nombre de la ventana que se muestra como un mensaje flash mientras se mueve entre aplicaciones, dando una idea de cómo funciona esto y qué nombres se utilizan para aplicaciones. Normalmente es bastante sencillo, como el nombre de la ventana es el nombre Netflix o la ventana de Gmail es Gmail. Lo esencial es que hay una variable que básicamente te dice lo que se muestra en la pantalla. Mediante el uso del contexto de evento/establecer variable, en lugar del contexto en el estado de visualización de la configuración anterior, y cambiando el "activa" por %WIN "en la tarea de introducir y eliminando tarea de salida del perfil (ya que se convierte en un perfil de eventos), usted puede hacer que el tablet envie el nombre de la ventana activa al teléfono. La variable %arpar2 , será entonces la ventana activa en ese momento, y esta variable se puede utilizar como un disparador para varias cosas. Un ejemplo sería establecer el teléfono en silencio si usted está utilizando una aplicación de libro electrónico sobre la tableta. Tenga en cuenta que este método particular enviará todos y cada uno de los cambios de pantalla al teléfono. Es una buena idea filtrar esto de alguna manera antes de enviar el mensaje, para evitar que el sistema se llene de correo basura. Si usted necesita el teléfono para saber cuando la tableta está usando Netflix, usted puede configurarlo para enviar el mensaje sólo si coincide %WIN con Netflix, en lugar de filtrarla en el teléfono cuando ya haya llegado. Ejemplo 2: notificación de Gmail que se abre Gmail en el PC

Ejemplo 4 en la parte 3 de esta guía (http://www.pocketables.com/2012/09/b...-3-scenes.html ) muestra cómo funciona mi sistema de notificación de Gmail. Si se cumplen ciertos contextos (como estar en casa), muestra un logo de Gmail en la pantalla cuando un correo electrónico entra en juego Esto puede clikarse para abrir la aplicación Gmail en el teléfono. Desde que publiqué esa parte aunque he añadido una característica toque largo al logotipo, un mensaje de AutoRemote a mi PC para gmail.com.(N.T: ¿?) La tarea es casi idéntica a la tarea “tap” ( N.T:¿?) para abrir la aplicación de Gmail del teléfono (véase el ejemplo original para eso), esto sólo envía un mensaje de AutoRemote en su lugar. Ese mensaje se abre automáticamente en el navegador en el PC, lo que significa que simplemente manteniendo pulsado el logotipo de Gmail, cuando aparezca, abre Gmail en el PC. Este es un sistema muy simple, pero que yo uso mucho. Cuando vienen mensajes de correo electrónico mientras estoy en casa, puede verlos en mi teléfono o mi PC, todo a fondo y desde la propia notificación. Ejemplo 3: Reenviar notificaciones a un PC cuando está encendido. Este ejemplo se basa en una configuración que el propio desarrollador de AutoRemote utiliza. Utiliza AutoRemote y EventGhost para crear un sistema en el que las notificaciones se envían al ordenador cuando está encendido. En primer lugar tienes que ir a EventGhost. Seleccione Configuración, Agregar Plugin, y encontraras AutoRemote en Otros. Configurelo con un nombre y añada un dispositivo a la lista de dispositivos. Ahora haga clic derecho en el árbol Autostart en la lista y seleccione Agregar acción. Encuentre la acción EventGhost Registro bajo AutoRemote. Seleccione el dispositivo que ha añadido, y escriba "notificación", como el canal. Haga clic en Aceptar y asegúrese de que está anidada en Autostart.

A continuación, agregue una macro. Déle un nombre. Haga clic derecho en la macro, seleccione Agregar evento, e ingrese "AutoRemote.Message.osd" en el campo. Por último, haga clic derecho en él de nuevo, seleccione Añadir acción y, a continuación, Mostrar OSD bajo EventGhost. Escriba "Mensaje del teléfono: {} eg.event.payload.arcomm" en el "texto para mostrar" caja. Guarde la configuración EventGhost, a continuación, reinicie EventGhost.

Ahora ve a Tasker en su dispositivo. Crear un nuevo perfil y seleccione el contexto de evento/Notificación/UI. No agregue ningún filtro a la configuración. Como la tarea conectado, crear uno nuevo, y añada Mensaje AutoRemote como acción. Seleccione canal como dispositivo para enviar el mensaje, a continuación, introduzca "notificación" en el campo canal de más abajo. En el campo Mensaje, escriba "osd =:=%NTITLE". Guardar y salir de Tasker, entre en AutoRemote, y compruebe que está puesto para caer PCs a los que no se puede llegar a partir de canales de forma automática (que debe ser de todos modos el ajuste que este predeterminado) . Eso es todo. Cuando el equipo está encendido, el título de notificaciones en el teléfono aparecerá como un mensaje en el PC. Entonces, ¿qué está pasando aquí? La acción EventGhost Registrarse en EventGhost permite que el dispositivo sepa que está activo, y al ejecutarlo en el arranque, que se produce cuando el equipo se enciende (suponiendo EventGhost se establece en el inicio automático). Las macros son como los perfiles de EventGhost y los eventos y acciones que caen en las macros se vinculan juntos como los contextos y tareas en Tasker. En este caso, tenemos un evento para un mensaje entrante que contiene "OSD" y una acción para mostrar un menú OSD (On Screen Display) que contiene la versión EventGhost de la variable %arcomm de Tasker. Esto significa que cuando un mensaje que comienza con "OSD" se recibe, se muestra la variable de comando (el título de notificación en este caso) en la pantalla. Es fácil confundirse aquí, porque no sólo estamos utilizando Tasker. EventGhost utiliza métodos diferentes para eventos y acciones, con variables en un formato completamente diferente. Para obtener el máximo partido de lo que estos dos podrían hacer trabajando juntos, probablemente debería leer un tutorial EventGhost - que no voy a escribir, porque no sé muy bien EventGhost yo mismo. Ejemplo 4: PC permitiendo un dispositivo Android sabe lo que está haciendo Este ejemplo es similar al ejemplo 1, pero con un ordenador como el dispositivo al que se está monitorizando. Suponiendo que no se ha perdido demasiado con la configuración por defecto de EventGhost, el registro en el lado debe mostrar lo que sucede en el equipo desde el punto de vista de EventGhost. Esta es una gran característica, porque es una lista de eventos que usted puede arrastrar y soltar! Si, por ejemplo,cambia a Skype, el registro mostrará el evento "Task.Activated.Skype". Suponiendo que hiciste los pasos en el ejemplo 3 para activar el plugin y registrar EventGhost en el arranque, ahora es muy sencillo de utilizar estos eventos. Añadir una nueva macro, darle un nombre y, a continuación, arrastre y suelte el evento que usted desee desde el registro hasta la macro. Si usted desea enviar a su dispositivo un mensaje cuando usted está utilizando Skype, el "Task.Activated.Skype" y "eventos" Task.Deactivated.Skype son los que usted desea, como un ejemplo. A continuación, haga clic en la macro y seleccione añadir una acción, entonces encuentre Enviar mensaje bajo AutoRemote. Envié el mensaje que desea enviar, usted conoce la instrucción por ahora. Para mi ejemplo de Skype, simplemente hago que el mensaje sea "skypeon". Ahora, en Tasker, cree su perfil. Utilice AutoRemote como contexto y filtre el mensaje la instrucción que hizo, el mensaje "skypeon" en mi caso. Haga que la tarea realicelo que quiera hacer – lo importante de este ejemplo es la relación EventGhost / AUtoRemote, no lo que usted hace con él en Tasker. Un uso posible para esto puede ser, por ejemplo si usted juega a juegos en línea y desea que el teléfono, por ejemplo, este en silencio o establecer más fuertes las notificaciones cuando haces eso. A continuación, haría a AutoRemote establecer una variable basada en un mensaje de EventGhost, desencadenar un perfil silencioso

basado en esa variable, y restablecer la variable mediante un mensaje para cuando el programa informático se cierra. Una vez más usted puede ser que consiga un uso para el sistema de retardo de la guía anterior, con el fin de evitar que una ventana de conmutación rápida desencadene cambios de perfil. Ejemplo 4.1: Convertir el teléfono en un mando de control automático de programas informáticos específicos Esto es más un consejo que un ejemplo, pero que decidí incluir. Tanto EventGhost y NirCmd (http://www.nirsoft.net/utils/nircmd.html ) le permiten enviar pulsaciones de teclas para el sistema, y ambos pueden ser utilizados a través de AutoRemote (NirCmd directamente desde el programa AutoRemote Windows). Mediante el uso de escenas, puede crear interfaces personalizadas con botones que envían mensajes AutoRemote a su equipo, que a su vez provocan la entrada de teclado allí. Imagine tener una escena de Photoshop que tiene botones para copiar, pegar, niveles, seleccionar, y todas lo demás herramientas que necesita como botones en la escena. Al vincular esto a un sistema en el que el Pc avisa al dispositivo cuando está en funcionamiento Photoshop, puede crear un escenario en el que la puesta en marcha de Photoshop en el ordenador muestra automáticamente un panel de control para que aparezca en el teléfono. Ejemplo 5: Copiar texto al portapapeles de Chrome de un dispositivo He mencionado anteriormente la extensión de Chrome, que había instalado desde hace un tiempo. De acuerdo con la sugerencia del desarrollador de AutoRemote, lo he configurado para que pueda copiar texto de Chrome en mi computadora directamente en el portapapeles en mi teléfono. Cuando tenga la extensión Chrome instalado, registre el dispositivo, haga una nueva regla, a continuación, establezca el nombre del comando a "Copiar" y el comando a "copiar". A continuación, entrar en Tasker, y crear un nuevo perfil. Añadir el contexto AutoRemote, y el conjunto "copy =:=" como el filtro de mensajes. Seleccione Comportamiento de evento. Vincule el contexto a una nueva tarea, y seleccione del conjunto de acciónes: Miscelaneo/Copiar al portapapeles. Ponga %arcomm en el campo de texto para esta acción. Con todo esto configurado, usted debe tener una nueva opción para AutoRemote donde se puede copiar la selección o URLs abiertos en los dispositivos registrados. Ejemplo 6: Acceso remoto ToDo List EventGhost y las extensiones de Chrome son buenos, pero es importante no olvidar lo esencial de AutoRemote: acceso Web. Esta URL personal que te dan se puede introducir en un buscador para que le dé una página que le permite enviar mensajes al dispositivo desde cualquier navegador web, que es mucho más fácil que usar un software especial. Uno de los ejemplos en la página de Google Play para AutoRemote es un escenario en el que una mujer envía una lista de las compras a su marido, que luego se dirá en voz alta cuando sale del trabajo. Este escenario es realmente muy fácil de configurar. Haga un nuevo perfil en Tasker, agregue el contexto AutoRemote, y establecer el filtro de mensajes de "comprar". Agregar una tarea con una acción Decir con "Hay que ir de compras! Necesitas comprar %arcomm "como el texto, a continuación, añadir un segundo contexto para la hora que la persona deja el trabajo (la hora a la que desea que el mensaje suene) en el mismo perfil. El mensaje ahora debe sonar en ese momento, y el mensaje (lista de la compra) se puede agregar a través de la interfaz web para enviar "comprar =:= artículos de las compras aquí" para el dispositivo. Tenga en cuenta que este es un "mudo" versión de este sistema, en el que sólo el último mensaje será leído, es el

momento en base, y así sucesivamente. Mediante el uso de métodos de los artículos anteriores se puede almacenar cualquier nuevo artículo en su lista en la lista actual, se suman a la lista con mensajes nuevos, y que el inicio del sonido del mensaje se dispare, por ejemplo, dejando una red Wi-Fi en vez de un tiempo específico.

Tasker para principiantes. Lección 7. Las matrices de variables. Dedicada a las matrices, que no son verdaderas matrices, pero casi.

En la lección 5 de esta guía (http://www.htcmania.com/showthread.php?p=8821039) mencioné brevemente las matrices. En ese momento no era oportuno entrar en muchos detalles, pero ahora es el momento de explorar a fondo estas variables de Tasker. ¿Qué es una matriz? Las matrices son comunes en muchas áreas, desde las matemáticas a la programación. En Tasker, una matriz puede ser descrita como una variable de base que tiene varias variables hijas. Cuando se utiliza Separarvariable sobre la variable %Hola, obtienes un montón de variables hijo %Hola1, %Hola2, %Hola3, etc. %Hola es entonces una matriz con varios elementos, y cada elemento es una variable en sí misma. Hasta aquí nada nuevo, quizás con la excepción de la terminología, porque ya hemos estado utilizando variables hijo a lo largo de la guía. Cada elemento de una matriz es una variable, por lo que puede ser utilizado como una variable independiente, que es la forma en que hemos estado utilizando matrices anteriormente. Pero lo que hace especial a las matrices son algunas cosas que se pueden hacer únicamente con ellas, además de todo lo que se puede hacer con cualquier variable. Dado que las variables de una matriz están dispuestas en una forma que pueden ser fácilmente referenciadas, ahora tenemos un nuevo conjunto de herramientas que podemos utilizar para manipular las variables a nivel de matriz, en lugar de tratarlas como simples variables individuales. Para utilizar matrices, hay que abandonar el concepto de variables como entidades únicas. Cuando se hace referencia a una matriz, es común referirse a ella de dos formas: por su variable de base (como %Hola) o en el formato %Hola(). El primer método es usado para configurar acciones específicas en Tasker, algunas de las cuales veremos más adelante. Por otro lado, %Hola()incluye los contenidos de cada variable de la matriz, separados por

una coma. Si tenemos la variable %ingredientes = azucar.leche.harina y le aplicamos la acción Separar-variable usando el punto como separador, obtenedremos una variable matriz %ingredientesque contiene %ingredientes1 = azucar %ingredientes2 = leche %ingredientes3 = harina En este momento, usar una acción Flash para ver %ingredientes nos mostrará azucar.leche.harina, con puntos intermedios como al principio. Pero una acción Flash sobre %ingredientes()mostrará el valor de cada variable hija, separándolas con una coma, por lo que verás azúcar,leche,harina. Si se borra la variable %ingredientes y luego se repiten ambas acciones Flash, se obtendría un %ingredientes vacío en la primera, y el mismo resultado azúcar,leche,harina en la segunda. Esto se debe a que la matriz se mantiene a pesar de que se borre la variable que se usó para crear la matriz. Por el contrario, si se borran las variables de la matriz %ingredientes, la primera acción Flash no se vería afectada, mientras que la segunda solo mostraría variables vacías. Esto resulta confuso, porque %ingredientes puede hacer referencia a la variable individual %ingredientes o a los elementos de la matriz %ingredientes. Cuando manejamos matrices, éste es el error más común: hacer referencia a uno cuando te quieres referir a lo otro. Haciendo referencia a las matrices Dado que las matrices numeran listas de variables, esto permite nuevas maneras para referirse a ellas. La lista de estas opciones está disponible en la versión inglesa de la Guía de Usuario, en la sección Variable Arrays (http://tasker.dinglisch.net/userguide_summary.html), y voy a citarlas aquí: Si las cuatro variables %matriz1, %matriz2, %matriz3 y %matriz4 contienen respectivamente a, b, c, d,entonces tenemos una matriz con 4 elementos. Estas variables se pueden utilizar como cualquier otra, pero también es posible acceder a ellas de manera especial. Veamos algunos ejemplos: %matriz(#) El número de elementos de una matriz (4 en este caso). %matriz(#>) El índice del primer elemento de una matriz definida, o 0 si la matriz no está definida (1 en este caso). %matriz(#) El contenido del primer elemento de la matriz (a). %matriz( 0



Menú, Título: Eliminar elementos %Gtselectedd, ítem 1: Sí (Establecer-variable Gtcd a 1), ítem 2: No (*nada*)



Si %Gtcd coincide con 1



For Variable:%gendelete, ítems:%Gtselected(



Sumar-a-variable, nombre: %gendelete, valor: 1



Restar-de-variable, Nombre: %gendelete, Valor: %shuffle, si %shuffle no coincide con *shuffle*



Array Pop, Variable: %Gentodo, Posición: %gendelete



Sumar-a-variable, nombre: %shuffle, valor: 1



End-For



Escribir-archivo, Archivo: gentodo.txt, Texto: %Gentodo()



End If



End If



Establecer-variable: %Gtcd a 0



Limpiar-variable: %shuffle



Establecer-variable: %Gtselectedd a 0

Como se puede ver, hay un puñado de cosas anidadas aquí. El primer Si(If) se asegura de que hay elementos seleccionados antes de intentar ejecutar acciones para eliminarlos. Te habrás dado cuenta de que hay una acción que reajusta %Gtselectedd, pero no hay acción que limpie la variable %Gtselected. Esto quiere decir que los últimos valores de la matriz %Gtselectedpersisten, porque en la tarea de borrado todo está anidado en un bucle For %Gtselectedd (que se repone cada vez); así ya no volveremos a tener una situación en la que accidentalmente se borren elementos que hubieran sido seleccionados en el pasado. Además de eso, se desactiva eficazmente la tarea asociada a la pulsación larga, si no hay nada seleccionado. La acción Menú que está como la primera acción en el grupo For no debe confundirse con el elemento de menú de escena que he mencionado muchas veces. Esta acción Menú genera un cuadro emergente con una pregunta y respuestas de tipo estándar, en este caso con Sí y No, creando un sencillo cuadro de diálogo de confirmación. Al hacer clic en Sí se establece una variable que es condición para la siguiente acción Si(If) del grupo. Esta variable también se restablece al final de la tarea, por lo que siempre es 0 a menos que haga clic en Sí para confirmar la eliminación. A continuación tenemos nuestro bucle For. Se ejecutan de forma secuencial las cuatro acciones anidadas y eso se hace para cada elemento de la matriz %Gtselected. En la configuración de la acción For , el campo de ítems requiere una lista separada por comas, y no necesariamente una matriz, por lo que la escribimos con el formato %Gtselected(). Para cada elemento de la matriz%Gtselected, el valor de dicho elemento se copiará en %gendelete, que se utiliza en las siguientes cuatro acciones, y luego continúa con el siguiente elemento, poniendo su valor en%gendelete, y así sucesivamente. En cuanto a las cuatro acciones anidadas, la primera simplemente resuelve un despiste cerebral del desarrollador. Ahora mismo, los elementos de menú comienzan en 0, mientras que los elementos de matriz empiezan en 1. Así, el valor de elemento de matriz 1 es el mismo que el elemento de menú 0. Este problema se solucionará pronto de acuerdo con el desarrollador Tasker: Se corregirá para que sea el mismo que los índices obviamente. Esto va a causar problemas en las escenas de algunas personas, pero es demasiado tonto para dejar así. Mediante la adición de 1 a %gendelete, que a su vez contiene el número del elemento de menú seleccionado, traemos ese número hasta el nivel de la matriz, de manera que elemento de menú 1 es el mismo como elemento de la matriz 1. Cuando los dos coinciden, se hace muy fácil quitar cosas de la matriz, usando la tercera acción del bucle For. Basta con utilizar Array-pop con %gendelete como posición para que Tasker saque de la matriz el elemento que ocupa esa posición. Los otros elementos superiores de la matriz son movidos hacia abajo de modo que si se elimina el

elemento tercero de una matriz que tenía cinco elementos, el número cuatro se convierte en el número tres. Espera, te has saltado una acción! Sí, en efecto. La segunda acción en el bucle For, combinada con la cuarta, corrige un problema inherente a este sistema. La primera vez que el bucle se ejecuta, los números de elementos de matriz coinciden con los números de elementos de menú, una vez que se han añadido 1 para compensar la diferencia en la posición inicial. Sin embargo, debido a que todos los elementos de la matriz son empujados hacia abajo cuando eliminamos un elemento, los números no coinciden después de la eliminación! Digamos que tenemos 10 elementos en la lista/matriz, y seleccionamos los números 3 y 5. %Select_indices entonces mostrará 3,5 (siempre en orden, no importa cuál seleccione primero). A continuación, el bucle For comienza borrando el elemento 3 de la matriz, lo que nos deja con 9 elementos, donde el anterior número 5 es ahora el número 4. Si el bucle For continuara normalmente, borraría el número 5, que era el número 6 cuando se seleccionaron los elementos. Para solucionar este problema, añadí 1 a %shuffle al final de cada bucle. %shuffle representa el número de veces que la lista se ha encogido. En el grupo de acciones, la acción segundaRestar-de-variable resta este número del número del elemento que va a eliminar, pero sólo si %shuffle tiene realmente un valor (la condición Si(If) se encarga de verificarlo). Si borramos 5 elementos, entonces el número del elemento quinto tendrá que ser ajustado hacia abajo 4 veces para mantener la coincidencia. Cuando se finaliza el bucle For, es el momento para escribir los cambios en el archivo. A diferencia de la primera versión de la lista de tareas, aquí se sobreescribe el archivo completo, porque tenemos toda la información en la matriz y el archivo está des-actualizado. Al escribir %Gentodo() al archivo, se escribe una lista de elementos separados por comas. La próxima vez que se abra la escena, leemos de nuevo el archivo a una variable, y luego se divide en una matriz, separando por la coma. En este punto terminamos los grupos de acciones y continuamos con tres acciones que se ejecutan siempre, aunque sólo sea para dar garantías. Esencialmente se trata de limpiar las variables%Gtcd, %shuffle, y %Gtselectedd, que quedan preparadas para la próxima vez. Parecería que no es necesario limpiar %shuffle ya que es una variable local, pero si se mantiene la escena y hay que borrar algo en varios lotes, %shuffle seguiría contando con el último valor y por eso conviene borrarla. La escena: el indicador de ítems seleccionados Hay un campo de texto en la parte inferior de la escena que muestra "%Gtselectedd ítems seleccionados". Es tan simple como eso. La escena: botón nuevo ítem

El botón para añadir un nuevo elemento no es muy complicado. La tarea es la siguiente:



Consulta-de-variable Título:Elemento nuevo, variable:%gentoadd



Si %gentoadd no coincide con *gentoadd*



Array-push, nombre:%Gentoadd, Posición 9001, Valor:%gentoadd



Escribir-archivo, Archivo:gentodo.txt, Texto:%Gentodo()



End If

Esta tarea es simple. Se inicia mediante la acción Consulta-de-variable para preguntar al usuario por el elemento a añadir. A continuación, chequea si realmente se introdujo algo en la variable. Si es así, usa Array-push para añadirlo a la matriz. Al especificar una posición muy alta (superior a 9000), queda casi garantizado que la matriz sea menor que eso, y en esos casos, simplemente se añade en la posición siguiente del último elemento que la matriz tuviera. Por lo tanto, si usted tiene una matriz de 10 elementos y agrega un nuevo elemento, se convertirá realmente en el número 11, y no en el número 9001. Después de eso, se escribe la matriz en el fichero. Un efecto secundario interesante de la utilización de matrices es que cuando el contenido del archivo se lee en la variable, una coma que hubiera dentro de alguno de los elementos recibirá el mismo tratamiento que una coma que separa los elementos de matriz original. Esto le permite agregar varios elementos de una sola vez escribiendo varios elementos separados por comas, con el formato 1,2,3,4,5. Una vez añadido, se mostrará como un elemento con varios números separados por comas, pero cuando la lista se actualiza (escena destruida, y relanzada) cada uno de los elementos separados por una coma se convertirá en un elemento independiente. El inconveniente es que no se pueden utilizar las comas dentro de un elemento de texto, pero creo que compensa por la ventaja de poder añadir varios elementos de una sola vez, en la misma escritura. La escena: el botón actualizar Alertas Lo que he mostrado hasta ahora es mi nueva lista TODO genérica, que es nueva (antes yo solía usar una app indpendiente con widget). Pero tengo otras tres otras listas específicas (casa, comprar, por la mañana) que también utilizan este sistema de matrices. El concepto básico es el mismo, sólo ligeramente diferente para acomodar tres listas en la misma escena. Las tres listas tienen diferentes alertas, por lo que tendría que asumir los necesarios cambios, pero en realidad no hace falta. Todas ellas trabajan mediante la lectura de los contenidos del archivo, la comprobación para ver si hay algo en el archivo, y luego actuar basado en eso. Los productos están separados por una coma en lugar de cambio de línea, pero eso no afecta a los sistemas de alerta. Integración con AutoRemote En todas estas listas de tareas ahora se pueden agregar elementos de forma remota, desde AutoRemote . Este sistema tuvo que ser cambiado cuando reconstruí el sistema TODO. El formato para la adición es el mismo, es decir, "Todo tag=:=nombre del elemento", sólo con la adición de una etiqueta de lista genérica/universal. Al recibir un mensaje en este formato se activa una tarea que tiene cuatro grupos de acciones idénticos a excepción de las variables y las identificaciones de archivos, que están adaptadas a cada lista. La condición Si(If) de cada

grupo es la coincidencia con la etiqueta apropiada. Para la lista universal, el grupo es el siguiente:



Si %arpar2 coincide con genérico/universal



Leer-archivo, Archivo:gentodo.txt a Var:%Gentodo (lee el archivo de mi lista genérica TODO en una variable)



Separar-variable %Gentodo, Separador:,



Array-push, nombre:%Gentoadd, Posición 9001, Valor:%arcomm



Escribir-archivo, Archivo:gentodo.txt, Texto:%Gentodo()



End If

A estas alturas ya se sabe lo que hacen todas estas acciones, porque ya han sido explicadas antes. La única diferencia es que a la matriz se añade %arcomm en lugar de %gentoadd. Como he dicho, hay cuatro grupos de este tipo en la misma tarea, una para cada uno de mis cuatro listas. Después de los cuatro grupos Si(If), al final la tarea añade una última acción que es la siguiente:



Decir "Producto añadido a la lista %arpar2"

Integración AutoRemote Chrome

Hasta ahora sólo he utilizado el plugin AutoRemote de Chrome para copiar texto desde el explorador a mi teléfono . Pensé que sería más fácil para agregar elementos a mi lista, así que he añadido unas cuantas reglas para el plugin de Chrome. Cada regla tiene un nombre que en realidad no importa, y un comando como "Compras pendientes". Esto me permite seleccionar texto en Chrome, hacer clic derecho en el ratón y enviarlo a mi tarea de listas (que he indicado antes). Es una opción muy útil, que incluso me permite ir a cualquier campo de búsqueda (como en google.com), escribir algo, seleccionarlo y enviarlo a cualquiera de mis listas.

http://www.youtube.com/watch?v=kM_YWA_tFUQ

(1) Actualización: Tasker beta 1.3.2b2 y siguientes Ha sido solucionado el problema de discrepancia numérica entre las matrices y el menú de escena, y también el problema de des-seleccionar el último elemento. Ambos se han resuelto en la última versión beta de Tasker, lo que implica que la próxima versión también incorporará esas correcciones. El cambio en la lista TODO es que ya no hay que agregar 1 a %gendelete, y la tarea de la solapa Tap en el elemento de menú de escena debe quedar así:



Si %select_indices no coincide *select*



Establecer-variable %Gtselected a %select_indices



Separar-variable %Gtselected, Separador:,



Establecer-variable %Gtselectedd a %Gtselected(#)



Else



Establecer-variable %Gtselectedd a 0



End If

En conclusión Las matrices y bucles For permiten ahorrar mucho trabajo. Hay algún problema con las matrices globales y los elementos de menú de escena, donde todo se ralentiza significativamente debido a que las variables globales tienen que estar establecidas todo el tiempo. Eso apenas importa en una pequeña lista de tareas, pero en un artículo posterior voy a mostrar cómo hacer un explorador de archivos basado en Tasker, donde sí que importa. Originalmente había hecho un navegador utilizando matrices y su funcionamiento era demasiado lento, y después de un poco de ayuda de otro usuario de Tasker, resultó que las matrices eran extremadamente ineficientes en esa situación particular. Esto podría ser un problema grave, pero ya sabemos varias formas de acelerarlo. Aun así, la iteración actual funciona muy bien, al menos para mi uso.

Beginner’s guide to Tasker, part 1.5: Tasker basics (New UI) Back in 2012, I wrote a beginner’s guide to Tasker that currently consists of 7 parts. With the UI overhaul that Tasker got a couple of months ago, however, a lot of the references, screenshots, and videos from that guide are now hard to follow, since it’s in many ways a new app. The basic concepts still apply, but it looks and is organized differently. Since this first part of the guide is many Tasker user’s first stop after getting the app, I wanted to post an updated version. This article contains the same information as the original, just based around the new UI. Since the old UI is still being used on older versions of Android, I’m leaving the original article as it is, and just adding this one on top. So, if you’re using Tasker with the new UI, read this one, and if you’re using Tasker with the old UI (i.e. on an Android version lower than 4.0), read the original version of this article. If you’re not sure which version you’re using, look at the screenshots and see which matches what you have. A part 0 has been added to the guide, talking about what Tasker is and how you can go about learning it. It’s available here. This part of the guide therefore jumps straight into talking about how Tasker itself works. Tasks, profiles, projects, contexts, scenes, variables, and actions These seven terms are important to understand in order to use Tasker. When reading through the over 100 (and counting) Tasker articles on the site, as well as the rest of the guide, these terms will be used to refer to very specific things, so common mistakes like confusing “task” and “action” can throw someone completely off. Actions An action is the most basic part of Tasker, a thing that the app does. Switching off WiFi is an action, going back to the home screen is an action, starting Angry Birds is an action, turning down the media volume is an action. Tasker have over 200 basic actions, and most of them have configuration options that make them capable of doing different things, like how the Media Controls action has five different options for which button it should emulate. Linking actions together allows you to do some truly amazing things with Tasker, things that go far beyond changing a setting or two when you leave the house. Tasks Actions are grouped in tasks. A task can have a single action, or it can have hundreds, it all depends on what that task needs to achieve. Tasks can also be triggered with actions, so that a task can have several actions that run individual tasks, each with their own actions. This way you can group actions together into more meaningful tasks, and it allows you to reference a set of actions from different tasks. For instance, you might have a set of actions that set screen brightness, volume, WiFi settings, and so on a certain way. If you need to use those settings in more than one task, you can turn them into a task of their own, and then simply run that task from within the other tasks, instead of having to copy each individual action. Tasks can be triggered either by contexts, or directly using shortcuts, widgets, and other methods, like through third party apps. Contexts and profiles A context is a trigger. An incoming notification, the opening of an app, or connecting to a certain WiFi network are all examples of contexts which can be used to trigger a task. If you want the GPS to turn on when you leave the house, you could for instance use not being connected to your home WiFi as the context, and have that trigger a task with an action that turns on GPS.

Unlike tasks, contexts can’t “live on their own.” They’re always the first part of a profile, and a profile consists of up to four contexts and one or two tasks. A profile is what links tasks and contexts together, deciding which task should run when the context triggers. There are two types of contexts, state contexts and event contexts. A state context makes a profile be active as long as the context is, so if the context is being connected to a specific WiFi network, the profile will be active for as long as the device is connected. State contexts have two types of tasks, enter tasks and exit tasks. An enter task is the default, and runs when the profile becomes active. An exit task on the other hand runs when the profile is deactivated. It’s important to understand that Tasker doesn’t enforce anything you specify in the enter task while the profile is active. By that I mean that if you change the screen brightness in your enter task, and then change it to something else using the system settings, Tasker won’t change it back until the profile has been deactivated and then reactivated. Think of it as a door that rings a bell when it opens; it will ring that bell every time it opens, but leaving the door open won’t make the bell ring continuously. Another important thing to know about state contexts is that some settings will automatically be reverted when the profile is deactivated. So if you change the brightness in your enter task, it will change it back when the profile exits, without you having to tell it that. You can disable this by long pressing on the profile name, clicking the settings button that appears on top, and then uncheck “Restore Settings”. Not all settings are automatically restored, however, and it’s mostly limited to system settings like brightness. Event contexts on the other hand is never continuously active. It makes the task attached to it run once, and then it’s done. An example of an event context is Received text, which is when you receive an SMS. Receiving an SMS is something that happens instantaneous, meaning it’s not something that becomes active and then later becomes inactive, which is what makes it an event (there’s no practical difference between when you start receicing an SMS message and you’re finished receiving it). Profiles with event contexts don’t have exit tasks, and they don’t restore settings. In cases where there are multiple contexts in a single profile, the relationship between them is AND (e.g. context 1 and context 2), meaning that both contexts have to be fulfilled in order for the profile to trigger. If a mix of event and state contexts are used, the profile will follow event profile rules. An example is a combination of a WiFi state context and a Received Text context, which when combined, creates the trigger “when I receive a text message while I’m connected to this WiFi network”. If you then specify your work WiFi network in the WiFi Connected context, you suddenly have a profile that triggers when you get SMS messages at work, but not anywhere else! To add multiple contexts to a profile, you first create your profile with a single context, then long press on that context in the profile list (tap the profile name to expand it if the context and task is not visible), and select Add. To add an exit task to a profile, or to turn an enter task into an exit task, long press on the task in the same manner. You can have multiple state contexts in a profile, but only one event context. This is logical, because since event contexts are instantaneous, it’s practically impossible that two of them happen at the exact same moment. Variables A variable is like a virtual text file within Tasker, or like a variable (X, Y, A, B) in math. A variable is represented by a % symbol followed by a name, like for instance %Variable1. Variables are used to get access to system information, transfer information between parts of Tasker, and even work as settings and options. The variable %DATE will for instance always be the current date, so if you were to tell Tasker to create a notification with the text %DATE, then %DATE would be replaced by the actual date when the notification appears. Variables are key

to advanced Tasker use, and is a huge topic to cover in itself. I go through it in other parts of this guide, starting with part 2. Scenes A scene is essentially a customized user interface. You can user Tasker’s scene functionality to create menus, popups, settings boxes, and much more. This is a very useful and complex feature that I also cover in greater detail in a later part of this guide. Projects A project is the final grouping in Tasker. Think of it as a folder capable of holding all of the above, so that you can keep everything related to a specific Tasker system in one place. The more complex Tasker setups often use multiple profiles, multiple tasks, and even multiple scenes all working together. You can group all of those together in a single project to stay organized, and projects are also vital when using Tasker’s app export capability, since they allow you to export a whole range of tasks, scenes and profiles as one single app. The Tasker screen Tasker has a beginner mode that is designed to make the app easier to use for beginners, by disabling certain features. It’s a good idea, but unfortunately you won’t find many people referencing this version of the UI when you read about Tasker online, so I recommend disabling it. You do this in Tasker’s main preferences. As such, I’ll be basing this guide on the normal Tasker look, not beginner mode. Since this article is a rewrite of a guide for the pre-ICS version of Tasker, it also goes without saying that this and any future versions of the guide based on the new UI will be based on the ICS+ design. More specifically, the theme I use is the Light theme, which is selectable in the UI section of Tasker’s preferences.

Knowing the difference between the various terms I explained above is half the battle when it comes to understanding how the UI works. The image above should help explain what everything is, but it’s worth mentioning that holding down or single tapping on parts of the UI is the way to access a lot of features. It’s the way to import and export items, add more contexts to a profile, switch out tasks, turn enter tasks into exit tasks (or vice versa), and so on. Also, to delete items, you grab the right part of the screen besides their name (where the enable/disable toggle is for profiles) and drag them down to the trash can that appears. This is also how you sort items and transfer them to other projects: drag and drop. What Tasker requires to work When Tasker is active, there will be a persistent notification icon present in your notification bar. This is to make sure the system will never close Tasker, as Tasker obviously needs to run at all times to work. You can also look at this notification in the notification drop-down to see which state profiles are currently active. To prevent a profile’s status to show here, long press its name in Tasker, go into its settings, and disable the Show in Notification Pulldown option. Some features in Tasker, specifically the ability to read notifications from other apps, require that Tasker has accessibility access. This is a system-level access that you have to manually give to Tasker by going to the device’s main system settings, accessibility section. This, along with Tasker’s long list of required permissions, might sound scary because of Google’s way of phrasing its warnings, but every permission Tasker requires is there for a very good reason, and it’s not malicious.

Tasker also requires device administrator privileges for certain features, like manipulating the status of the lock code. This also has to be enabled manually, and if you do enable it, you will have to manually disable it to uninstall Tasker. This is another system level Android thing that you can read more about here. There are dozens of plug-ins for Tasker, giving Tasker lots of new abilities. These plug-ins are available in the Play Store, and install as normal apps. Tasker shares the plug-in system with another automation app, Locale, and so many Tasker-compatible plug-ins are listed as Locale plug-ins. Furthermore, some apps have Tasker compatibility built in, meaning that installing the main app also unlocks the plug-in components in Tasker. The plug-ins can be accessed from either the third party or plug-in parts of Tasker (in the list of other actions/contexts) depending on whether the plug-in was built into Tasker or got installed on the side. If the accompanying app is installed, there’s no practical difference between actions listed in the third party section and those listed in the plug-in section, other than the name of the category they’re listed in. Being rooted is not required for Tasker, but it does give it more abilities. The availability of certain actions and contexts is dependent on the device and software version/ROM, and being rooted can unlock features that are otherwise unavailable on a certain device. Tasker can also use root to kill apps, manipulate files, and so on. The plug-in Secure Settings allows you do access a lot of otherwise blocked features via root, and is a valuable tool. Please note that Tasker taps into so many features that differences between devices and ROMs is sometimes a problem. You might read about an awesome Tasker creation online, go to replicate it, and find that some part of it isn’t working. This doesn’t mean Tasker is broken, or that you did anything wrong, it likely means that the feature you’re trying to use doesn’t work properly on your device or ROM. In those cases it’s more productive to complain to your device or ROM creator, not the Tasker dev, or the person whose creation you’re trying to copy. The truth is that you’re much better off by reading about how things can be done in Tasker, and then explore that on your own, than to try to copy someone else’s creation step by step. That’s because that will teach youwhy something works, and in the process help you understand why something doesn’t work, and maybe even how to fix it. Creating your first profile The best way to learn Tasker is to tinker with it and explore, like I just said. The configuration for each context, each action is different, and so it’s hard to generalize. The image below explains some of the buttons and options that are fairly common in the configuration screen for actions, while skipping those that are more unique to that particular task. Each action and context has different options however, and with the amount of contexts and actions in Tasker, not to mention plug-ins, explaining each and every one is impossible. The harsh truth is that if you expect there to be a 20 page user’s guide to every single option in Tasker, you’re better off just uninstalling the app right away.

There is however some documentation for more or less all the features and settings in Tasker, though often it’s just very quick explanations. I simply cannot emphasize enough how important self study is for using Tasker. This article, the more than 100 others I’ve written, and posts and articles from people around the web are great resources, but at the end of the day, you’re the person who needs to set up Tasker the way you want it. Is it worth the hassle? Oh, definitely! The video below shows the creation of a simple state profile with an enter task and (later) an exit task. My advise is to play around with the various contexts and actions and see what happens.

So where do you go from here? The banner below links to our Tasker portal page, which has a boatload of articles that you can look at. It also has links to the other parts of the beginner’s guide. So far only this first part is available in a version for the new UI though, so I advise playing around with basic features in Tasker before reading further. While there are some notable changes to the UI in the new version, Tasker hasn’t really changed, so the top priority of any new Tasker user should be to understand the basics, in order to be able to understand information written for the old UI. If you ever need to import anything into Tasker, please see this video for instructions.

Beginner’s guide to Tasker, part 2: Variables

In the first part of this guide I covered the basics of Tasker, and mentioned that I would go more into variables and scenes later on. Both are features that require a bit more explanation than the other aspects in general, so I’m going to dedicate an article to each of these topics. First out, variables. What is a variable? Variables are part of many programming languages, and Tasker is, in many ways, a programming language. Mathematics also use variables, and in many ways they work the same too. A variable is essentially a virtual text file. Imagine a text file called variable.txt that contains the text “Hello World.” Instead of it being a physical file you can move around however, it exists within Tasker; and instead of being called variable.txt, it’s called %variable. The percentage symbol is always present at the beginning of a variable name, and it’s the way that Tasker knows that something is a variable – just like the file extension .txt lets

computers know that it’s a text file. The name that follows the percentage symbol is in a way the file name. Just like a text file, a variable can contain text, but only text. This text can be a single symbol, number, a URL, a paragraph from an article – any text, in other words. When a variable is used anywhere in Tasker, Tasker will replace the variable with whatever the value (content) of the variable is when it executes whatever the variable is used in. Let’s say you have a variable %hello that contains “Hello World.” You then tell Tasker to create a notification with the text %hello. When Tasker then goes to create the notification, it will check the value of the variable, and use that instead of the variable name. As such, the final notification created by Tasker will not read “%hello.” Instead, it will read “Hello World.” Why use variables? The purpose of variables is to have a way to store information in a dynamic way. This enables you to not only transfer information between different parts of Tasker, but also to control Tasker settings and text remotely, without having to go into each context/task and manually change it. To fully understand the purpose of using variables, you first need to know about the different ways that you can change the value (contents) of a variable. Some examples include: 

Set the value of a variable using an action. This value can then be used as a context for a completely different profile, or used as part of other actions



Turn the contents of a real text file into the value of a variable



Do math using variables. For instance, you can add +1 to a variable every time an action runs. The variable value would then increase in numerical value the more times the action is run, acting as a counter



Many system settings and events exist in variable form in Tasker. The value of the variable %TIME is always the current time, %DATE is always the date, %BATT is always the battery level and so on. Full list of these so-called built-in variables are here, and knowing how to use these is one of the more important lessons of Tasker

In short, there are many ways to change the value of a variable. The whole idea is to create a library of information that different parts of Tasker can access, instead of having information stored as static text that’s only usable where it’s written. In fact, variables share a lot of advantages with the internet: 

Information can be shared easily between connected participants



Information collaboration is possible by having multiple participants work on the same information



Information can be updated in once place and still reach multiple participants without each of them having to be updated directly

With the internet, participants are internet users. With Tasker and variables, the participants are different actions, contexts, and so on within Tasker.

Variable name capitalization The capitalization of variable names actually changes – and indicates – what type of variable it is. There are three types: local, global, and built-in. To create variables of a certain type (only global and local variables can be user created), simply use the corresponding capitalization format. Furthermore, global variables are listed in Tasker’s Variables tab, however neither local nor built-in variables are. 

Local variables are all lowercase and are only available to the task/profile that creates them. If you have a task “Home” that creates a variable %home, then that variable will not be available to other tasks. Another task “Away” would hence not be able to use that variable. 

Global variables are listed in the Variables tab and will be visible and usable by all parts of Tasker. These variables have to start with a capital letter. If your “Home” task creates a variable %Home, your “Away” task will be able to see it, change it, and use it. 

Built-in variables are always all uppercase. These are the variables I talked about above which are built into Tasker and that take on the values of system information. %TIME, %DATE, and %BATT are the examples I used above. These can be read by any part of Tasker, but do not show in the variables tab. Furthermore, they cannot be changed by the user, as they by definition display a piece of system (generated) information. The only way to change %BATT is to change the actual battery level by charging or discharging the battery.

Exceptions No rules are without exceptions. There are some variables that take the form of local variables, but are actually built-in variables. An example is %new_val, which you’ll run into in scene creation. For the time being though, you can ignore these for the sake of avoiding unnecessary confusion. Variables for information sharing and dynamic text Variables can be used to share information between parts of Tasker, and even between plugins and Tasker. To use the internet simile from above, variables allow one part of Tasker to send information to another part, just like an internet user would email another. The concept of dynamic text is like document collaboration in Google Documents or other online document editors. Instead of text being a static creation, parts of it can be changed out by different independent sources.

Example 1: My morning message I have an elaborate sleep mode setup that I use every night. When I wake up in the morning, I use a Tasker action called Say (found in the Misc category), which is a text to speech function. This action has a text field into which I type the text I want it to say, and then the phone reads that message out loud. Currently, this text field reads:

” Good morning. You slept for %Smduration hours. %Lazy. Weather forecast for today is %Norweather. %Todomorningnot As you can see, this message contains 4 variables (it used to contain more). Before the Say action runs, dozens of other actions run, collect and process data, and store the final results in these four variables. 

%Smduration is the duration, in hours, that the sleep mode was active for. If it was activated at 23:00 (11 PM) and deactivated at 7:00 (7 AM), then the value of %Smduration would be 8.  %Lazy’s value depends on the value of %Smduration. If %Smduration is at least 9, %Lazy’s value is “You lazy bastard”. If %Smduration is less than 9, it’s simply nothing. 

%Norweather is the result of a task I made to collect Norwegian weather data. Its value is a very short description of the weather forecast for that day, like “sunny” or “heavy rain.”



%Todomorningnot is part of my Tasker-based todo list system. If I have todo list items marked “morning,” its value is “You have items due in your todo list.” If I don’t have any such items, its value is simply nothing.

By using these four variables, the message the phone speaks in the morning varies depending on these – and here comes the reason for the name “variable” – variables. If I get up after 8.5 hours on a rainy day where I have nothing to do, the phone will speak the following message:

“ Good morning. You slept for 8.5 hours. Weather forecast for today is rain. If I get up after 10.2 hours on a sunny day where I have items in my todo list, the phone will speak the following message:



Good morning. You slept for 10.2 hours. You lazy bastard. Weather forecast for today is sunny. You

have items due in your todo list Using variables in this way here gives me two very important abilities: 

My morning message is dynamic. Even though I never go in and manually change the Say action’s Text field, the message still changes.



I can transfer information from one part of Tasker to another. The four variables in the message are each the result of work done by other tasks and actions, and using variables allows me to transfer this information to where I need it.

Example 2: AutoRemote AutoRemote is a Tasker plug-in that I’m particularly fond of. It allows different devices to talk with one another by sending each other messages that are not visible to the user. It allows Tasker on one device to talk to Tasker on another device, without using a communication method that is meant for something else – like SMS or email. Incoming messages through AutoRemote can be used in two ways: as triggers, or as information sources. If it’s used as a trigger, you can for instance set up a Tasker profile that activates if a message that says “hello” is received through AutoRemote. This could for instance be used as a “find my tablet” feature, where sending a message with “hello” from your phone to your tablet triggers a task that makes the tablet beep. If the message is used as an information source, the actual content of the message can be transferred to a Tasker variable. Let’s say that you want your tablet to be able to tell your phone the status of the battery. Your tablet could then send the following message to your phone:

“ Tablet battery level %BATT percent Where %BATT is a built-in variable. When the tablet sends this message, it will replace %BATT with its own battery level. As such, the message that arrives on the phone will have the tablet’s battery level. The phone would then be configured to look for a message that contains “Tablet battery level.” AutoRemote has an option for whether it has to be an exact match, which in this case we wouldn’t want. This message filter would act as the context for the profile, meaning that the profile would trigger when a message containing “Tablet battery level” was received. This is similar to the “find my tablet” example above, but we want to go one step further here – actually using the content of the message as well, not just use the message itself as a trigger. To do this, you would configure AutoRemote to turn the message into a variable – let’s say %tabletbattery. That variable could then be used in a notification, Say action, or similar. Simply creating a Say action with %tabletbattery as the text, and using it in the profile that is triggered by the incoming message, would then have your phone read the tablet’s battery status out loud when it receives a message from the tablet.

Since %tabletbattery is a local variable it would only be available within that profile, but you could easily use the Set Variable action in the Variable category to create a global variable. This is done by setting the Set Variable action to create a variable with global variable capitalization, like %Tabletbattery, and setting its value (in the Set Variable configuration screen) to %tabletbattery. This would then create a global copy of the local variable. In this AutoRemote example, the value of a built-in variable on a tablet is sent to another device using a plug-in, where it’s turned into a variable which that device can use. This is just another example of information transfer using variables, but a more advanced one since it transfers information between devices.

Example 3: Minimalistic Text and Make Your Clock Widget Minimalistic Text and Make Your Clock Widget are two independent Android widget creation apps that both have the ability to receive information from Tasker. They both interact with Tasker very similarly, using an action that transfers information from Tasker (either static text or the value of a variable) into the apps’ own variables. I use both of these apps, and I use them both with Tasker. I use Minimalistic Text for my shopping list, by having a widget on my lock screen that Tasker can write information to. The widget only shows something if I’m outside and have items in my shopping list; otherwise it’s blank. The shopping list is handled by my own Tasker-based system.

The configuration screen image to the right shows how the action that bridges Tasker and Minimalistic Text is configured. It transfers the value of the Tasker variable %Todoshopping into the Minimalistic Text variable TODO, the latter of which is a variable in a completely different app and as such doesn’t use the % symbol to indicate a variable. Once this task is run, any place where the variable TODO is used in Minimalistic Text (will then show the value of %Todoshopping. Each time %Todoshopping is changed in Tasker, the bridge action has to be run in order to transfer that information to Minimalistic Text. Variables as settings Variables have another use that is perhaps less apparent, but still very important to be aware of: they can be used as settings. This is done by assigning values to variables which are then used as references later. If you have a profile for when you’re home, you can use the Set Variable action to set a variable %Home to “on” when it activates (enter task), and set it to “off” when is deactivates. Any other part of Tasker will then be able to check what value %Home has, and in turn know if you’re home. If you think about it, this is how settings work outside Tasker as well. If you go into system settings and turn off WiFi, you’re essentially setting a WiFi variable to “off” – it’s just a more visual way of doing it. If you’re connected to a WiFi network called McDonald’s, that’s like having a variable for WiFi network with a value “McDonald’s.” Referencing variables: contexts When I say that other parts of Tasker can check the value of variables and act accordingly, there are many ways it can do this. For contexts, the value of a variable is its very own context. It’s located in the State section, Variable category, Variable Value context. The screen you get when selecting this context asks for a Name, Op, and Value. Name is the variable name, like %Home. The variable name you put here is simply the name of the variable which contains the information you want the profile to be aware of and react to. Op is a bit more complicated. It means Operator, and refers to the method Tasker uses to check the value of variables, using a simplified version of regular expressions. You can set it to things like Matches, Doesn’t Match, Maths: Less Than, and so on. In short, the operator refers to the relationship between the third field, Value, and the actual value of the variable. As an example, let’s say that you want a profile that is active when %Home is set to “on,” and deactivated when %Home is set to “off.” You would then use %Home as the Name, Matches as the Op, and “on” (without the quotes) as the Value. The resulting context can then be read like this:



Activate the profile if the value of the variable %Home matches “on”

To take another example, think back to the morning message example above. The variable %Lazy there has a different value depending on whether or not %Smduration is less than or more than 9. If I want to create a profile

that reacts the same way, the Name would be %Smduration, Op would be Maths: Greater Than, and value would be 9. The resulting context can then be read like this:

“ Activate the profile if the value of %Smduration is at least 9 To finish off with a real world example, I use this system for my location profiles. I have three profiles that are mutually exclusive yet use different contexts. My Home profile is active when I’m connected to my home WiFi, my School profile is active when there’s a calendar entry in my School calendar, and my outside profile is active when the other two aren’t. To be able to make sure that all profiles are indeed mutually exclusive, I use my own variables as settings. Both the School and the Home profiles have Variable Set actions on both the enter and exit tasks. When the Home profile is active, it sets the variable Home to 1, and when it deactivates, it sets it to 0 (exit task). The School profile does the same for %School. The Outside profile then has two Variable Value contexts: %School Matches 0, and %Home Matches 0. In other words, it’s only active if both those variables are set to 0 – which in turn only happens when the other two profiles are inactive. The School profile also has two Variable Value contexts, %Home Matches 0 and %Schooloverride Matches 0. The former makes sure the school profile isn’t active when I’m at home (which could happen if we finish early,) whereas the latter variable is set by a button in a scene I have. I’ll cover scenes in the next article, but to make a long story short, I press a button that says “School override” and the school profile deactivates. This is for situations when I finish early but don’t go straight home (50 meters away), allowing me to manually trigger the Outside profile (by deactivating the school profile) for those rare occasions. Referencing variables: actions It’s not just contexts that can be controlled by variables – actions can be, too. One of the images in my first article pointed out the If checkbox on an action configuration screen. This checkbox is present for most actions, and allows you to control the action based on If conditions. An If condition is quite simply a condition that has to be fulfilled for the action to run.

For all intents and purposes, If conditions and Variable Value contexts work the same way. You have a variable name, an operator, and a value that has to be compared to the value of the variable. In the previous section, I explained how the Variable Value context works by using the configuration %Smduration Greater Than 9 as an example. That’s from my sleep mode profile, but it’s actually not used as a context in that profile: it’s used to limit an action using an If condition. The image to the right shows how this is configured. As you can see, the If checkbox is checked; %Smduration is inputted into the first field; 9 into the second; and the operator is >, which is the symbol for Greater Than. With the action configured this way, the action will only run if the value of %Smduration is greater than 9. If it isn’t, the task simply skips that action. I can use the same system to limit single actions based on the %Home variable created by my Home profile. If I want an action to run only when I’m home, all I have to do is check the If box, type %Home into the first box, select = (Matches) as the operator, and type 1 into the

second box. That way it will only run when the value of %Home is 1, which only happens when I’m actually at home. Please note that the choice to set %Home/%School to 1 or 0 instead of on or off is my own personal choice. You decide what the various states of a setting should be, and if you were to create your own Home profile with a %Home variable, there’s absolutely nothing stopping you from using a value of “crabcakes” as “on” and “hurricane” as “off.” It would simply mean that you would need to set the context/If condition to %Home Matches “crabcakes”.

It’s also possible to group multiple actions under the same If condition. To do that you use the If action found under Task, configure it like you would an integrated If condition, and then place it before the first action you want in the grouping. Any actions following that If action will then be nested under it, and follow its condition. You close the group by inserting an End If action. This is simply an easier method for applying the same If condition to multiple actions Finally, there’s an action in the same category called Else. This is an optional action you can use between an If and an End If condition to create a new group of actions (nested under the Else action) which will run if the If condition is not met, but onlyif it’s not met. The screenshot to the right demonstrates this with one of my profiles, where I’ve inserted an Else action for the sake of demonstration. The way to read this setup is as follows:

“ If the if condition is fulfilled, run action 3 (Notify Sound) and 4 (Minimalistic Text) If not (Else), run action 6 (Stop) The Else action is optional, and it really only saves you from adding a second If group that is the exact opposite of the first one. I have previously written an article on controlling profiles using variables, which you can find here. Much of it is the same as what you’ve read here, but it was written for existing Tasker users, not beginners. Special characters When doing pattern matching using this method, it’s important to be aware of the three special characters *, / and +. * is a wildcard, meaning that you can use it to match only part of a piece of text. If you input Android into the value field and use Matches as the operator, it will only match the exact use of Android. *Android* on the other hand will match any use of the word Android, like I like Android very much. *Android would match I like Android, but not I like Android very much, because the wildcard is only in front of the word, not behind it. In some cases it’s better to use *ndroid* instead of *Android* because the former will catch both Android and android. Update: Sean points out in the comments that you can use all lower case letters in pattern matching and it will work with everything. For instance, *ndroid* here is not necessary because *android* would match with both Android and android. It does however not work the other way around, so *Android* would not match both. I wasn’t aware of this, and it saves you some hassle when dealing with case sensitivity.

/ acts as OR, meaning that it lets you insert multiple values in a single field. Inputting 1/2/3 in the value field and using Matches as the operator would match variable values of both 1, 2, and 3. This is very useful since it lets you create contexts and If conditions that react to several different variable values. + means “at least one letter.” You can see the use of this in the If/Else/End If screenshot above, in the very first action, where the If action is configured as %Todoshopping Matches ++. Tasker reads this condition as “If %Todoshopping contains at least two letters, no matter which letters they are.” Empty variables Empty variables will not be replaced by blank space; instead, they will retain their full variable name if referred to. If you create a notification with %Variable as the text and that variable doesn’t contain anything, then the notification will literally say %Variable. To make it display blank space instead, create a Variable Set action for that variable and set it to a space. Use an If condition with the variable in question as the variable, Matches as the operator, and *variable-namewithout-%-symbol* as the value (see the screenshot below to see what I mean by this). Example for the variable %Home: This writes a space as the value of the variable if it’s empty, which it detects by seeing if the variable value is the variable name. Note that you should insert the space in the text field last, and immediately save without selecting anything else. Otherwise you will likely get an error message saying that the field can’t be empty.

Processing data using variables So far I’ve mostly talked about simple ways of using variables to transfer information and control actions and contexts, but that’s only half the story. For those who have read my older articles about Tasker, you’ve probably seen some articles which processed data internally in Tasker. Examples include a weather forecast announcerand calendar event announcer. What these have in common is that they process information after it has been imported into Tasker, essentially taking a single variable full of information and chopping it up into tiny pieces that can be used as settings or as dynamic text. To do this, you use many of the tools available in the Variable category in the action list. Variable Split is one of the most powerful, but you’ll also find Variable Section, Variable Search & Replace, and others. Knowing how to use these gives you the ability to get Tasker to do practically anything, since more or less any text-based information source online or offline can then be used with Tasker. Unfortunately, this is a massive topic to cover, and I’m already coming up on 4000 words from explaining the “simple” side of variables alone. As such, I want to dedicate an entire article to this topic later on in the series, after some of the more basic things are out of the way. I did however want to mention it briefly in this article as to not make people think I either forgot or that they’ve missed something.

Nelly is built on pattern matching variables To finish off this part of the guide, I can mention that my DIY Tasker-based voice assistant, Nelly, is built (more or less) entirely on the concept of variables and pattern matching. It can be a good idea to read through that (old) article after reading this part of the guide to see how it’s implemented in practice and at such a large scale.

Beginner’s guide to Tasker, part 3: Scenes What are scenes? Scenes are user interfaces that you can create in Tasker. Think of a scene as a box that contains various elements that you would normally find in an app interface, like buttons, text, text input, images, sliders, and so on. Normal Tasker actions can be tied to these elements, so that you can have a button that runs a task, a text field that lets you write text to a variable, or a slider that controls screen brightness. Scenes can be all kinds of sizes, and be displayed in different ways: As a pop-up box, full screen like an app, as an overlay over another app, and so on. The size and type of scene depends on what you need the scene to do. I will quickly go through the basics of creating a scene, and then I will go through multiple examples at the end to show how everything works in practice and for different uses. Creating a scene.

Scenes have their own tab in each project, and you add a new one by tapping the plus symbol. The first thing you see after entering a name is a screen with a box in the middle, and a magnifying glass and ok/cancel buttons on the bottom. When the magnifying glass icon is not lit up with a green dot, you’re in the screen for editing the base “canvas” for the scene. You simply drag the edges of the scene to the size you want, indicated in pixels on the bottom. Currently there’s no way to set the size in pixels directly, something that will likely change now that

scenes have a much bigger role due to Tasker’s app creation functionality. Also note that some aspects of how the scene will look are controlled by the action that triggers the scene, which I’ll cover later. Clicking the menu button will bring up a few options such as grid size and background color. The background color picker is fairly self explanatory, but I should mention that the unlabeled slider controls transparency/opacity. The grid size option controls what grid is used for editing the scene, which affects the accuracy of placing elements on the scene. If you want three buttons of the same size side by side in the scene, you will need a grid size that allows for three identically sized buttons. “Turning on” the magnifying glass makes a few new buttons pop up, and also shows the grid that you just set the size of on the scene. This is where you edit the content of the scene; add buttons, images, and so on. A few new buttons also appears on the bottom, specifically a teddy bear icon and a plus symbol. The teddy bear button lets you set the touch mode, with the three options being Normal, Move, and Resize. Normal means that you can both move and re-size elements in the scene, all depending on where on the element you touch (middle being move, edge being resize – but on small elements you often only get resize). The other two limit the editing to either moving or re-sizing an element. The plus symbol is for adding new elements to the scene, but you can also just hold down on the scene to get this option. Holding down on existing elements allows you to do things like copy, delete, hide, pin, set depth, and so on. You can duplicate an element, set one element to display underneath another, pin it so it can’t be accidentally moved, etc. Configuring elements There are 11 different elements that you can add to a scene, and they don’t all share the same options. When you add an element, a configuration screen pops up, and there are multiple tabs of settings that you need to deal with for each element. The UI tab (and background tab where applicable) is normally pretty self-explanatory for all elements, as it deals with how the element looks. Text size, name, text, color, position, icon, and label are just some examples of options you’ll run into in this tab. Note that Name refers to what Tasker uses to refer to an element internally in Tasker, while Label or Text (depending on the element type) are the fields that control what the element will actually display. Variables work fine in these fields, and I’ll show how that can be used in practice in the examples further down. The other tabs on the configuration screen vary greatly depending on element type. For the most part, each tab is essentially a task, capable of containing actions, and whose name indicates what triggers the action. For instance, adding a button to a scene brings up a configuration screen with three tabs: UI, Tap, and Long Tap. The Tap and the Long Tap tabs are each their own tasks which trigger depending on whether you tap the button or long press it. Anything you want to happen (Tasker actions) when the button is tapped goes into the Tap tab, and similarly with the Long Tap tab. Adding an Airplane Mode: Toggle action to the Tap tab will result in a button that turns Airplane Mode on or off when clicked. Other than being in tabs like this, actions work like you’re used to. You can use multiple actions, limit them using If conditions, and so on. With 11 element types that all work differently, there are a lot of different tabs to be familiar with. Like with individual actions, there are too many to go into detail with each one, but the Tasker help button is available in the element configuration screens to explain how each element works. The examples at the end of this article will also go into detail on how some specific usage scenarios are configured. Scenes can be used for so many things that examples are a better way of trying to explain the potential rather than trying to explain each component individually. In fact, making elements work together is far more difficult than configuring them on their own, as some of the examples will show. Triggering scenes

The Scene category of actions currently has 20 different actions available. Most of them have to do with manipulating elements using actions, but the top four actions are different; they control the existence of a scene. These four actions are Create Scene, Destroy Scene, Hide Scene, and Show Scene. A scene can be active even if it isn’t displayed. You can compare it with how an app can run in the background, and in the same manner, a scene that is active in the background takes up system resources. The Create Scene and the Hide Scene actions deal with this state of visibility, with Create Scene starting up a scene without displaying it and Hide Scene taking a visible scene and hiding it without actually closing it. Show Scene and Destroy Scene are the two most used options, and the only two of these four that I actually use. Show Scene displays the scene, and creates it (starts it up) if needed. Destroy Scene closes the scene, so that it doesn’t run in the background either. The name “destroy” can be confusing as it sounds like it deletes the scene you created, but it actually doesn’t affect the saved scene “template” that you created in Tasker at all – it simply closes the scene completely. To make this perfectly clear, here’s a short vocabulary of terms often used with scenes: 

Create scene: Starts up a scene in the background



Show scene: Shows a created scene (and creates it if needed)



Hide scene: Hides a scene, but still allows it to run in the background



Destroy scene: Closes the scene completely

This can be confusing since most people would assume that “create scene” refers to what you do in the scene editor. In fact that is often referred to as creating a scene too, so you just have to be aware of the double use of the term. Activate and deactivate would have been better choices for names, but hindsight is always 20/20. Normally you’d use Show Scene to make a Scene appear, and Destroy Scene to make it disappear and not run in the background. The examples at the end will show a few ways to use these in practice. Show Scene options The Show Scene action is the method you’ll most likely use to trigger your scenes and make them appear. Like I said above, this action actually controls some aspects of how the scene will look. Specifically, there is a Display As option in this action that has 9 different states: 

Overlay



Overlay, Blocking



Overlay, Blocking, Full Display



Dialog



Dialog, Blur Behind



Dialog, Dim Behind



Activity, Full Window



Activity, Full Display



Activity, Full Display, No Title

These 9 Display As option decide how the resulting scene will display and act. From the Tasker user guide:

“ All Overlays are displayed over the current application and persist until hidden or destroyed. Blocking overlays only block touches on the part of the screen they cover. Non-blocking Overlays are also displayed over the Keyguard. Dialogs are little popup windows which take all user input while they are displayed and can be dismissed with the Back key. Activities are standard Android app views.

What you have here is essentially three display types, each with three variations. 

Overlays are meant for scenes that display over part of another app. Let’s say you want to have music controls visible while browsing. You could then make a small scene with music controls, and display that as a overlay at the bottom of the screen when your browser is active (using an app context).



Dialogs are essentially pop-up boxes, like yes/no dialogs and the likes. You might want to have a profile that triggers on plugging in your headphones, and then pops up a box with several options for apps to launch. A scene displayed using a dialog option would be perfect for this. Do note that there’s an action called Menu in the Alert category which provides an alternative way to create a dialog scene.



Activity scenes are meant for scenes that work more or less like apps. As a result, you would normally use those options for scenes that you want to act like apps. With Tasker’s new app export ability, many people find themselves using scenes as configuration screens in exported apps.

If you use any of the Display As options that are not fullscreen, you will also get some additional options that adjust the position of the scene. This is particularly useful for overlay scenes which often need to go over a certain part of the screen. Do note that display type options sometimes act differently on different devices and OS versions. My advice is to try the options out and see which ones work the best for you. The Show Scene action also has an option to “show exit button,” which is enabled by default. This shows a red exit button in the bottom right corner which will close the scene when clicked. This is a failsafe to prevent anyone from making a scene with no way of closing it. You can really mess up if you use certain display types and disable this without having an exit option yourself, so make sure that you have some sort of way to destroy or hide the scene from within the scene before you uncheck this option. In the examples that follow, pay attention to how the Show Scene action is rarely on its own in the task that triggers the scene. Very often, you have to do additional preparation in the same task in order to properly create the scene, such as setting an element value (example 1), loading text files into variables (example 2), and downloading images from the web (example 3). Also pay attention to the order of these actions. Example 1 has the Show Scene action first, as the other action manipulates an element in the scene, thus requiring the scene to exist beforehand. Example 2 and 3 have the Show Scene action last, as the other actions in the triggering task gather information that has to be in place before the scene can be created. Like I said, the difficult part of scenes has to do with making all the parts work together correctly, not configuring individual elements. How it’s triggered

The settings box can be triggered using two shortcuts; one on my home screen, and one on my lock screen. Tasker has a built in feature that allows you to run tasks from shortcuts, which is why I use in this case. When either of those shortcuts are clicked, a task called Show Psett runs. This contains two actions, Show Scene: Popupsett, and Perform Task: Refresh Br. The Show Scene action is what I described above, and in this case it uses Dialog, Blur Behind as the display type. Refreshing the slider: a lesson in dealing with generic elements The second action, which runs the separate task Refresh Br, has to do with the display brightness slider in the scene. To understand why it’s there, you first have to understand how generic scene elements work, as well as how the slider element works. A slider element in a scene has to be configured with a minimum and a maximum value, which is what the value of the slider will be when the slider handle is all the way to one side or the other. Screen brightness has 255 levels in Tasker, so my brightness slider is set to go from 0-255. When you slide the slider half way, the value is 128, when you slide it all the way, it’s 255, and so on. This is a setting in the slider element’s UI configuration tab. The other tab in the configuration for the slider element is Value Selected. Value Selected is the slider element’s version of the Tap/Long Tap tabs I mentioned for button elements earlier. Every time the slider handle is moved, Tasker runs any actions added to the Value Selected tab. Additionally, the value that the slider lands on when you release the handle is written to the local variable %new_val automatically. For my brightness slider, moving the handle all the way to the right sets the value of %new_val to 255, and it runs any action in the Value Selected tab. In this case, this tab contains a single action: Display Brightness, where the Level field is set to %new_val. When the slider handle is moved, the value it lands on is stored in %new_val, and the Display Brightness action uses that value to change the screen brightness. The result is that sliding the slider all the way up sets the screen brightness to 255, which is 100%. It’s important to understand that the slider doesn’t know that it’s a brightness slider. All it does is turn a position on the slider into a value, and that’s it. As such, the slider handle will start at 0 every time the scene is created, because the slider neither knows nor cares what the current brightness level is. In order to make the slider handle be in the correct position on the slider when the scene pops up, you have to actually tell the slider where the handle should be positioned. This is what the Refresh Br task does.

As you can see above, this task consists of two actions: Set Variable and Element Value. Element Value is an action in the Scene category, and it allows you to manipulate the value of an element using a task. In this case, we want to tell the slider to put the slider handle at the same level that the screen brightness is currently at. If you’re at 25% brightness, you want the slider to be 1/4 of the way to max, and to make that happen, you need to tell the slider to start there. By running an Element Value action that sets the value of the slider to the current brightness level as part of the same task that triggers the scene, the slider will be in the right position when the pop-up box appears. So, what about the Variable Set action? Well, the Tasker dev messed up a bit when he created the Element Value action. The Value field only accepts global user-created variables and numbers, so we can’t use the built-in variable %BRIGHT (which always contains the current brightness level) in that field. To work around this “bug,” I copy the value of %BRIGHT into my own variable %Brait, and use that variable in the Value field instead. It’s a weird and slightly annoying bug, but worth noting since a brightness slider is a useful thing to have in a scene, so you might run into this situation yourself. To put all of this in words, this is what Tasker sees the Show Psett and Refresh Br tasks as:



Show the pop-up settings scene and move the slider handle so it matches the current screen

brightness Where the red text indicates what Show Scene does and the blue text indicates what the Refresh br task does. The important lesson to take from this is that elements in a scene are generic, and that means that they won’t always work the way you think they would work. In this case, the slider is used to control the brightness level, but the slider doesn’t know that, and so it needs you to tell it that the brightness level has changed without it in order to display that properly. In example 5 you’ll find a use for the slider that proves pretty conclusively that it doesn’t have to be a brightness slider. As for why the two actions in Refresh Br are in their own task instead of being part of the Show Psett task, that was originally in order to refer to the same refresh task from other places than just that one task. I ended up changing the system to where only the Show Psett task actually uses that task, meaning that it doesn’t need to be its own separate task at this point. However, in the todo list example below, I will show you an example of where such separation does have a use. The scene

This is what the scene edit screen looks like for the pop-up settings scene, and what it looks like when actually triggered. It’s a collection of button elements, text elements, and a slider element. As you can see, I’m using a grid size that allows me to space out buttons of various sizes evenly, and finding the right grid size for that to be the case can often be a pain. In this case, the settings box actually looks like it’s fullscreen, even though the Display As type is Dialog, Blur Behind. That’s because the scene itself covers most of the screen, but you can still see the status bar shining through, and the effect of the Blur Behind option. Also note the position of the slider handle. The brightness is set at 25% in that image, and the slider reflects this – because of the Refresh Br task. Without it, the brightness would still have been 25%, and the slider would still have been able to control the brightness, but it wouldn’t have displayed the correct brightness unless it was the one to set the brightness. Top seven buttons

The top seven buttons all do different things, but are all rather basic. Most of them have two actions: Perform Task and Destroy Scene. Destroy Scene closes the pop-up settings scene, while Perform Task runs a separate Tasker task. Two of the buttons, WebCam image and Todo list, trigger new scenes which are separate examples above. The reason why the TeslaLED task doesn’t use Destroy Scene is that it toggles the LED light on my phone on or off, so I want the scene to stay active (not close) when I click the button, so I don’t have to start the scene up again to toggle it off after I toggle it on. The actual functionality of the tasks behind the Perform Task actions here isn’t important, the point is just that I use these buttons to toggle other tasks from a central location. For the record though, the seven buttons do the following: Run a task that archives the articles I’ve written on this site that day, opens a “virtual window” scene with WebCam images, overrides an active school profile using a variable, toggles the LED, opens my todo list scene, turns my computer monitors off wirelessly, turns my computer monitors on wirelessly. Profile buttons

The three profile buttons control a profile system that is separate from my automated profiles that I talked about in part 2 of this guide. They’re designed to be activated manually, which is why I have buttons for them. Each button closes the scene (using Destroy Scene), sets the variable %Profile to a specific value, and in the case of the Normal mode button, deactivates silent mode. The values that %Profile is set to in this case are literally “Normal mode,” “Silent mode,” and “Movie mode.” Movie mode and Silent mode are separate profiles altogether, both of which uses Variable Value as the context. In order for the Movie Mode profile to be active, the value of %Profile literally has to be “Movie mode.” In the previous article I talked about advantages of using number values instead of text values for variables that are used as settings, but in this case, using a (complicated) text value has one big advantage. That advantage can be seen in the right image, where the text element is set to display “Profile: %Profile.” Since the value of %Profile is the full name of the currently active profile, the text element will end up displaying the name of the active profile (this can be see in the screenshot in the “The scene” section above. Had I sued 0/1/2 instead of Normal mode/Silent mode/Movie mode as the values, the text element would for instance have displayed “Profile: 1.” That little lesson in variable value naming aside, this profile button setup demonstrates how you can activate and deactivate entire profiles using scene elements. The scene elements (buttons in this case) set a variable to different values, and then various profiles trigger depending on that value. Brightness controls I already explained how the slider works, but as you’ve probably seen, there are also buttons present that set the brightness to specific values. These buttons simply set the brightness to the specified level (measured from 0-255, so that 50% is 128), and then destroy the scene. As for the OK button, it only does one thing: Destroy Scene. That button is there for when I use the LED toggle or the brightness slider, as those two elements don’t contain their own Destroy Scene action. Like I explained earlier, the choice not to include a Destroy Scene with those is because I expect to want to continue using the scene after I interact with them, and so having the scene go away would be annoying. Example 2: Todo list A month ago I gave up on commercial todo list systems and made my own in Tasker. I didn’t go into details onhow I did it back then, but I will now, as most of it happens in a scene. How it’s triggered

The todo list system currently consists of three lists, each for a different situation. I get notified of items from the shopping list when I walk outside, the morning list when I get up, and the home list (listed as “after school” in parts of the system) when I get home. These lists are stored as physical text files on my phone, but Tasker needs these to be variables to display their content. As such, the first three actions in the task that triggers the todo list scene are Read File actions. These actions read the text files and turn them into variables, one for each list. The fourth action is a Wait action, the purpose of which I’ll get into later. It simply delays the rest of the task by half a second. The fifth and final action is the Show Scene that actually makes the scene show up. Like the previous example, the Display As setting is set to Dialog, Blur behind. The task itself is triggered from the pop-up settings box in example 1, using the Perform Task action.

The scene

This is what the scene looks like in edit mode and in actual use, with some examples thrown into the latter for good measure. The field between Title and Tag is a text input field, and the three fields at the bottom are text fields. Text input field, tag buttons, and save button Text input fields work a lot like slider elements. Each time you input something in the text field (i.e. for each and every letter), it writes the content of the text edit field to the local variable %new_val. It also runs all actions under the Text Changed tab in its configuration screen, just like how the slider runs all actions in the Value Changed tab when the handle is moved. The problem with this is that if you’re typing, you’re going to run those actions a heck of a lot of times. As such, I advise that you keep the number of actions in this tab to the bare minimum. For me, there’s only one action, which transfers the value of %new_val to my own variable, %todotitle. I don’t actually think I even need to do that, but I have an old habit of using user created variables. Point being, when I’m done typing into the text field, there will be a variable %todotitle that contains whatever was typed into the field. Next up is the tag buttons. These are very simple buttons that set the variable %Todotag to Shopping, Home, or Morning respectively. The Save button is where the actual magic happens. When clicked, it appends the corresponding text file with the value of %todotitle (plus a line shift) depending on the value of %todotag. In other words, whatever you wrote in the text input field is added to the text file for the list you selected using the tag buttons. It filters this using If conditions on the Write File actions. The important lesson here is how the use of a separate Save button means that I can put the actual Write File action out of reach of the “rapid fire” Text Changed tab. If I had put Write File in the Text Changed tab for the text input field, it would have written to the file every time a new letter was put in. Not only could that cause problems for the system, but you couldn’t use the append option for adding the text to the end of the file, as it would then repeat all preceeding letters as well when it wrote new ones. Inputting “apple” in the field would then result in a file like this:



aapappapplapple

I can’t emphasize enough that making everything work together is what’s difficult with scenes, and this is just another example. After it has saved the text to a file, it destroys the scene, and runs the task that triggers the scene all over again (the one described at the beginning of this section). The point of this is to refresh the entire scene in as simple a

way as possible, clearing the text input field and updating the text elements so that they display the new content of the text files. This is where the 500ms delay comes in. I had trouble with the scene not reloading properly when doing it without a delay, so I added one. Sometimes you just have to manually give tasks a bit of breathing room by adding wait actions. The save button also has a second use, triggered by holding down the button instead of just quickly clicking it. This is done by adding actions to the Long Tap tab, in this case a simple Destroy Scene action. Since clicking the button will make the scene reload, I needed a button that actually closes the scene. Instead of adding a separate button, I simply added a second use for the Save button.

Text elements

The bottom part of the scene consists of six text elements: fields that list the contents of the three todo lists, and corresponding labels on top. The labels are static, but the lists are dynamic. First of all, each list has a variable as the content of the Text field. They’re the variables that are created by the initial task that creates the scene, and contain the contents of each of the todo lists. In other words, each of the three text elements contain the text stored in the text files. Whenever the initial task is run by destroying the scene and running the initiation task again, these variables are refreshed. The Tap action for each text element is top open the corresponding text file. This opens it in whatever app is set to open text files, and this is frankly just a very quick and simple way of adding a way to edit todo lists. I very rarely have to do so, as I normally clear the entire list at once, but it’s nice to have the option.

The Long Tap task for each element does three things. First, it displays a new dialog scene the quick and dirty way, by using the Menu action I briefly mentioned earlier. The Menu action technically creates a scene, one you can modify the looks of even, but you configure it via the action’s own options, not the scene editor. It’s quicker when you just need to create a quick dialog scene, like here. This Menu scene asks if you want to clear the corresponding todo list. There are two options in this Menu scene, Yes and No. No destroys the Menu scene, and then the initial Long Tap task continues, closes the todo scene, and restarts/refreshes it using the same method as with the save button. The Yes option writes a blank space to the corresponding todo list text file, with append unchecked. The append option for Write File decides whether or not the new text is added to the end of the file, or if it overwrites the file. The Save button Write File actions have append enabled, but this one doesn’t, as it’s supposed to clear the list. There are a couple of reasons why I write an empty space to the text file instead of writing nothing or deleting it. If I had used Delete File to delete the file, then Tasker would have given me an error when it tried to read the file into a variable as part of initiating the scene. If I had written nothing to the file, then the variables created by Tasker when initiating the scene would have been blank. As explained in the previous article, this causes Tasker to literally display the name of the variable where the variable is used. In other words, an empty list wouldn’t display as empty in the scene, instead it would show the name of the variable, like %Todoshopping. After you click yes, the todo scene is destroyed, then recreated to refresh it. The non-scene part of this list Since I know for a fact that there are people out there who tried to make a todo list system like mine and failed, I’ll also briefly mention the side of this system that isn’t scene related – just for the sake of not leaving it half done. What this scene does is to give you an interface for creating and managing the todo list, but the other component to the puzzle is a way for Tasker to check it and act based on it. The image above shows my Todo Morning task. The purpose of this task is to check the morning todo list and notify me if there are any items in it. It starts off by reading the text file that contains the list into a variable. If that list is empty, the variable will contain only a space (ref. the way I clear the list above). As such, I can use an If condition for %Todomorning Matches ++ to check if there are any items in it. ++ means “at least two letters,” which is true when there are any actual items in the list, but not true if there’s only that one single space. Action 4 in the list above creates a notification with %Todomorning as the text, but is limited by this If condition. As a result, it only creates the notification when there are items in the list. Action 2-3 are not really relevant, but I’ll explain them for the sake of not leaving any questions. This Todo Morning task runs as part of a much larger task that runs when I get up in the morning, and I want the spoken message that I get when that happens to mention if I have any items in my todo list. I do this

by setting the variable %Todomorningnot to “You have items in your todo list” using the same If condition as action 4 above. %Todomorningnot is then inserted into the Say action in the main morning task. Action 2 makes sure that this variable doesn’t contain anything if the If condition is not met. The final result is that if the list contains any items, a notification will be created, and my morning message will notify me of it. If the list is empty, there will be no notification and no message. Example 3: Virtual window WebCam scene My virtual window has been the topic of a short article before, but I didn’t go into much detail. Just like the todo list, this is also all about the scene. How it’s triggered

This scene is also triggered by a task linked to one of the buttons in example 1. The scene itself contains images that have to be downloaded from the web, and because of this, the Show Scene action is at the end of the task. The three actions before it are HTTP Get actions, which are used to download the images. The images are saved to a specific path, so that each time the task runs it overwrites the existing images. It’s imperative that the Show Scene action is run last here, or the scene would load the old images. The Display As type in this case is Overlay, Blocking. In this case it doesn’t really matter though. The scene

The scene is as simple as it gets. It has three image elements, each of which uses one of the downloaded images as a source. The images have been moved and re-sized in the editor, and even though it loads newly downloaded images each time it’s displayed, it keeps the same layout. Each image also has Destroy Scene as the Tap action. That means that tapping any of the images will make the scene go away. This is a very simple scene from a technical point of view, but I use it a lot. It also demonstrates the use of dynamic images, which has many applications. You could for instance create a scene that shows today’s new web comics when you click a button. Examples 1-3 in practice Examples 2-3 are triggered with buttons in example 1, so I thought I would create a simple video to show how all of this looks in practice. There’s a lot that goes into making everything in a scene work the way it should, especially when there’s a lot that has to work together. As you can see in the video though, it’s all quite simple when you actually get to where you can use it.

Example 4: Gmail notification The first three examples are all fairly standard uses for scenes. This one is not. It all started with a wish to add a more visible notification for incoming emails, similar to notification LEDs on some devices. I experimented with using the camera LED, and that worked well, but it wasn’t quite as…elegant as it could be. My Galaxy S II has an AMOLED screen, and one of the advantages of such a screen is that the color black is created by turning off the pixels. Black pixels are therefore just the screen being off, and you can’t tell a black bezel from the screen when that’s the case. I came up with the idea of having a Gmail logo be displayed on the screen, in such a way that it appears as if only the part of the screen with the logo actually turns on (which is in reality what actually happens as well, due to the way AMOLED technology works). The video below is the result of this idea, and all the magic is done with Tasker scenes.

How it’s triggered

Part of what makes this example so different is how it’s triggered (or perhaps controlled is a better word in this situation). First of all, this scene is triggered automatically using a profile and a context. Four contexts, to be exact. The main one is an event context for any notification from the app Gmail. In other words, this context is triggered if Gmail receives a notification, which is only when it receives an email in my case. This event notification is further filtered using three state contexts. The variable %Sleepmode can’t match “on,” the Home profile has to be active, and the display has to be off. The first of these is to prevent the profile from being active when I sleep. The second is to make make sure it only runs when I’m home (I have a different Gmail notification system for other locations). The third is to make sure it only runs when the display is off, so that it doesn’t start interfering with me using the device. Now, to the task that creates the scene. The first action shows the Gmail Notification scene, which is the Gmail logo on a black background. The display type is Overlay, Blocking, Full Display. The second action is another Show Scene, this time for a completely black scene, with display type Activity, Full Display, No Title.

So, why two scenes? In my testing, I found that (on my device and ROM, this might very well be devicedependent) the Overlay display type wasn’t capable of turning on the screen of my device. The Activity display type is, but its definition of Full Display doesn’t include the status bar, leaving it visible. By using two scenes – one of each type – I managed to get a scenario where the scene will turn on the display, and it will actually cover the entire screen with a black box, meaning the pixels will stay off on an AMOLED screen. Since I initially created this system, I’ve rooted my device, and I can now use the Secure Settings plugin to wake the device. Still, I don’t tend to fix something that’s not broken, and the non-root method is a better example of how you can use scenes creatively. On to action 3, that one’s a Wait action which decides how long the display will stay on for (as action 5 is System Lock). The Gmail logo is clickable, and clicking it will bring you to the Gmail app, so action 4 is there to prevent the rest of the task from running (and in doing so, turn off the screen) if I do indeed click the logo. The variable that the Stop action has an If condition for is set when clicking the logo, as you’ll see further down. Action 6 is a new wait, this time to make sure that the lock screen animation has time to finish before the two scenes are destroyed with actions 7-8. When all of this works together, you get the result in the video above. The scene

The two scenes here aren’t very interesting in themselves. The Gmail Notification scene has the Gmail logo, and that’s about it. There are however quite a few actions tied to the Tap task for the image. First, it sets the %Gmailactive variable, which in turn controls the Stop action I mentioned above. Then it destroys the two scenes used to create the notification. Next, it loads the Gmail app, allowing me to actually read the email that came in. Finally, it waits for 6 seconds, and then clears the %Gmailactive variable, resetting it for next time. Like I said, this is a fairly peculiar use of scenes, but it’s also one of my favorite Tasker setups. My phone is normally sitting in a DIY cradle on my desk when I’m at home, with the screen pointing towards me, so having a visible notification is great. Being able to limit it to when I’m at home and not using the phone makes it that much more useful. For the record, when I’m not home, the notification switches to three one second vibrations instead of this setup.

Example 5: Lock screen using scenes

The previous examples have all been from my own Tasker setup, with scenes and systems I know well. For this last one I’ll do a reader request from a previous Tasker article and create a lock screen in using scenes. How it’s triggered Since we’re talking about a lock screen, the logical thing to do would be to trigger it on Display On, which is an event context. The problem with that is that since it takes a few milliseconds to show the scene, you get this lag effect when using that context – at least on my older Galaxy S II. The alternative is to trigger it on Display Off. This might seem backwards, but the advantage is that the scene is then ready to go when you turn the screen back on, making that part faster. This method does however also have its disadvantages. First off, any elements in the scene will have been created when the screen was turned off, and might be outdated by the time you turn it back on. As you’ll see later on, I added a simple text element with %TIME as the text to my test lock screen, which resulted in a “static clock” that displays the time that the scene was created (but doesn’t change on its own). That means it’s useful for checking the time quickly by turning on the screen if the scene is created at the same time, but not if it (and the time) is from back when the screen was turned off. It is however possible to half fix this by adding a profile that does trigger on Screen On, and use it to update the time-sensitive elements by using the various element update actions in the Scene category of actions. You then get a scene that appears quickly, but with the wrong data, which is then updated after a split second. The second problem with using Screen Off is that if you have a security lock screen (e.g. pattern unlock screen) below your Tasker-created lock screen, you need to use the dialog display type to make your own lock screen be on top (if that’s what you want, of course). Unfortunately, any dialog scene also turns the screen back on, so when you lock the screen, it will create a scene that turns the screen back on. You can half fix this issue too, by adding a System Lock action after the Show Scene action in the task. You then end up with a lock screen that flashes briefly when turning the screen on. So, bottom line, both of these methods have issues. If you’re not overly picky about it though, the split second you have to wait when using the Screen On context isn’t too bad.

Creating a lock screen scene Now this is where the fun begins! There’s so many things you can do to create a lock screen in Tasker, and the end result can be pretty impressive. I started out by adding a slider, picking the Tasker icon as the handle (or thumb as Tasker calls it), and setting it to go from 0-100. Then I went to the Value Selected tab and added a Destroy Scene action with the If condition %new_val Maths: greater Than 90. Why? Slide to unlock! When you slide the slider past 90% to the right, it destroys the scene, and the screen “unlocks.” Next I added the “clock.” It’s a simple text element with %TIME as the text, as I explained above. Using a large text size makes it look like a widget. You also have %DATE, %BATT, and a ton of other built-in variables to help populate your lock screen scene. Just remember that the more dynamic content you add, the more you have to update using a second profile if you should choose the Display Off option for triggering the scene. Next I added a Gmail logo by inserting an image element and using the Gmail app logo. I added an action to open the Gmail app as a Tap action, as well as a Destroy Scene action to close the lock screen when doing so. Since I don’t plan on using this lock screen system myself, I cheated and added static text to display new emails beside the icon. Adding an actual email counter (or SMS counter for that matter) is not a problem. Finally, I added a static image of my dog, just to fill the screen. If I were to actually use this though, I would have used the rest of the space for something else, like owner information and the likes. Once your scene is done, all you have to do is link a task that triggers it to your preferred context. Situation-dependent lock screens While I don’t plan to replace my WidgetLocker lock screen, there is one advantage of this scene system that makes me very tempted to do just that: Having situation-dependent lock screens. You can easily create multiple scenes for different occasions, like one for home, outside, school, work, and so on. Many people, me included, have profiles for various locations and situations, and using those to control which scene is displayed is as easy as having multiple Show Scene actions with If conditions. Why WidgetLocker doesn’t have profiles is something I can’t fathom, but from what I’ve seen of the developer’s response to user feedback there isn’t much hope. Despite that though, using scenes as lock screens isn’t quite there yet if you ask me, but it’s ridiculously close for something that wasn’t designed for it. In closing This has been a very long part of the guide, with a stronger focus on examples than on theory. That’s simply because the scene feature has so much potential that I think it’s easier to understand how it works by seeing real life examples. As you’ve probably noticed though, there are a lot of minor things here and there that makes each scene unique, from having to pre-load data before creating a scene to using multiple scenes to combine their advantages. The next part of the guide will cover data processing using variables, which is something that opens up for a whole range of new uses for Tasker.

Beginner’s guide to Tasker, part 4: Variable data processing

With the basics, variables (in general), and scenes now all covered, it’s time to dig into something a bit more specific: Processing data using Tasker variables. It’s more of an implied feature than the previous topics, but it’s also (in my opinion) one of the most powerful features in Tasker. Variable data processing? I’m kinda making up terms here, but it’s as good a term for this aspect of Tasker as anything. By variable data processing, I’m referring to how you can work with data stored in variables, extracting information from it, creating your own contexts, and so on and so forth. I have multiple profiles and tasks that use this in my Tasker, and some of them have been posted on this site before. The calendar event announcer and the weather forecast announcement system are both examples of variable data processing. It’s all about taking some data – text, in other words – and working on it until you get what you need from it. Data sources To really understand the power of variable data processing you first have to realize how many potential data sources there are out there. More or less anything that is stored in text form can be used in Tasker, it’s all about knowing how. Websites, exported calendar data, text documents – all of them are potential data sources. If you see some text, you can most likely use it in Tasker – it’s that simple. Weather data, local news, moon phases, horoscopes, Pocketables articles, you name it. Want to create a profile that is active when your horoscope mentions money? No problem. It’s also important to understand the difference between what you see and what a computer sees. A web page is seen by the computer as pure text, a mixture of references to images, text, rules for how to lay out the page, and so on. CTRL + U brings up the page source of a web page in most web browsers, allowing you to see what the computer sees – the web page in pure text form. The chaos of text that greets you when you look at the source can be frightening at first, but as you’ll see further down, it can also be extremely useful. Reading data into variables The first part of any system based on outside data sources is to get the data into a variable, where we can work with it. There are many ways of doing this, but some of the most important ones are Read File, HTTP Get, Get Voice, and Variable Query – all of which are actions. The examples will focus on data gathered with HTTP Get though, as that’s the hardest to work with, and the most powerful.



Read File reads a file stored on the internal memory into a variable, like the contents of a text file.



HTTP Get is used to get (the source text of) a webpage into a variable, %HTTPD.



Get Voice is used to listen for voice input, which is then turned into text and stored in a variable, %VOICE. This is the foundation for a DIY voice assistant like my Nelly.



Variable Query pops up a dialog box asking for a variable value. Great for things like quick todo list entries, Tasker-based accounting systems, URL archive, and so on.

HTTP Get HTTP Get (found in the Net action category) is perhaps the most versatile data collection action of them all, as it allows you to load web pages into variables. It does however have some quirks here and there. In theory, it loads the contents of the web page into the built-in variable %HTTPD. On some devices however, like mine, %HTTPD simply doesn’t contain the right data (or any data) after using HTTP Get. In such cases, using HTTP Get’s option to save to a file, combined with Read File to get it into a variable, is an excellent workaround. In examples further down you’ll see this approach a lot, though I should point out that simply using HTTP Get to populate the built in %HTTPD variable is the “proper” way to do things – when it works. Then again, to actually work with the data you have to have it in a user created variable, meaning you have to copy the contents of %HTTPD to another variable, leaving you with just as many actions as if you use HTTP Get and Read File. In the HTTP Get configuration screen, you’ll see several fields, the top two being Server:Port and Path. As a general rule, put anything before and including the domain (like .com) in the first field, and the rest in the Path field. For instance, the URL http://www.pocketables.com/2012/09/beginners-guide-to-tasker-part-3-scenes.html Would be split into these two fields: Server:Port: http://www.pocketables.com Path: 2012/09/beginners-guide-to-tasker-part-3-scenes.html In theory, the contents of this URL should then be available in %HTTPD after the actions runs. If not, use the Output File field to save it to a file (e.g. pocketables.txt) and then use Read File on that file. Data processing tools Once you get the data into a variable, the job of actually turning it into something useful begins. Often, especially if you load entire web pages into a variable, the variable becomes an epic mess of text. It’s always a good idea to do this type of Tasker setup in front of a computer, so that you can have the full text available in front of you. If you’re working with a web page, for instance, have the source code (CTRL + U) of the page in front of you to get a better look at what is in the Tasker variable. You’ll see me do this in the video in example 2. Next up I’ll cover some of the most common tools you’ll be using when working with the data. These are all actions that manipulate the content of a variable, and as such, are located in the Variable action category. I won’t cover all, but I will cover the most important ones. Variable Split

Congratulations, you just met the single most important action there is for this kind of Tasker setup. Variable Split could just as well be called Variable Chainsaw or Variable Ninjasword, as what it does is that it cuts/slices variables into pieces. It has two relatively simple configuration fields: Name and Splitter. Name is the name of the variable you want to chop into pieces, and Splitter can best be described as the point in the variable where you want to split it. For instance, let’s say you have a variable %Hobbies that contains the text “football,hockey,swimming” If you then use a comma (,) as the splitter, the “chainsaw” will target all of the commas and cut the variable in those spots. The actual splitters will be destroyed in the process. This creates new variables that are numbered derivatives of the original, each containing a piece. In this case, you would get the following variables: %Hobbies1: football %Hobbies2: hockey %Hobbies3: swimming You just used the commas as points to split a single variable into smaller, individual pieces. This method is the alpha and omega of variable data processing. By choosing the right splitters you can chop huge variables containing entire web pages into small, manageable pieces that contain just the information you need. You can split a weather website into variables that contain just the weather forecast, or split a news site into just the titles. This is where all the “weird” text in a web page comes in handy. All the tags that are used to assign formatting to specific parts of a web page can very often be used as splitters as well, allowing you to grab parts of a web page much more easily than you’d think from seeing just the text. By using the source on a computer together with CTRL + F (find text on page), you can feel your way to finding a good splitter. As an example, let’s take a look at pocketables.com. Let’s say that we want to create a list of articles currently on the front page, both links and titles. We load the page into the variable %Pocketables. Looking at the source in a browser (which is also what’s in %Pocketables at this point), we see how each article is listed in the source code:

All the tags (like ) in between the text are what decides how the page looks to you – it’s like a guide for telling the browser how to display the page. You see the visual result, but Tasker sees this code when you load a web page into a variable like this. This is a good thing, as we can use these tags as splitters. In this case, we see that the link to each article is immediately preceded by puts the headline at the beginning of the variable %lbnews22, but still leaves a bit of junk at the end. A final split of %lbnews22 using the splitter leaves us with a variable %lbnews221 which contains only the headline, which can then be used directly in actions within the same task, or transferred to a global variable and used elsewhere. Since the initial split created multiple children that share the same format as %lbnews2, just with a different article, we can then copy the actions that split %lbnews2 and %lbnews22, and simply replace the variables with %lbnews3 and %lbnews32, respectively. We then get %lbnews321, which contains the second headline – and nothing else. Copying again and doing the same with the number 4 would give us the third headline in %lbnews421, and so on and so forth for as many of the headlines you need. Each headline will then be in its own variable which can be used in a Say action or something else. Like I said earlier, there are ways to automate this beyond manually copying the actions for each child, but for the sake of simplicity I won’t go into that. Task download: The downloads below contain the finished task with 5 complete headline variables. It can be edited to change the number of headlines it splits out of the source if necessary. Follow the instructions for downloading and importing in example 1 to get this into Tasker. The final action, which is a Say, has to be edited to specify a different voice engine if the Amy UK English Ivona engine I’m using for my text to speech is not installed. Download: Lpnews.tsk.xml

Download: Lpnews.tsk.xml.zip Example 3: Google calendar event announcer Another explanation of a task I’ve given you a download for before. This time it fetches data from Google Calender using Google Calendar’s ability to access the calendar with a web link, in XML format. Like with example 1, I’ll give you a task you can download and import, and then I’ll go through and explain how it works. Preperation Download the task from the bottom of the article. Four versions are available: A direct .xml download and a zipped version for each of the two basic task versions, DDMM and MMDD. Which of the basic versions you need depends on the date format you use. This task only works with the date formats DD/MM/YYYY and MM/DD/YYYY. This is a setting you pick in your device’s system settings, in the date and time section. It has to use one of those two, or it won’t work. If you read 07.12.2012 as July 12th, you want MM/DD/YYYY. If you read it as December 7th, you want DD/MM/YYYY. Follow the instructions in example 1 on how to download and import the task.

Once imported, open the task, then the HTTP Get action. In the Path field, you will see XXXX and YYYY as part of the path: calendar/feeds/XXXX%40gmail.com/privateYYYY/full?singleevents=true&futureevents=true&orderby=starttime&sortorder=ascending&max-results=1 These are the two pieces of information you have to switch out. XXXX needs to be replaced with your Google user name, e.g. “example” if your login email for Google is [email protected]. If your email for Google does not end in @gmail.com, you also have to change the bit after %40 with whatever domaing your email is. Examples: calendar/feeds/example%40gmail.com/privateYYYY/full?singleevents=true&futureevents=true&orderby=starttime&sortorder=ascending&max-results=1 calendar/feeds/example%40googlemail.com/privateYYYY/full?singleevents=true&futureevents=true&orderby=starttime&sortorder=ascending&max-results=1

YYYY needs to be replaced with a private access key for your Google calendar. To get this, start by going to the Google Calendar website, then go into settings. Click the Calendars tab, then the calendar you want to use. At the bottom of the calendar details screen, click the orange XML button next to Private Address. You should get a popup box with a URL that looks something like this: https://www.google.com/calendar/feeds/example%40gmail.com/private-1234567812345678/basic Your access key is the piece I highlighted in bold. You need to copy this in place of YYYY in the Path field in Tasker. An example of a finished Path would be: calendar/feeds/example%40gmail.com/private1234567812345678/full?singleevents=true&futureevents=true&orderby=starttime&sortorder=ascending&maxresults=1 Save the edit to the HTTP Get action and then find the Say action at the end. Select a speech engine that you have installed on your device.

“ Note: Recently created Google Calendar calendars use a different format with a [email protected] email in the URL. This task has been tested to work with the new format, however you need to grab both the specialized email address and the key from the XML button mentioned above.

Task download Download (DDMM, .xml): CalendarDDMM.tsk.xml Download (DDMM, .zip): CalendarDDMM.tsk.xml.zip Download (MMDD, .xml): CalendarMMDD.tsk.xml Download (MMDD, .zip): CalendarMMDD.tsk.xml.zip

Explanation This task was made on demand for a very specific purpose: Reading the next upcoming event, if that’s on the same day. This means it won’t list multiple events, although you can use the same method (with a different source URL that contains the right data) to make one that does, if you need that. Actions 1-2: Reads the data into a variable, like before. Action 3: Copies the variable into another variable, since we’ll be splitting it multiple times. We did this earlier too, with another variable. Action 4:

Does a variable split of %Ceventdate, which is the copy of the calendar source data, using startTime=’. This contains the start date and time of the event. This splits it right up against the edge of the time information, and because we’re working more with it later on, we don’t cut off anything from the end of it right now. Action 5: Copies the value of %Ceventdate2 into a new variable, %Eventdate. Like earlier, this is because we’re going to use this variable multiple times, and don’t want any overwrites. Action 6: This splits the recently created %Ceventdate2 copy %Eventdate using the splitter -. %Eventdate contains data in the form of 2012-09-12T21:30:00.000+02:00, which means that splitting by a dash puts the year in its own variable, the month in its own variable, and the day of the month plus some garbage text at the end in its own variable. Action 7: This splits %Eventdate3, which is the third child from action 6 (the one with the day of the month plus garbage) using the splitter T. This is purely to clean up that last variable from action 6, removing the garbage. Action 8: Creates a variable %Samedayevent and sets its value to “no.” This is to make sure that the default value of this variable is “no,” in case the If condition in action 9 isn’t met. We’ve done something similar before, and without this, a leftover value from the previous time the task ran will still be present if the If condition in action 9 isn’t met. Action 9: Overwrites the value of the variable created in action 8 to “yes” If %DATE matches %Eventdate31-%Eventdate2%Eventdate1. This one requires a bit of explanation, and will make it clear what the previous bunch of actions were for. %DATE is Tasker’s built-in variable for the date. It’s in a specific format, the same as the device’s system settings – hence why there are multiple versions of the task download based on the date format used. %Eventdate31%Eventdate2-%Eventdate1 takes the day, month, and year that we got from actions 6-7 and rearranges them to match the format that %DATE is in. That way, we’re able to compare the current date (%DATE) with the date of the next event, even though they’re originally in different formats! After action 9, we have a variable %Samedayevent that’s either “no” (if the If condition in 9 wasn’t met) or “yes” (if it was). This variable is a setting that we will use later to control whether or not the Say action mentions the next event. Note that like I said, this task was originally created for someone who wanted this specific feature. Many people would prefer that it lists the next event no matter if it’s not on the same day. It is however a great example of how you can process a mess of data into something that’s even in the same format that Tasker is used to. Action 10: With action 10, we’re done with the actions that check to see if the event is on the same day. Instead we’re back to dealing with our original variable, %Calendar. We made a copy of this in the beginning, which we then split out to eventually get the date of the event, and now we’re going to work with the original. In this case I don’t think it would have mattered if we hadn’t copied it to begin with, but it’s always good practice to do it to be sure.

Anyways, action 10 does a Variable Split of %Calendar with the splitter . This is the text that immediately precedes the title of the event, and even though it’s not unique (it’s used once earlier in the source text), it’s ok to use it this time because there will always only be one occurrence of that text before the one we want. That just means that instead of using the %Calendar2 child, we use %Calendar3. Action 11: Does a Variable Split of %Calendar3 with the splitter . This is just for cleaning up the garbage text at the end of %Calendar3, a procedure we’ve used many times by now. Action 12: Splits the variable %Ceventdate2 with the splitter T. We haven’t used the %Ceventdate “family” for a few actions now, but it’s still there for us to use. This time we’re after the time, not the date, so we’re starting over. The reason why we copied %Ceventdate2 to a new variable in action 5 was to be able to use it now. %Ceventdate2 is identical to the original %Eventdate, so its value starts with data in the format 2012-0912T21:30:00.000+02:00 as well. I believe we could have used %Eventdate32 directly instead of starting from this far back with %Ceventdate2, but the original task was made in somewhat of a hurry, and I don’t want to change the task in this example compare to the original article where it was a download only. Keeping track of all these child variables is a pain, and sometimes you get them mixed up. It is however better to be safe than sorry. Action 13: A real world example of Variable Section! Sections %Ceventdate22, which now contains data in the format 21:30:00.000+02:00*garbage*, to only be 5 characters long. That means we get the hours, the colon, and the minutes – the time, in other words. This is where the original example of Variable Section above comes from, and like I mentioned then, it saves us from having to reassemble the time like we would have had to do had we split it with a colon (as the colon is used in the time, too). Action 14-15: These two actions set the variable %Nextevent to either “Your first appointment today is %Calendar31 at %Ceventdate22″ or “You have no appointments scheduled for today”, depending on the value of %Samedayevent, which can be “yes” or “no.” These are frankly redundant as we could have put actions 8-9 here and have them do it directly, but again it has to do with this task being put together a bit too quickly. Action 16: The final action, the infamous Say which actually turns 15 actions worth of work into a spoken message. Simply tells us the value of %Nextevent, which was set in the two previous actions. The result is that it has a different message for a day without appointments, and of course the message is dynamic and has the title of the event (%Calendar31 from actions 10-11) and the time (%Ceventdate22 from actions 12-13). This task is long, and complicated, because of the use of different messages for different situations (event/no event). Without that feature, it would have been a matter of splitting out the event title, which is fairly simple (actions 10-12, basically). It’s often the minor details that take time, as this example proves, and sometimes that extra hassle isn’t worth it for some people. In conclusion Being able to process data in variable using Tasker opens up for a lot of possibilities, but there’s also a lot to keep track of when you’re splitting variables left and right. Keeping a steady hand, having the source text open for

reference, and debugging using a Flash action (see example 2) are essential for getting through this without going crazy in the process. In the next part of the guide I’ll cover some tips and tricks of using Tasker, things that didn’t really feel natural including in any of the previous parts but still deserve to be mentioned. Later on in the series I’ll do parts dedicated to examples of all sorts, so if you have a profile or task you just can’t figure out how to make, let me know and it might make it into an article as an example, like example 2 in this article did.

Beginner’s guide to Tasker, part 5: Tips & tricks Time in seconds Dealing with time can be annoying, as hours and minutes don’t exactly work that well with withnormal math. That creates something of a problem when a lot of Tasker actions/creations require you to find out when something occurs in terms of time from or until now, or between two points in time. Examples are the Calendar Insert action, which requires you to input the date and time in minutes from now, or my sleep mode profile, which tells me the time I slept. The solution is to use the smallest measurement of time we use normally: Seconds. Referring to all time as seconds allows you to apply normal math to time, like finding out how much time has passed since two dates weeks from one another by using simple subtraction. This, of course, requires that all time is converted to seconds. Actual measurements for time, such as minutes, hours, days, weeks, or months, can easily be converted with multiplication or division. There are 60 seconds in a minute, so 1000 seconds is 1000/60 minutes, and so on. Calendar dates, on the other hand, is another matter. After all, “how many seconds is today’s date” makes no sense in a traditional conversation. Luckily though, Tasker has a built in system that makes that statement make sense, by using its own chronology that started in January, 1970. All dates since then can then be expressed as a (large) number of seconds elapses since then. This number can then be accessed in two ways. The built-in variable %TIMES gives you the current date/time in seconds, similar to how %TIME and %DATE does it for actual time/date. You can also use the Variable Convert action, which I’ll talk more about below, to convert times and dates into this format. You then have the tools needed to apply math to time. The result will be in seconds, which you can convert to minutes, hours, days, weeks, etc, by dividing by 60, then 60 again, then 24, and so on to move through the formats. To take a concrete example, I mentioned my sleep mode profile. When that one is activated, it writes %TIMES to a user-created variable, %smactivation. When it’s deactivated, it does a simple (%TIMES-%smactivation)/3600, giving me %smduration. Dividing by 3600 is the same as dividing by 60 and then 60 again, converting seconds into hours. As such, %smduration is the total time (in hours) that the profile was active. Note that the result doesn’t convert decimals into minutes, meaning that it gives me 8.5 hours, not 8 hours 30 minutes. I could easily make it give me hours and minutes, but I understand either format just fine.

Variable Convert Variable Convert is an action everyone should be aware of. It can convert the contents of a variable into another format, given of course that it supports that particular conversion type. You have everyday things like feet to metres, more specialized things like hex to decimal, and the conversion I talked about above: Time in seconds. The latter is perhaps the most important conversion available in Variable Convert, and it even has four different conversion functions associated with it. Date Time to Seconds is the conversion function you have to use to convert into time in seconds. The Tasker user guide, available through that question mark in the bottom corner of the Variable Convert configuration screen, has an overview of what format the time and date has to be in to be compatible with Variable Convert, with perhaps the most straight forward being YYYYMMDD HH.MM. The date can be in there on its own, in which case the time is assumed to be 00.00, but converting just time requires you to specify a date, even if it’s today. Sometimes you’ll find yourself with a date that’s in another format than what Variable Convert wants, for instance if you pull data from a calendar online or similar source. This is where your skills in using Variable Split, Variable Section, and in some cases, math, comes in. As an example, let’s say that you have a %date in the format DDMMYYYY and want it to be in the format YYYYMMDD. A pretty simple way to do that would then be: 1. Variable Section Name: %date From 1, Length 2 Store result in %dd 2. Variable Section Name: %date From 3, Length 2 Store result in %mm 3. Variable Section Name: %date From 5, Length 4 Store result in %yyyy 4. Variable Set %newdate to %yyyy%mm%dd %newdate can then be used in Variable Convert. Note that some of Variable Convert’s accepted formats depend on the date format setting in your system settings. It’s important to remember that you have the tools to do practically anything to the value of a variable, and so the order of a date isn’t an impossible task. It is however also important to remember to check what input

an action like Variable Converts accept, and not just input anything thinking that it’s capable of ectracting the same information from something as you can. Time in seconds to date time The other three time/date related functions deal with converting back to a human readable format. The only difference between them is how much information the resulting variable contains. The image below shows the difference between the Date Time, Medium Date Time, and Long Date Time options.

A very typical use for this would be to return a human readable date after you’ve done some calculations with time in seconds. You could for instance make a task where you input a number of days from today, and then it returns what date that corresponds to. It would be as simple as adding X*24*60*60 (where X is the number of days, and the calculations turn that into seconds) to %TIMES, and running the resulting variable through Variable Convert. Variable Randomize Variable Randomize is the alpha and omega for making any part of Tasker random, but it’s not the most intuitive action out there. Looking at the options, you’ll see some fairly simple options for Name, Min, and Max. Simply put, it gives the Name variable a value between Min and Max. Sounds simple enough, but how on Earth do you use that to for instance read a random file, or random line in a text file? Well, it’s all about using Variable Randomize to give you that random number, and then use that number elsewhere. Many settings for other actions in Tasker allow you to use variables as the setting instead of a static value, and the key is to use these two features together. For instance, the Read Line option allows you to read a line from a text file. That line is specified by the option Line in the Read Line action. By first doing a variable randomize, and then using the created variable in the Line field, you end up reading a random line! This can be used in so many places, down to reading different files by giving the files names with numbers. It doesn’t stop there though. The Min and Max fields in the Variable Randomize action itself can be replaced with variables, which means that you can control the range of the randomize action remotely. An example of this in practice can be found in my random dinner picker, where the task looks like this: 1. Read File: File: dinner.txt To Var: %dinnertext

2. Variable Split: Name: %dinnertext Splitter: | 3. Variable Set: Name: %dinnerrandom To: %dinnertext(#) 4. Variable Randomize: Name: %dinnerno Min: 1 Max: %dinnerrandom 5. Variable Set: Name: %Dinnersuggestion To: %dinnertext(%dinnerno) The task starts out by reading the content of a text file, and splitting it by |. | has been intentionally added at the end of each line in the text file with the specific purpose of acting as a splitter. Splitting by it therefore gives us one variable for each line in the text file. Action 3 sets %dinnerrandom to %dinnertext(#). By adding (#) to the end of a base variable (aka an array) with lots of children (%dinnertext1, %dinnertext2 etc), you’re actually asking Tasker to insert the number of child variables in place of the variable. If the text file contains 5 lines, you get variables %dinnertext1-5, and %dinnertext(#) will be 5. This is a quick and dirty way of counting how many lines there are in the file, by counting how many variables were created when splitting. Action 4 does a Variable Randomize from 1 to %dinnerrandom. In other words, a range equal to the number of lines in the original text file. This gives us a random number that is guaranteed to be within the right range for the text file, even if the text file has been externally edited, since the range is determined by first reading the text file! Action 5 uses this randomly generated number to pick the corresponding child variable, and transfers that into a global variable. This variable can then be used in a Say action, Notification action, etc. By doing it this way, the task is completely independent of text file changes. You don’t need to update the task for every time you update the text file, as the task will count the number of entries itself, and pick a random number from that range. This saves you from having to change the Max field in Variable Randomize every time the number of lines in the text file changes.

Do Maths Both If conditions and variable manipulation allows for applying math to the situation. I mentioned a few uses for this above, with converting different measurements for time. The good news is that the approach is pretty straight forward: Use Tasker variables with numerical values in place of actual numbers (much like you use unknowns in math), and then use normal mathematical rules. The bad news is that you still need to know math to be able to do this, which in many cases can be a bigger challenge than anything else in Tasker. If you don’t know when to put something in parenthesis in math, Tasker won’t understand what you’re trying to do either. Math can in some cases also be used as a replacement for Variable Split/Variable Section, but you have to be careful when doing so. If you have a time in the format HHMM, like 1435, you can actually make that compatible with Variable Convert by dividing by 100. This gives you 14.35, which is a decimal number from a math perspective, but a time with a period as the separator between hours and minutes from a Variable Convert perspective. The reason why I say you have to be careful is that doing the same thing to a time with a zero at the beginning or end, like 0930, will result in 9.3, as you don’t store unnecessary zeros when doing math. Variable Convert won’t understand what 9.3 means in terms of time. You can run after it with If conditions for variable length and throw zeros at the end after the fact, but it quickly escalates into dozens of actions to cover all possibilities. Counting things Something as simple as counting something has a lot of uses in Tasker. You can for instance count incoming SMS, emails, the number of hours you’ve been at work, slept, or driven in your car. You can use this information in feedback to the user (notifications, Says), widgets, or to control/trigger actions and contexts. Variable Add is a very useful tool in these cases. It adds a specified numerical value to a variable every time the action is run, essentially making the variable a counter. If you tie this to a Event context, like Received Text, you have a system that adds to a variable every time something happens. When doing this, it’s important to remember to reset the variable, as well as when to do it. Never confuse such a counter with an app’s internal counter, as they don’t have to be the same. For instance, I can add a profile that counts how many SMS I’ve received by adding 1 to a variable every time I receive an SMS. If I then go into the SMS app and read SMS, the SMS app’s internal unread counter will reset, but the Tasker counter won’t. To reset the Tasker counter, I could for instance create a profile that sets the counter variable to 0 whenever the SMS app is opened, which then assumes that I opened the app to read the messages. If I leave the app without reading all the messages however, the counter will be off the mark again. Normally this isn’t a big problem, at least not if you keep up to date with reading all messages. Using Tasker like this isn’t as accurate as reading an app’s internal counter, but on the other hand, you can count pretty much anything that happens on your phone. You can also combine different counters, like combining missed calls, SMS, and emails into a single new events counter. Test The Test action is semi-hidden away in the Misc category. Test here refers to testing the value of something, like a variable, static data, or a file. There’s a long list of test types you can choose from, ranging from the length of a variable to the modification date for a file.

I don’t find myself using this action a lot, and when I do, it’s normally the Variable Length test type I use. This counts the number of characters in a variable, which can have uses in for instance Variable Section. The Test action is one of those actions you should know of and be familiar with so that you know to look there if you ever need one of its tools, just like Variable Convert. Don’t be afraid to use multiple task and profiles to accomplish something One thing that has surprised me from watching help requests for Tasker is how a lot of people feel a need to cram as much functionality into as few tasks and profiles as possible. It seems to come from wanting to keep Tasker organized and running smoothly, but often comes at the expense of actual functionality. I’ll use my sleep mode profile as an example once again. 98% of the time I trigger it by plugging in my charger, which Tasker can read using a power state context. Despite this, the profile isn’t triggered by that context. It’s triggered by a variable context, %Sleepmode, which in turn is set by a separate profile with the power state context. This means that plugging in the charge makes one profile set a variable, which in turn enables another profile. So, why use twice as many profiles as what’s seemingly necessary? The answer is simple: To make the main profile controllable with different methods. My Tasker based voice assistant, Nelly, also has the ability to set %Sleepmode, based on voice input containing “goodnight” and “good morning.” If the main profile had been tied to AC charging directly, I wouldn’t have been able to also control it using Nelly. I’ve mentioned the advantages of turning contexts into variables before, and this is exactly that. I should also remind everyone that adding multiple contexts to a profile makes the relationship between them AND, not OR. All the contexts have to be met, not either one or the other. There is no way to make this relationship OR, as there frankly is no reason to. Profiles tie contexts together with tasks, and the same task can be used by multiple profiles. You can therefore have two separate profiles, each with different contexts, tied to the same task, and still only have to edit one task. It might clutter up your Tasker a bit, but practically speaking, it makes no difference. Don’t confuse the lack of an OR relationship between different contexts with the relationship between several possible configurations of the same context, however. You can for instance have a single WiFi Connected context react to multiple different networks by using a slash in the configuration fields, like SSID. If you want a profile to be active both when connected to a WiFi network called Home and one called Work, you put Home/Work into the SSID field. Tasks can also be split into pieces, by using the Perform Task action to run other tasks as part of a task. This both helps keeps things organized and makes it possible to share action groups between tasks. An example is my widget update task. It contains actions that together pull in the necessary information and use it to update my Make Your Clock Widget widget. Updating the widget is something I need to do in multiple situations, including when the device boots, and when one of the values (of which there are several) used in the widget changes. Instead of inserting the same actions in all the different tasks, they’re all located in a separate task, which the other tasks can then call on using a single action. It saves you time both with initial setup and when you need to edit the actions. Speaking of editing actions, I have several rather complicated single actions in my Tasker. By complicated, I mean that there are many fields that are filled in, often with a lot of information, and perhaps even an If condition that adds even more. If you need the same action in multiple places you can of course copy and paste it, but you might

also consider giving those actions their own separate tasks, and using Perform Task to refer to them. That way, you only have to edit those complicated actions in one place to have the changes apply to everywhere it’s used. Heck, it doesn’t even have to be a complicated action, just something that’s used in enough places to make any edits a pain, unless you can edit it in just one place. Back-to-back calendar events can overlap in Tasker The ability to have profiles be active when calendar events are is great, but there’s a “trap” with that system that is very easy to be caught in. If you have two calendar events that are back to back, say from 9.00-10.00 and 10.0011.00, you would perhaps assume that the first one would become inactive at the same time the second becomes active. That’s not the case. A calendar event lasting until 10.00 actually lasts until the time is no longer 10.00, which is at 10.01.00. From 10.00.00 to 10.00.59, both the above events are active, which causes the collision. To avoid this, back-to-back events have to be set up so that one event ends a minute before the other begins, in this case 9.59. The event will then stop being active at 9.59.59, and the second event will become active at 10.00.00. Notification contexts There are a few handfuls of apps that are integrated with Tasker, on top of whatever Tasker can get from the system. That still leaves a lot of apps and services that Tasker doesn’t have direct access to. The Notification event context can often help in such situations, allowing Tasker to react to notifications created by other apps, assuming Tasker has accessibility access (a setting in the main system settings). You can filter by what app sent the notification and the title of the notification, but unfortunately not the description. The notification title will also be stored in the built-in variable %NTITLE, allowing you to use it in Tasker. The usefulness of the title field depends on the app, and even the OS version. The Gingerbread Gmail app creates a different notification title than the ICS Gmail app, and neither really contain the info one would likely need (such as message subject, which is stored in the notification description). This means you can create profiles that act on notifications from Gmail, but forget about filtering them based on subject (K-9 mail is however an alternative email app that has the needed Tasker integration). Like I said, the usefulness of the notification title depends on the app and OS version. Furthermore, Tasker is only able to see the notification when it appears. There’s no State equivalent for ongoing notifications, which would be useful for long app installs, file uploads, syncs, and other processes that use ongoing notifications while active. Similarly, there’s no Even action for when a notification disappears. Blame Android. Even with these restrictions, the Notification event is great. I personally use it to customize Gmail email notifications based on location (visual at home, strong vibrations outside), and you can imagine similar uses with other apps. Delaying a profile’s activation/deactivation Sometimes you may not want your profile to activate or deactivate the very moment the context is met. A typical example would be if you have a WiFi Connected profile that you don’t want to deactivate if you move out of range for a few seconds, or perhaps you want your meeting profile to deactivate a few minutes after the calendar event context is over, giving you time to exit before sounds start coming. Delaying a task is simple with the Wait action, but

dealing with profiles like this is a bit trickier – but not much. Let’s assume you want to create a profile that is active when connected to a WiFi network, but you want to make it so that the profile doesn’t deactivate until the device has been disconnected for 5 minutes without having reconnected in the mean while. To do this, you want to make the actual trigger for the profile its own profile, with both an enter task and a named exit task. The enter task does a Set Variable %Wifiactive to 1, as well as a Stop action with the exit task’s name. The Exit task first does a Wait for 5 minutes, and then a Set Variable %Wifiactive to 0. You then create your original profile and use the Variable Value state context for %Wifiactive equals 1. What this does is to make your original profile triggered indirectly, by a variable set by another profile. That other profile contains the original context, but it’s that profile’s tasks that control the other profile. That way you can use the standard Wait action to actually delay the deactivation of the main profile by 5 minutes. If the device reconnects in those 5 minutes, the enter task’s Stop action will stop the exit task, which is important to avoid the Exit task completing and disabling the other profile despite the reconnection. In conclusion There are probably hundreds of tips and tricks that help with using Tasker, and these are just the ones that came to mind. If you have any to add, feel free to do so in the comments below.

Beginner’s guide to Tasker, part 6: AutoRemote What is AutoRemote? Mobile devices can communicate with one another, but in ways designed with the user in mind. SMS, email, video chat, IM, and so on are all services designed for the user, not the back end. AutoRemote on the other hand is a communication system designed for the devices to communicate, without the user having to be part of it. It allows messages to be sent between devices that have been registered as a group, instantaneous, and without bothering the user. Ever wish your phone could notify you of your tablet battery running low after days of being idle? AutoRemote gives the two the channel needed to communicate that kind of information. It does, however, not do so entirely on its own. While AutoRemote has grown beyond its original dependency on Tasker in some areas, it’s still very much a Tasker plug-in. After all, something has to manage the messages, act on them, and send them. Tasker already has the ability to collect practically any data, so with AutoRemote there to allow it to communicate that data to other devices, you have what you need to create setups that make iOS devices look like they’re from the last century. Getting started with AutoRemote AutoRemote can be had from Google Play for $1. Once installed and opened, it will fetch your personal URL, which will be in the format http://goo.gl/RandomCharacters. This URL is both used for registering your device with other devices, and for accessing AutoRemote’s web access. Opening the URL in a browser will present you

with a page where you can send messages to your device, as well as instructions for accessing AutoRemote’s second personal code, the key, which is used for some parts of the AutoRemote eco system. Back in the app, you can access the menu to get into the list of registered devices. Here you can register a new device by using the personal URL of that device, and this way connect devices together. You’ll have to do this on both devices in order for both of them to be able to send messages to the other. Any devices registered in this list will be available as an option when you go to send a message. Once this is done, AutoRemote’s Tasker-independent features will be ready to go. Try going into Google Play, go into an app page, select Share, and then remote open URL. This will open the same page on the other device, showing you that it’s set up correctly. Tasker context AutoRemote adds both contexts and actions to Tasker, so let’s start with the context. It’s available in Tasker’s State context category, under Plugins. There’s quite a few settings available in the configuration screen, so let’s go through them all. Plugin Options Event Behaviour: The AutoRemote context is a state by default, but as you can imagine, you’ll want it to behave as an event in many situations. Checking off this box does that. Note that Tasker still thinks the context is a state, just one that turns on and off quickly, so if you use this to change settings that Tasker normally revert automatically – like screen brightness – you need to uncheck “restore settings” in the profile options. Target: One of the methods for filtering messages. Specifying a target in the context and the message allows you to control which messages trigger the context without matching the message itself. Matching Options Message Filter: The main method for filtering messages. This one allows you to specify text that should be part of the message for it to trigger the context. It’s a partial match system, so “message” will match “this is a message.” Clear Message Filter: Clears the message filter, which isn’t the same as simply making the message filter blank, as that actually creates a blank message filter that will make it react to all messages. Case Insensitive: If checked, the message filter will be case insensitive Exact Message: Makes the message filter require an exact match, whereas the default is a partial match system as mentioned above. Use Regex: Allows you to ruse regular expressions in the message filter Tasker Vars Message: The name of the variable you want the message to be transferred into. Default is %armessage Comm Params Prefix: Part of a system to allow you to send more advanced commands using AutoRemote. The basic syntax for this is parameters=:=command. To use an example from AutoRemote’s Google Play description (also example 6 below), this can be used like this:

“ You can use AutoRemote with other Tasker conditions, such as the Date and Time conditions. Create a “shop=:=” command and combine it with a 5PM condition. Then, share your personal AutoRemote URL with your wife and have her send stuff she needs you to buy like “shop=:=carrots and ice cream”. Then, at

5PM your phone could say that list out loud: “You need to go shopping! You need to buy carrots and ice cream”

There can also be multiple parameters in a single message, separated by a space before the command separator =:=. This settings controls the name of the parameter variable(s), and the default is arpar. This system will be easier to understand with the examples further down. Command: Controls the name of the command variable created from using the =:= system. Main settings: For accessing AutoRemote’s general settings. Tasker action 1: AutoRemote Message The AutoRemote context helps you trigger profiles based on incoming messages, and the message action allows you to send messages. Like the context, it has a few options as well. Device: Select which device to send the message to, or, alternatively, a channel (see below) or the last sender. Device Type: Selected automatically based on the setting above Message: The message you want to send Channel: Channels are connection groups that multiple devices can join to be part of the same network. If this option is used, a channel connection will be made with the receiving device. This allows that device to simply reply to a channel instead of having to specify a device. Don’t confuse this with the Channel option under Device – this one allows you to send a message to a specific device and at the same time enable a channel, whereas sending a message to a channel sends a message to that channel. The description below from the AutoRemote developer might help understand channels better:

“ To better understand what a channel is, imagine channels as chatrooms. When you enter a chatroom, you start receiving all messages in that chatroom. The same happens with channels. Also, when you exit a chatroom, you stop receiving messages from it. Advanced settings Time To Live: The amount of time the system will try to deliver the message before it gives up Message Group: Allows you to make the message part of a message group, basically categorizing the message. You can then specify how to handle multiple messages from the same message group. An example would be if your tablet lets your phone know what it’s doing, but your phone has been off, so there are several such messages queued up, and you only want the last. Target: Corresponds to the Target option in the context Password: If AutoRemote has been password protected in the main app on the receiving device, you need to specify the password here for the message to get through. Send Message: Allows you to test send the message Tasker action 2: AutoRemote Channels The second available action is for managing channels. The available options are:

Name: Name of the channel to manage Device: All devices by default. If specified, the changes apply only to a specific device. Clear chosen device: Clears the above setting Enter of Exit: Makes the specified device enter or exit the specified channel Exit all: Makes the specified device exit all channels Apply now: Let’s you apply the settings right away instead of running the action. AutoRemote for Windows

There’s a program available for Windows computers that expands the AutoRemote network there. On its own, the program is very similar to AutoRemote on Android. You can add devices, send messages, and receive messages. URLs can be opened in a browser when received, and on top of that, you can create rules for incoming messages, similar to profiles in Tasker. This enables you to run commands upon receipt of certain messages, for instance by tying it to programs like nircmd.exe to use it to turn off your PC at night (which is what I do). AutoRemote EventGhost plugin The Windows program also has a tab which allows you to install and manage an EventGhost plugin. EventGhost can best be described as Tasker for Windows, a program that automates you computer in much the same way Tasker does your Android device. The way it works is similar, but still different enough that you basically have to learn an entirely new Tasker-like program to be able to use it properly. There’s an example further down which shows a very basic setup with EventGhost, but I can’t start going into EventGhost in detail here – especially since I haven’t used the program much myself. With the EventGhost plugin installed, there will be a couple of new actions available in EvenGhost. One is for registering EventGhost, which basically means that the action lets your AutoRemote network know that it’s there. It should be run on EventGhost startup, and will then make EventGhost an available device on your Android device. The other action is for sending a message. The options available here are identical to the other places you can send AutoRemote messages, so I won’t go into detail. Note that EventGhost has to be registered to the device you want to send messages to.

To actually trigger an EventGhost macro (similar to Tasker profile), you need the event that a message creates. The simplest way to get this is to set up the message you want to send from your device, set it to send to EventGhost, and then send it. This will make the event appear in EventGhost’s log, allowing you to drag it into a macro. Like I said, EventGhost is different enough from Tasker to be alien to new users, and I won’t turn this into a EventGhost guide. AutoRemote Chrome extension

AutoRemote also has a Google Chrome extension available. It’s relatively new, but the beta made a cameo in the video to example 2 in part 4 of this guide, where I open a URL on my phone by right clicking in my PC browser. The extension adds an option to send text to one of your devices when right clicking in Chrome, which you can use to send URLs or entire parts of a web page. Example 1: One device letting another know what it’s doing When I talked about how Android has ruined iOS for me, I mentioned that I’m expecting my phone to know that I’m on my iPad, and in turn let it notify me of emails instead of my phone. That was a reference to a very real possibility on Android, which uses Tasker and AutoRemote. Here’s how that would work. Option 1: When the tablet is in use at all Create a new profile in Tasker on the tablet. As the context, use the Display State option under State -> Display. Configure it for the screen being on. This makes the profile active when the tablet’s screen is on. As the enter task, add a AutoRemote Message action. Configure it to send the message “tabletstatus active=:=” to the phone. Then, add an exit task, and configure a similar message with “tabletstatus inactive=:=.” On the other device, create a new profile. Select AutoRemote, enable event behavior, and set message filter to “tabletstatus.” For the task, add a Set Variable %Tabletstatus to %arpar2. You will now have a global variable which will be either “active” or “inactive” based on the status of the tablet. You can now do what you want with that. If you have a email notification profile, you can for instance add a Variable Value %Tabletstatus matches inactive to it to make it stop triggering if you’re using your tablet. You could also add a Say action to the AutoRemote-triggered profile and make it say for instance “Tablet is now %arpar2,” which would give you a vocal message for when the tablet is in use. This latter example is shown in the video below (it might not be obvious that it’s the phone that speaks, but it is).

So what exactly is going on with all the =:= and %arpar2 and whatnot? Well, we want to send a message from the tablet that is unique to the screen on/off scenario, and we want it to contain information about the state of the tablet. By using messages in the format “tabletstatus (in)active=:=,” we’re activating AutoRemotes command system, which puts parameters before the =:= and commands after. We don’t need commands here, but we do need two parameters. The first (tabletstatus) is static, and simply lets us filter this particular message for use in the context on the phone. The second parameter is “active/inactive,” based on the state of the tablet. By enabling the command system with =:=, AutoRemote splits the message into (by default) %arpar and %arcomm variables. %arpar2 is the second parameter, which is here “active/inactive.” We can then transfer this “setting” to a global variable on the phone and use it elsewhere in Tasker, or we can simply use the local variable %arpar2 in the same profile (which is the case with the Say example). When the tablet turns on, the Display State On context becomes active, runs the enter tasks, which then sends a message to the phone that the tablet is active. When the screen turns off, the profile deactivates, and the exit tasks sends a message saying it’s inactive. In reality it’s such a very simply profile, but in practice, it gives one device the ability to act on the state of the other. Note that such a profile can become a nuisance if it’s constantly going off when you’re for instance just trying to check the time on your tablet. Part 5 of this guide covered how to set up profile delays properly, a system that should probably be implemented in a setup like this. Option 2: When a specific app or feature is being used Making the phone aware of when the tablet is in use is great, but what if you only want it to be aware of when specific apps or features are in use? The concept is practically the same as above, depending on what exactly you want it to be aware of. If you want your phone to know when your tablet is connected to a specific WiFi network, has headphones plugged in, or anything like that, then all you really need to do is switch out the Display State context on the tablet with whatever context fits. If you want it to be aware of when a specific app is being used, however, it’s a bit more complicated – but not much. Tasker has a built in variable for the so-called window label, which is the name of the window (i.e. app) that is currently being displayed. This variable is %WIN, and is updated as the window name changes. If you make a profile with the event profile Variable Set %WIN and tie it to an task with Flash %WIN as the action, you can move around your device and see the window name displayed as a flash message as you move between apps,

giving you an idea of how this works and what names are used for apps. It’s normally pretty straight forward, like Netflix’ window name being Netflix or Gmail’s window name being Gmail. Point is, there’s a variable that basically tells you what’s being displayed on the screen. By using the Variable Set %WIN context in place of the Display State context in the setup above, switching out “active” with %WIN” in the enter task, and deleting the exit task (since it becomes an event profile), you can make the tablet send the name of the active window to the phone. The %arpar2 variable will then be the active window, which you can use as a trigger for various things. An example would be to set the phone on silent if you’re using an ebook app on the tablet. Note that this particular method would send every single %WIN change to the phone. It’s a good idea to filter this somewhat before sending the message, to avoid it spamming the system. If you need your phone to know when your tablet is using Netflix, you can set it to only send the message if %WIN matches Netflix, rather than filtering it on the phone end. Example 2: Gmail notification that opens up Gmail on the PC Example 4 in part 3 of this guide showed how my Gmail notification system works. If certain contexts are met (such as being at home), it displays a Gmail logo on the screen when an email comes in. This can then be clicked to open the Gmail app on the phone. Since I posted that part though I added a long tap feature to the logo, an AutoRemote message to my PC for gmail.com. The task is almost identical to the tap task for opening the phone’s Gmail app (so see the original example for that), it just sends an AutoRemote message instead. That message automatically opens in the browser on the PC, which means that simply holding down on the Gmail logo when it pops up opens Gmail on the PC. This is a very simple system, but one I use a lot. When emails come in while I’m at home, I can either view them on my phone or my PC, all thorough the notification itself. Example 3: Forward notifications to a PC when it’s on This example is based on a setup that the AutoRemote developer himself uses. It uses AutoRemote and EventGhost to create a system where notifications are forwarded to the computer when it’s on. First you need to go into EventGhost. Select Configuration, Add Plugin, and find AutoRemote under Other. Configure it with a name, and add a device to the list of devices. Not right click the Autostart tree in the list and select Add Action. Find the Register EventGhost action under AutoRemote. Select the device you added, and enter “notification” as the channel. Click OK, and make sure it’s nested under Autostart. Next, add a macro. Give it any name. Right click the macro, select Add Event, and enter “AutoRemote.Message.osd” in the field. Finally, right click it again, select Add Action, and then Show OSD under EventGhost. Enter “Message from phone: {eg.event.payload.arcomm}” into the “text to display” box. Save the EventGhost configuration, then restart EventGhost.

Now go to Tasker on your device. Create a new profile, and select the Notification context under Event -> UI. Don’t add any filters to the configuration. As the connected task, create a new one, and add AutoRemote Message as the action. Select to send to channel as the device, then enter “notification” in the channel field further down. In the message field, enter “osd=:=%NTITLE.” Save out of Tasker, go into AutoRemote, and check that it’s set to drop PCs that can’t be reach from channels automatically (that should be the default setting anyways). That’s it. When the computer is on, the title of notifications on the phone will appear as a message on the PC. So, what’s going on here? The Register EventGhost action in EventGhost lets the device know it’s active, and by running it on startup, that happens when the computer turns on (assuming EventGhost is set to autostart). Macros as the profiles of EventGhost, and dropping events and actions into macros tie them together like contexts and tasks in Tasker. In this case, we have a event for an incoming message containing “osd” and an action to display an OSD (On Screen Display) that contains EventGhost’s version of the %arcomm variable from Tasker. This means that when a message starting with “osd” is received, it displays the command variable (the notification title in this case) on the screen. It’s easy to get confused here, because we’re not just in Tasker anymore. EventGhost uses different methods for events and actions, with variables in a completely different format. To really get the most out of making these two work together, you should probably read an EventGhost tutorial – which I won’t be writing, because I don’t know EventGhost very well myself. Example 4: PC letting an Android device know what it’s doing This example is similar to example 1, but with a PC as the device we’re checking in on. Assuming you’ve not messed too much with the default setup of EventGhost, the log on the side should show what happens on the computer from EventGhost’s point of view. This is a great feature, because it’s a list you can drag and drop events from! If you for instance switch to Skype, the log will show the event “Task.Activated.Skype.” Assuming you did the steps in example 3 to activate the plugin and register EventGhost on startup, it’s now very simple to use these events. Add a new macro, give it a name, and then drag and drop the event you want from the log and into the macro. If you want to send your device a message when you’re using Skype, the “Task.Activated.Skype” and “Task.Deactivated.Skype” events are the ones you want, as an example. Next, right click the macro, and select to add an action, then find Send Message under AutoRemote. Send whatever message you want to send, you know the drill by now. For my Skype example, I simply made the message “skypeon.” Now, in Tasker, create your profile. Use AutoRemote as the context, and filter the message by whatever you made the message “skypeon” in my case. Make the task whatever you want to do – the point of this example is the EventGhost/AUtoRemote end, not what you do with it in Tasker. A possible use for this can for instance be if you play online games and want the phone to for instance be quiet or use louder notifications when you’re doing that. You’d then make AutoRemote set a variable based on a message from EventGhost, trigger a silent profile based on that variable, and reset the variable using a message for when the computer program closes. Again you might get a use for the delay system from the previous guide in order to avoid having quick window switching trigger profile changes. Example 4.1: Turn you phone into an automatic control pad for specific computer programs

This is more of a tip than an example, but I thought I would include it. Both EventGhost and NirCmd allows you to send keypresses to the system, and both of those can be used via AutoRemote (NirCmd directly from the AutoRemote Windows program). By using scenes, you can create custom interfaces with buttons that send AutoRemote messages to your computer, which then trigger keyboard input there. Imagine having a Photoshop scene that has buttons for copy, paste, levels, select, and whatever other tools you need as buttons in the scene. By tying this to a system where the computer notifies the device when Photoshop is running, you can create a scenario where starting up Photoshop on your computer automatically makes a control panel for it appear on your phone. Example 5: Copy text from Chrome to a device’s clipboard I mentioned the Chrome extension above, which I have had installed for quite a while now. As per the AutoRemote dev’s suggestion, I set it up so that I can copy text from Chrome on my computer directly into the clipboard on my phone. When you have the Chrome extension installed, register your device, make a new rule, and then set command name to “Copy,” and the command to “copy.” Next, go into Tasker, and create a new profile. Add the AutoRemote context, and set “copy=:=” as the message filter. Select Event Behaviour. Tie the context to a new task, and find the Set Clipboard action under Misc. Put %arcomm in the text field for this action. With all this configured, you should have a new option for AutoRemote where you can copy the selection or open URLs on registered devices. Example 6: Remote access todo list EventGhost and Chrome extensions are all good, but it’s important to not forget what started AutoRemote: Web access. That personal URL you get can be entered into a browser to give you a page that allows you to send messages to the device from any web browser, which is much easier than needing special software. One of the examples on the Google Play page for AutoRemote is a scenario where a wife sends grocery list items to her husband, which will then be spoken out loud when he leaves work. Such a scenario is actually quite easy to set up. Make a new profile in Tasker, add the AutoRemote context, and set the message filter to “shop.” Add a task with a Say action with “You need to go shopping! You need to buy %arcomm” as the text, and then add a second context for the time the person leaves work (the time you want the message to play) in the same profile. The message should now play at that time, and the message (grocery list) can be added to by using the web interface to send “shop=:=shopping items here” to the device. Note that this is a “dumb” version of such a system, where only the latest message will be read, it’s time based, and so on. By using methods from previous articles you can store any new list items in an actual list, add to that list with new messages, and have the message play based on for instance leaving a WiFi network rather than a specific time. In conclusion The guide continues on in part 7. More parts will come eventually, though at a much slower pace. You can follow any Tasker coverage by using this link or this RSS feed. Download: Google Play

Beginner’s guide to Tasker, part 7: Variable arrays

What’s an array? Arrays are common in many areas, from mathematics to programming. In Tasker, an array can be described as a base variable which have several child variables. When you use Variable Split on the variable %Hello, you end up with a bunch of child variables like %Hello1, %Hello2, %Hello3, etc. %Hello is then an array with several elements, each element being a variable in itself. So far nothing new, perhaps with the exception of the terminology – we’ve been using child variables throughout the guide. Each element in an array is a variable, so it can be used as a variable, which is how we’ve been using arrays for so long without calling them that. However, what makes arrays special is what you can do with them in addition to what you can do with normal variables. Because variables in an array is arranged in a way that can very easily be referenced, we suddenly have a whole new set of tools that we can use to manipulate the variables on an array level, rather than treat them as individual variables. To use arrays, you need to get out of the mindset as variables as single entities. When referring to an array, it’s common to either refer to them by their base variable (like %Hello) or in the format %Hello(). The former is accepted as the input into several array-specific action settings in Tasker, some of which we’ll look at later. %Hello() on the other hand will list the value of each variable in the array, separated by a comma. If you were to split %ingredients = sugar.milk.flour by the period, you’d end up with the array %ingredients containing %ingredients1 = sugar, %ingredients2 = milk, and %ingredients3 = flour. Adding a Flash action for %ingredients would then flash sugar.milk.flour, because the value of the single variable %ingredients is still sugar.milk.flour. Flashing %ingredients() however would tell Tasker to take the value of each child variable and separate them with a comma, so you’d get sugar,milk,flour. If you were to clear the variable %ingredients and repeat the flashes, you’d get an empty %ingredients on the first, and the same sugar,milk,flour on the second. This is because the array remains even though you cleared the variable that created it in the first place. If you similarly were to clear the array %ingredients, the first flash would be unaffected, while the second would just flash empty variables.

This can be a bit confusing, because %ingredients can refer to the single variable %ingredients or the array %ingredients. Perhaps the most common mistake when dealing with arrays is to refer to one when you mean the other, causing whatever you do to be based off a single variable instead of an array, or vice versa. Referring to arrays Since arrays are numbered lists of variables, you get some new ways to refer to them. The list of these ways are available in the official user guide, so I’ll just quote them here: If the four variables %arr1, %arr2, %arr3, %arr4 hold respectively a, b, c and d then we have an array with 4 elements. These variables can be used just like any other, however it is also possible to access them in special ways. Here are some examples: 

%arr(#) The number of defined array elements (4 in this case)



%arr(#>) The index of the first defined array element, or 0 if none are defined (1).



%arr(#) The contents of the first defined array element (a)



%arr( 0 o

Menu, Title: Delete %Gtselectedd items?, Item 1: Yes (Variable Set %Gtcd to 1), Item 2: No (*nothing*) o

If %Gtcd matches 1 

For, Variable: %gendelete, Items: %Gtselected() 

Variable Add, Name: %gendelete, Value: 1



Variable Subtract, Name: %gendelete, Value: %shuffle, If %shuffle doesn’t match *shuffle* 

Array Pop, Variable: %Gentodo, Position:



Variable Add, Name: %shuffle, Value: 1

%gendelete

o 

End If



Variable Set %Gtcd to 0



Variable Clear: %shuffle



Variable Set: Gtselectedd to 0



End For



Write File, File: gentodo.txt, Text: %Gentodo()

End If

So, lots of nested stuff here. The first If simple makes sure that there are selected items before you try to run some delete task on them. Keen eyes may have noticed that while we reset %Gtselectedd in the launch task,

there’s no Variable Clear for %Gtselected. That means that the last values in the %Gtselected array persists, however, because the entire delete task is nested in an If for %Gtselectedd (which is reset every time), we won’t ever get a situation where we accidentally delete last time’s selected items. On top of that, it effectively disables the Long Tap task if nothing is selected. The Menu action that sits as the first action in the If group must not be confused with the menu scene element that I’ve referred to so many times. This action simple creates a new pop-up box using the standard menu action, in this case with Yes and No items in order to create a simple confirm dialog. Clicking Yes sets a variable that the following If group is dependent on. That variable is also reset at the end of the task, so that it’s always 0 unless you click Yes to confirm deletion. Next we have our For loop. It runs the four nested actions once for each element in the array %Gtselected. The Items field here wants a comma separated list, not necessarily an array, so we give it the %Gtselected() form. For each element in the %Gtselected array, the value of that element will be written to %gendelete, used in the following four actions, and then it goes on to the next element, putting its value in %gendelete, and so on. As for the four nested actions, the first simply fixes a “developer brain fart.” Right now, menu items start at 0, while array elements start at 1. So, the value of array element 1 is the same as menu item 0. This will be fixed soon according to the Tasker developer:

“ Will fix that, it should be the same as the tap indices obviously. It’s going to cause problems for some people’s scenes, but it’s too silly to leave like that. By adding 1 to %gendelete, which in turn contains the number for the selected menu item, we bring that number up to the level of the array, so that menu item 1 is the same as array element 1. When those two match, it becomes very easy to remove things from the array, using the third action in the For loop, Array Pop. By simply using Array Pop with %gendelete as the position, we pop out the array that’s in that position in the list. The other elements in that array then get pushed down so that if you remove the third array element in a five element array, number four becomes number three. Wait, you skipped an action! Yes, on purpose. The second action in the For loop, combined with the fourth, fixes an inherent issue with this system. The first time the loop runs, the array element numbers will match the menu item numbers, once we have added 1 to compensate for the difference in starting position. However, because all the array elements get pushed down when we remove an element, the numbers won’t match after the first time! Let’s say we have 10 items in the list/array, and we select number 3 and 5. %select_indices will then show 3,5 (always in order, no matter which one you select first). The For loop then pops element 3 from the array, leaving us with 9 elements, where the previous number 5 is now number 4. When the For loop then comes around to pop number 5, it pops what was number 6 when you selected the items To fix this problem, we add 1 to %shuffle at the end of each loop. %shuffle then represents the number of times the list has been shrunk. The Variable Subtract action in spot two of the group subtracts this number from the number of the element we’re going to pop, but only if %shuffle actually has a value (the If condition takes care of this). If we delete 5 items, then the number of the fifth item will have to be adjusted down by 4 in order to match up. When the loop is done looping, it’s time to write the changes to the file. Unlike the first version of the todo list, we here overwrite the entire file, because we have all the information in the array – so the file is outdated. By writing %Gentodo() to the file, we write a comma separated list of items to it. When we then read that back into a variable, and then split to an array the next time we open the scene, we simply split by the comma.

At this point we end both our If groups and move to the three actions that can always run, if only for the sake of it. We essentially clear %Gtcd, %shuffle, and%Gtselectedd, so that they’re ready to go next time. I didn’t actually think %shuffle needed clearing since it’s a local variable, but it turns out that if you were to delete something in several batches while in the scene, %shuffle would continue counting with the last used value if not cleared. The scene: Selected item indicator There’s a text field on the bottom of the scene showing “%Gtselectedd items selected.” It’s as simple as that. The scene: New item button The button to add a new item isn’t very complicated. The Tap tab task looks like this: 

Variable Query, Title: New item, Variable% gentoadd



If %gentoadd doesn’t match *gentoadd* o

Array Push, name: %Gentoadd, Position, 9001, Value:

o

Write File, File: gentodo.txt, Text: %Gentodo()

%gentoadd



End If

This task is simple. It starts by using the Variable Query action to ask the user for the title of the item to add. It then does an If check to see if something was actually entered into the variable. If so, it uses Array Push to add that to the array. By specifying a very high position (it’s over 9000), you’re pretty much guaranteed that the array is smaller than that, and in those cases, it simply adds it after the last one. So, if you have a 10 element array, then add a new item, it will become number 11, not number 9001. After that, it writes the changed array to the file. A nice side effect of using arrays is that when the file contents are read into the variable, a comma that you put in is treated the same as a comma that originally separated array elements. This allows you to add multiple items in one go by adding an item in the format 1,2,3,4,5. Once added, it will show as a single list item with all numbers in one, but when the list is refreshed (scene destroyed, relaunched) each of the items seperated by a comma will be its own item. This does mean you can’t use commas in the titles as the title will then be split, but I think the benefit of being able to add a bunch of items in one go makes up for that. The scene: Refresh button Alerts This is my generic list, which is new (I used to just use a widget), but the three other lists I have (home, shopping, morning) also use this new array system. The basic concept is the same, just slightly different to accommodate three lists in the same scene. Those three lists all have different alerts, so you’d assume that those needed changing – but they don’t really. They all work by reading the contents of the file, checking to see if there’s anything in the file, then acting based on that. Items are now separated by a comma instead of line shift, but that doesn’t affect the alert systems. AutoRemote integration All my todo lists can now be added to remotely from AutoRemote. This system had to be changed when I redid the todo system itself. The format for adding is the same, i.e. “todo tag=:=item name,” just with the addition of a

generic/universal list tag. The task that activates upon receiving a message in that format then has four If groups that are all identical except for the variables and file paths being adapted to each list. The If condition for each group is then a match with the appropriate tag. For the universal list, this group looks like this: 



If %arpar2 matches generic/universal o

Read File, File: gentodo.txt To Var: %Gentodo (reads my generic todo list text file into a variable)

o

Variable Split %Gentodo, Splitter: ,

o

Array Push, name: %Gentoadd, Position, 9001, Value: %arcomm

o

Write File, File: gentodo.txt, Text: %Gentodo()

End If

By now you know what all of these do as they’ve been used before. The only real difference is that it pushes %arcomm into the array instead of %gentoadd. Like I said, there are four such groups in the same task, one for each of my four lists. At the end, independent from the If groups, is this: 

Say “Item added to %arpar2 list”

AutoRemote Chrome integration

So far I’ve only used the AutoRemote Chrome plugin to copy text from my browser to my phone. I thought I would make it easier to add items to my list, so I simply added a bunch of rules to the Chrome plugin. Each rule has a name that doesn’t really matter, and a command like “todo shopping.” This then allows me to select text in Chrome, right click, and send to my todo list (receiving end is the same as above). It’s a very handy option to have, as I can just go to any search field (like on google.com), type something in, right click it, and send to any of my lists. Video

Update: Tasker beta 1.3.2b2 and above Turns out that the array/menu numbering difference and the deselect bug have both been fixed in the latest Tasker beta, which means that the next release version will also have them fixed. The change in the todo list is that you don’t add 1 to %gendelete with the fix, and the Item Tap tab task in the menu scene element should be like this: 



If %select_indices doesn’t match *select* o

Variable Set %Gtselected to %select_indices

o

Variable Split %Gtselected, Splitter: ,

o

Variable Set %Gtselectedd to %Gtselected(#)

Else o



Variable Set %Gtselectedd to 0

End If

In conclusion Arrays and For loops can save you a lot of hassle. Right now there’s something of an issue with global arrays and menu scene elements, where the whole thing slows down significantly because the global variables have to be set all the time. It doesn’t matter much on a small todo list, but in a later article I’ll show how to make a Tasker-based file browser, where it does matter. I originally made such a browser using arrays and found it to be extremely slow, and after some help from another Tasker user, it turned out that arrays were extremely inefficient in that particular situation. There may very well be a V3 of this list somewhere down the line, as I already know several ways to speed it up. Even so, the current iteration works great, at least for my use.

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF