### Miscellaneous Tasker utility functions Source: https://tasker.joaoapps.com/invoketasks.html Utility methods for checking permissions, installation status, and retrieving the installation intent. ```java static boolean havePermission( Context c ); ``` ```java static boolean taskerInstalled( Context c ); ``` ```java static Intent getTaskerInstallIntent( boolean marketFlag ); ``` -------------------------------- ### Tasker Installation Intent Source: https://tasker.joaoapps.com/code/TaskerIntent.java Creates an intent to direct the user to the Tasker installation page on the market or download site. ```java public static Intent getTaskerInstallIntent( boolean marketFlag ) { return new Intent( Intent.ACTION_VIEW, Uri.parse( marketFlag ? ( ( SDKVersion() == CUPCAKE_SDK_VERSION ) ? TASKER_MARKET_URL_CUPCAKE : TASKER_MARKET_URL ) : TASKER_DOWNLOAD_URL ) ); } ``` -------------------------------- ### Install Tasker via ADB Source: https://tasker.joaoapps.com/download.html Use these commands to install the Tasker APK file from a computer using Android Debug Bridge. ```bash adb install Tasker.xxx.apk ``` ```bash adb install -r Tasker.xxx.apk ``` -------------------------------- ### getTaskerInstallIntent(boolean marketFlag) Source: https://tasker.joaoapps.com/invoketasks.html Retrieves an intent to prompt the user to install Tasker. ```APIDOC ## getTaskerInstallIntent(boolean marketFlag) ### Description Returns an Intent that can be used with startActivity() to direct the user to the Tasker installation page. ### Parameters - **marketFlag** (boolean) - Determines if the intent points to the Android market or a download page. ``` -------------------------------- ### Get Hints Bundle Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Retrieves or creates the hints bundle from an intent. ```java private static Bundle getHintsBundle( Intent intent, String funcName ) { Bundle hintsBundle = (Bundle) getExtraValueSafe( intent, EXTRA_HINTS_BUNDLE, Bundle.class, funcName ); if ( hintsBundle == null ) { hintsBundle = new Bundle(); intent.putExtra( EXTRA_HINTS_BUNDLE, hintsBundle ); } return hintsBundle; } ``` -------------------------------- ### Define Command Filter Source: https://tasker.joaoapps.com/commandsystem.html Example of a command string used to trigger an action. ```text launchapp=:=Chrome ``` ```text launchapp=:=* ``` ```text %app ``` ```text launchapp=:=Gmail ``` -------------------------------- ### Access external preferences intent Source: https://tasker.joaoapps.com/invoketasks.html Example of how to open Tasker's external access preferences. ```java startActivity( TaskerIntent.getExternalAccessPrefsIntent() ) ``` -------------------------------- ### Get Setting Variable Keys and Encoding Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Retrieves variable replacement keys or keys associated with a specific encoding. ```java public static String [] getSettingVariableReplaceKeys( Bundle fromPluginEditActivity ) { return getStringArrayFromBundleString( fromPluginEditActivity, Setting.BUNDLE_KEY_VARIABLE_REPLACE_STRINGS, "getSettingVariableReplaceKeys" ); } ``` ```java public static String [] getKeysWithEncoding( Bundle fromPluginEditActivity, Encoding encoding ) { String [] toReturn = null; if ( Encoding.JSON.equals( encoding ) ) toReturn = getStringArrayFromBundleString( fromPluginEditActivity, TaskerPlugin.BUNDLE_KEY_ENCODING_JSON_KEYS, "getKeyEncoding:JSON" ); else Log.w( TAG, "Host.getKeyEncoding: unknown encoding " + encoding ); return toReturn; } ``` -------------------------------- ### Configure Host Capabilities and Completion Intents Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Methods for hosts to communicate supported capabilities to plugins and define completion signals for synchronous execution. ```java public static Intent addCapabilities( Intent toPlugin, int capabilities ) { return toPlugin.putExtra( EXTRA_HOST_CAPABILITIES, capabilities ); } ``` ```java public static void addCompletionIntent(Intent fireIntent, Intent completionIntent, ComponentName callService, boolean foreground) { if (callService != null) { completionIntent.putExtra(Setting.EXTRA_CALL_SERVICE_PACKAGE, callService.getPackageName()); completionIntent.putExtra(Setting.EXTRA_CALL_SERVICE, callService.getClassName()); completionIntent.putExtra(Setting.EXTRA_CALL_SERVICE_FOREGROUND, foreground); } fireIntent.putExtra( Setting.EXTRA_PLUGIN_COMPLETION_INTENT, completionIntent.toUri(Intent.URI_INTENT_SCHEME) ); } ``` -------------------------------- ### Implement Basic Tasker Action Source: https://tasker.joaoapps.com/pluginslibrary.html Create a helper, configuration activity, and runner class to implement a simple action without input or output. ```kotlin import android.app.Activity import android.content.Context import android.os.Bundle import android.os.Handler import android.os.Looper import android.widget.Toast import com.joaomgcd.taskerpluginlibrary.action.TaskerPluginRunnerActionNoOutputOrInput import com.joaomgcd.taskerpluginlibrary.config.TaskerPluginConfig import com.joaomgcd.taskerpluginlibrary.config.TaskerPluginConfigHelperNoOutputOrInput import com.joaomgcd.taskerpluginlibrary.config.TaskerPluginConfigNoInput import com.joaomgcd.taskerpluginlibrary.input.TaskerInput import com.joaomgcd.taskerpluginlibrary.runner.TaskerPluginResult import com.joaomgcd.taskerpluginlibrary.runner.TaskerPluginResultSucess class BasicActionHelper(config: TaskerPluginConfig) : TaskerPluginConfigHelperNoOutputOrInput(config) { override val runnerClass: Class get() = BasicActionRunner::class.java override fun addToStringBlurb(input: TaskerInput, blurbBuilder: StringBuilder) { blurbBuilder.append("Will show a toast saying 'Basic'") } } class ActivityConfigBasicAction : Activity(), TaskerPluginConfigNoInput { override val context get() = applicationContext private val taskerHelper by lazy { BasicActionHelper(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) taskerHelper.finishForTasker() } } class BasicActionRunner : TaskerPluginRunnerActionNoOutputOrInput() { override fun run(context: Context, input: TaskerInput): TaskerPluginResult { Handler(Looper.getMainLooper()).post { Toast.makeText(context, "Basic", Toast.LENGTH_LONG).show() } return TaskerPluginResultSucess() } } ``` -------------------------------- ### Zip a file using TaskerIntent Source: https://tasker.joaoapps.com/invoketasks.html Demonstrates how to construct a TaskerIntent with a specific action and priority, then broadcast it to Tasker. ```java if ( TaskerIntent.testStatus( this ).equals( TaskerIntent.Status.OK ) ) { TaskerIntent i = new TaskerIntent( "MY_ZIP_TASK" ); i.addAction( ActionCodes.ZIP_FILE ). // name of action addArg( "/sdcard/test.txt" ). // argument list addArg( true ). // delete original after addArg( 9 ). // compression level setTaskPriority( 9 ); // high priority sendBroadcast( i ); } ``` -------------------------------- ### taskerInstalled(Context c) Source: https://tasker.joaoapps.com/invoketasks.html Checks if the Tasker application is installed on the device. ```APIDOC ## taskerInstalled(Context c) ### Description Checks for the presence of the Tasker package on the device. ### Returns - **boolean** - True if Tasker is installed. ``` -------------------------------- ### Get Variables Bundle Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Extracts a bundle of variables from an intent received from the FireReceiver. ```java public static Bundle getVariablesBundle( Bundle resultExtras ) { return (Bundle) getBundleValueSafe( resultExtras, EXTRA_VARIABLES_BUNDLE, Bundle.class, "getVariablesBundle" ); } ``` -------------------------------- ### Encrypt a file and announce completion Source: https://tasker.joaoapps.com/invoketasks.html Shows how to chain multiple actions and register a BroadcastReceiver to handle task completion status. ```java Status status = TaskerIntent.testStatus( this ); switch ( status ) { case OK: TaskerIntent i = new TaskerIntent( "NEW_ENCRYPT_TASK" ); // Add actions i.addAction( ActionCodes.ENCRYPT_FILE ). // action code addArg( "/sdcard/test.txt" ). // argument list addArg( TaskerIntent.DEFAULT_ENCRYPTION_KEY ). // encryption key name addArg( false ); // leave key after i.addAction( ActionCodes.SAY ). // action code addArg( "Finished!" ). // speech text addArg( "com.google.android.tts:eng-gbr" ). // speech engine addArg( 0 ). // sound channel addArg( 5 ). // pitch addArg( 5 ). // speed addArg( false ); // continue task immediately // Setup a receiver to get a) when task finished b) success/failure // Note: you need to setup a new receiver for each task, because each // receiver is tuned to a particular broadcast task BroadcastReceiver br = new BroadcastReceiver() { public void onReceive( Context context, Intent recIntent ) { if ( recIntent.getBooleanExtra( TaskerIntent.EXTRA_SUCCESS_FLAG, false ) ) ; // success, do something else Log.w( TAG, "Tasker reports failure." ); unregisterReceiver( this ); }; // You probably want to unregister this if the user leaves your app e.g. in onPause // You may want to set a timeout in case e.g. Tasker's queue is full registerReceiver( br, i.getCompletionFilter() ); // Start the task. This call exits immediately. sendBroadcast( i ); default: Log.w( TAG, "couldn't run Tasker task: " + status ); } ``` -------------------------------- ### Tasker Status Verification Source: https://tasker.joaoapps.com/code/TaskerIntent.java Checks if Tasker is installed and configured to accept external intents. ```java public static Status testStatus( Context c ) { Status result; if ( ! taskerInstalled( c ) ) result = Status.NotInstalled; else if ( ! havePermission( c ) ) result = Status.NoPermission; else if ( ! TaskerIntent.prefSet( c, PROVIDER_COL_NAME_ENABLED ) ) result = Status.NotEnabled; else if ( ! TaskerIntent.prefSet( c, PROVIDER_COL_NAME_EXTERNAL_ACCESS ) ) result = Status.AccessBlocked; else if ( ! new TaskerIntent( "" ).receiverExists( c ) ) result = Status.NoReceiver; else result = Status.OK; return result; } public static boolean taskerInstalled( Context context ) { return ( getInstalledTaskerPackage( context ) != null ); } ``` -------------------------------- ### Retrieve Relevant Variables Source: https://tasker.joaoapps.com/plugins.html Use this in onCreate() to check if the host supports relevant variables and retrieve the list passed to the plugin. ```java if ( TaskerPlugin.hostSupportsRelevantVariables( getIntent().getExtras() ) ) String [] passedNames = TaskerPlugin.getRelevantVariableList( getIntent().getExtras() ); ``` -------------------------------- ### Assign and Retrieve Tasker Inputs Source: https://tasker.joaoapps.com/pluginslibrary.html Implement assignFromInput to populate UI elements and use inputForTasker to return values to Tasker. ```kotlin override fun assignFromInput(input: TaskerInput) = input.regular.run { editTextSeparator.setText(separator) checkboxSplit.isChecked = options.split } override val inputForTasker get() = TaskerInput(GetIPInput(editTextSeparator.text?.toString(), GetIPInputOptions(checkboxSplit.isChecked))) ``` -------------------------------- ### Get Package Version Code Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Retrieves the version code for a specified package using the PackageManager. ```java public static int getPackageVersionCode( PackageManager pm, String packageName ) { int code = -1; if ( pm != null ) { try { PackageInfo pi = pm.getPackageInfo( packageName, 0 ); if ( pi != null ) code = pi.versionCode; } catch ( Exception e ) { Log.e( TAG, "getPackageVersionCode: exception getting package info" ); } } return code; } ``` -------------------------------- ### Check and Get Requested Timeout Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Methods to verify if a timeout was requested and to retrieve the timeout value. ```java public static boolean haveRequestedTimeout( Bundle extrasFromPluginEditActivity ) { return extrasFromPluginEditActivity.containsKey( Setting.EXTRA_REQUESTED_TIMEOUT ); } ``` ```java public static int getRequestedTimeoutMS( Bundle extrasFromPluginEditActivity ) { return (Integer) getBundleValueSafe( extrasFromPluginEditActivity, Setting.EXTRA_REQUESTED_TIMEOUT, Integer.class, "getRequestedTimeout" ) ; } ``` -------------------------------- ### Check Host Capabilities Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Verifies if the host supports specific capabilities by checking flags within a Bundle. ```java private static boolean hostSupports( Bundle extrasFromHost, int capabilityFlag ) { Integer flags = (Integer) getBundleValueSafe( extrasFromHost, EXTRA_HOST_CAPABILITIES, Integer.class, "hostSupports" ); return ( flags != null ) && ( ( flags & capabilityFlag ) > 0 ) ; } ``` -------------------------------- ### Get Bundle Value Safe Helper Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Internal helper function to safely retrieve values from a bundle. ```java private static Object getBundleValueSafe( Bundle b, String key, Class expectedClass, String funcName ) { Object value = null; ``` -------------------------------- ### Configure REST Command and Template Sensor in Home Assistant Source: https://tasker.joaoapps.com/home_automation/home_assistant.html Add these lines to the /config/configuration.yaml file to enable REST commands for Tasker and define a template sensor for state tracking. ```yaml rest_command: tasker: url: 'http://{{ip_address}}:{{port}}/{{path}}' method: POST verify_ssl: false payload: "{{ event }}" content_type: 'application/json; charset=utf-8' template: - trigger: trigger: event event_type: tasker_event sensor: - name: Tasker State state: "{{trigger.event.data.state}}" ``` -------------------------------- ### Manage Plugin Timeout Hints Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Methods for adding, checking, and retrieving timeout configuration hints for plugin actions. ```java public static void addHintTimeoutMS( Intent toPlugin, int timeoutMS ) { getHintsBundle( toPlugin, "addHintTimeoutMS" ).putInt( BUNDLE_KEY_HINT_TIMEOUT_MS, timeoutMS ); } ``` ```java private static Bundle getHintsBundle( Intent intent, String funcName ) { Bundle hintsBundle = (Bundle) getExtraValueSafe( intent, EXTRA_HINTS_BUNDLE, Bundle.class, funcName ); if ( hintsBundle == null ) { hintsBundle = new Bundle(); intent.putExtra( EXTRA_HINTS_BUNDLE, hintsBundle ); } return hintsBundle; } ``` ```java public static boolean haveRequestedTimeout( Bundle extrasFromPluginEditActivity ) { return extrasFromPluginEditActivity.containsKey( Setting.EXTRA_REQUESTED_TIMEOUT ); } ``` ```java public static int getRequestedTimeoutMS( Bundle extrasFromPluginEditActivity ) { return (Integer) getBundleValueSafe( extrasFromPluginEditActivity, Setting.EXTRA_REQUESTED_TIMEOUT, Integer.class, "getRequestedTimeout" ) ; } ``` -------------------------------- ### Get Setting Result Code Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Retrieves the result code from a plugin completion intent, defaulting to UNKNOWN if not present. ```java public static int getSettingResultCode( Intent completionIntent ) { Integer val = (Integer) getExtraValueSafe( completionIntent, Setting.EXTRA_RESULT_CODE, Integer.class, "getSettingResultCode" ); return ( val == null ) ? Setting.RESULT_CODE_UNKNOWN : val; } ``` -------------------------------- ### Tasker Package Detection Source: https://tasker.joaoapps.com/code/TaskerIntent.java Determines the installed Tasker package name, accounting for historical differences between Play Store and non-Play Store versions. ```java public static String getInstalledTaskerPackage( Context context ) { String foundPackage = null; try { context.getPackageManager().getPackageInfo( TASKER_PACKAGE, 0 ); foundPackage = TASKER_PACKAGE; } catch ( PackageManager.NameNotFoundException e ) { } try { context.getPackageManager().getPackageInfo( TASKER_PACKAGE_MARKET, 0 ); foundPackage = TASKER_PACKAGE_MARKET; } catch ( PackageManager.NameNotFoundException e ) { } return foundPackage; } ``` -------------------------------- ### Host.addCapabilities Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Signals the host's supported capabilities to the plugin via an intent. ```APIDOC ## public static Intent addCapabilities(Intent toPlugin, int capabilities) ### Description Informs the plugin of the capabilities supported by the host. This should be called when sending intents to EditActivity, FireReceiver, or QueryReceiver. ### Parameters - **toPlugin** (Intent) - Required - The intent being sent to the plugin. - **capabilities** (int) - Required - One or more EXTRA_HOST_CAPABILITY_XXX flags. ### Returns - **Intent** - The modified intent with capabilities attached. ``` -------------------------------- ### Tasker Action and Profile Configuration Source: https://tasker.joaoapps.com/commandsystem.html Configuration for the Power Menu action and the corresponding profile that handles the command. ```text Setup Power Menu (168) A1: Power Menu Action [ ID:Smart App Action:Add/Edit Type:Button Title:Chrome Subtitle:Browse the Web Icon:content://net.dinglisch.android.taskerm.iconprovider/app/com.android.chrome Command:launchapp=:=Chrome ] ``` ```text Profile: Open App With Command (169) Restore: no Event: Command [ Output Variables:* Command:launchapp=:=* Variables:%app Last Variable Is Array:Off ] Enter: Anon (170) A1: Launch App [ Package/App Name:%app Data: Exclude From Recent Apps:Off Always Start New Copy:Off ] ``` -------------------------------- ### Define Tasker State Constants in Java Source: https://tasker.joaoapps.com/code/StateCodes.java Use these static integer constants to identify specific device states or sensor conditions when interacting with the Tasker API. Values starting from 1000 are reserved for plugin-specific implementations. ```java package net.dinglisch.android.taskerm; public class StateCodes { public static final int NONE = -1; public final static int FIRST_PLUGIN_CODE = 1000; // higher are all plugins public static final int ACTIVE_USER = 154; public static final int AUTO_SYNC = 135; public static final int VPN_CONNECT = 136; public static final int NFC_STATUS = 195; public static final int BT_STATUS = 2; public static final int BT_CONNECT = 3; public static final int BT_NEAR = 4; public static final int CALENDAR_ENTRY = 5; public static final int CELLS_NEAR = 7; public static final int POWER = 10; public static final int HDMI_PLUGGED = 12; public static final int POWER_SAVE_MODE = 14; public static final int DEVICE_IDLE = 16; public static final int HEADSET = 30; public static final int CALL = 40; public static final int KEYBOARD_OUT = 50; public static final int DOCKED = 80; public static final int AIRPLANE_MODE = 100; public static final int LIGHT_LEVEL = 103; public static final int PRESSURE = 104; public static final int MEDIA_BUTTON = 105; public static final int MAGNETIC_FIELD = 106; public static final int MISSED_CALL = 107; public static final int MOBILE_CONNECT = 110; public static final int ORIENTATION = 120; public static final int DISPLAY_ORIENTATION = 122; public static final int DISPLAY_STATE = 123; public static final int PROXIMITY = 125; public static final int BATTERY_LEVEL = 140; public static final int BATTERY_TEMPERATURE = 141; public static final int PROFILE_ACTIVE = 142; public static final int TASK_RUNNING = 143; public static final int SIGNAL_STRENGTH = 145; public static final int UNREAD_MESSAGE = 147; public static final int PEN_OUT = 148; public static final int PEN_MENU = 149; public static final int USB_CONNECT = 150; public static final int WIFI_CONNECT = 160; public static final int ETHERNET_CONNECT = 161; public static final int VARIABLE_VALUE = 165; public static final int WIFI_NEAR = 170; public static final int DREAMING = 175; public static final int TEMPERATURE = 180; public static final int HEART_RATE = 182; public static final int HUMIDITY = 185; //joaomgcd public static final int CUSTOM_SETTING = 186; public static final int ROOM = 187; public static final int DARK_MODE = 188; public static final int REACHING = 189; public static final int ANY_SENSOR = 190; public static final int PHYSICAL_ACTIVITY = 191; public static final int SLEEPING = 192; public static final int MATTER_LIGHT = 193; public static final int WORK_PROFILE = 194; public static final int DATA_USAGE = 196; public static final int COMPASS_ORIENTATION = 197; } ``` -------------------------------- ### TaskerCommand Kotlin Implementation Source: https://tasker.joaoapps.com/commandsystem.html Helper file to facilitate sending commands from an Android application to Tasker. ```kotlin import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build.VERSION import android.os.Build.VERSION_CODES const val PERMISSION_SEND_COMMAND = "net.dinglisch.android.tasker.PERMISSION_SEND_COMMAND" private const val EXTRA_COMMAND = "command" val Context.canSendTaskerCommand get() = if (VERSION.SDK_INT < VERSION_CODES.M) true else checkSelfPermission(PERMISSION_SEND_COMMAND) == PackageManager.PERMISSION_GRANTED fun Context.sendTaskerCommand(command: String) { if (command.isEmpty()) throw RuntimeException("Empty command") if (!canSendTaskerCommand) throw SecurityException("No permission to send Tasker Command") val intent = Intent().apply { setClassName("net.dinglisch.android.taskerm", "com.joaomgcd.taskerm.command.ServiceSendCommand") putExtra(EXTRA_COMMAND, command) } try { if (VERSION.SDK_INT < VERSION_CODES.O) startService(intent) else startForegroundService(intent) } catch (t: Throwable) { throw RuntimeException("Couldn't send command", t) } } fun Context.sendTaskerCommandNoExceptions(command: String) = try { sendTaskerCommand(command) true } catch (t: Throwable) { false } ``` -------------------------------- ### Clean and Check Relevant Variables and Hints Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Utility methods to check for, remove, or clean variables, hints, and timeout settings from bundles. ```java public static boolean haveRelevantVariables( Bundle b ) { return b.containsKey( BUNDLE_KEY_RELEVANT_VARIABLES ); } ``` ```java public static void cleanRelevantVariables( Bundle b ) { b.remove( BUNDLE_KEY_RELEVANT_VARIABLES ); } ``` ```java public static void cleanHints( Bundle extras ) { extras.remove( TaskerPlugin.EXTRA_HINTS_BUNDLE ); } ``` ```java public static void cleanRequestedTimeout( Bundle extras ) { extras.remove( Setting.EXTRA_REQUESTED_TIMEOUT ); } ``` ```java public static void cleanSettingReplaceVariables( Bundle b ) { b.remove( Setting.BUNDLE_KEY_VARIABLE_REPLACE_STRINGS ); } ``` -------------------------------- ### Define Tasker HTTP Request Blueprint Source: https://tasker.joaoapps.com/home_automation/home_assistant.html Create this blueprint file in /config/blueprints/automation/tasker/tasker.yaml to allow Home Assistant to trigger Tasker via HTTP requests when device states change. ```yaml blueprint: name: Tasker HTTP Request V2 description: Call Tasker when a device changes state (Revised) domain: automation input: ip_address: name: IP Address description: The IP Address of the Android device Tasker is running on default: "192.168." selector: text: port: name: Port description: The port the Tasker device is listening on (usually 1821) default: 1821 selector: number: min: 1 max: 65535 mode: box path: name: Path description: The path in the HTTP Request event condition that the Tasker device is listening on (usually 'home_assistant') default: "home_assistant" selector: text: target_devices: name: Devices description: The devices that should trigger the request selector: entity: multiple: true trigger: - trigger: state entity_id: !input target_devices action: - action: rest_command.tasker data: ip_address: !input ip_address port: !input port path: !input path event: > { "device_id": "{{ trigger.entity_id }}", "device_name": "{{ state_attr(trigger.entity_id, 'friendly_name') }}", "from": "{{ trigger.from_state.state }}", "to": "{{ trigger.to_state.state }}" } ``` -------------------------------- ### Add Action to TaskerIntent Source: https://tasker.joaoapps.com/code/TaskerIntent.java Initializes a new action bundle and attaches it to the intent using an incrementing index. ```java public TaskerIntent addAction( int code ) { actionCount++; argCount = 1; Bundle actionBundle = new Bundle(); actionBundle.putInt( ACTION_CODE, code ); // Add action bundle to intent putExtra( EXTRA_ACTION_INDEX_PREFIX + Integer.toString( actionCount ), actionBundle ); return this; } ``` -------------------------------- ### setVariableReplaceKeys(Bundle resultBundleToHost, String[] listOfKeyNames) Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Configures which bundle keys should have variables replaced by the host. ```APIDOC ## void setVariableReplaceKeys(Bundle resultBundleToHost, String[] listOfKeyNames) ### Description Indicates to the host which bundle keys should have variables replaced when the setting fires. ### Parameters - **resultBundleToHost** (Bundle) - Required - The bundle being returned to the host. - **listOfKeyNames** (String[]) - Required - The list of bundle keys to perform variable replacement on. ``` -------------------------------- ### addRelevantVariableList(Intent intentToHost, String[] variableNames) Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Specifies to the host which variables might be used by the plugin. ```APIDOC ### addRelevantVariableList(Intent intentToHost, String[] variableNames) ### Description Used in EditActivity before setResult() to inform the host about variables the plugin might use. ### Parameters - **intentToHost** (Intent) - Required - The intent being returned to the host. - **variableNames** (String[]) - Required - Array of relevant variable names. ``` -------------------------------- ### Task Configuration Methods Source: https://tasker.joaoapps.com/code/TaskerIntent.java Methods for setting task priority and adding parameters or local variables to the intent. ```java public TaskerIntent setTaskPriority( int priority ) { if ( validatePriority( priority ) ) putExtra( EXTRA_TASK_PRIORITY, priority ); else Log.e( TAG, "priority out of range: " + MIN_PRIORITY + ":" + MAX_PRIORITY ); return this; } public TaskerIntent addParameter( String value ) { int index = 1; if ( getExtras().containsKey( EXTRA_VAR_NAMES_LIST ) ) index = getExtras().getStringArrayList( EXTRA_VAR_NAMES_LIST ).size() + 1; Log.d(TAG, "index: " + index ); addLocalVariable( "%" + PARAM_VAR_NAME_PREFIX + index, value ); return this; } public TaskerIntent addLocalVariable( String name, String value ) { ArrayList names, values; if ( hasExtra( EXTRA_VAR_NAMES_LIST ) ) { names = getStringArrayListExtra( EXTRA_VAR_NAMES_LIST ); values = getStringArrayListExtra( EXTRA_VAR_VALUES_LIST ); } else { names = new ArrayList(); values = new ArrayList(); putStringArrayListExtra( EXTRA_VAR_NAMES_LIST, names ); putStringArrayListExtra( EXTRA_VAR_VALUES_LIST, values ); } names.add( name ); values.add( value ); return this; } ``` -------------------------------- ### hostSupportsVariableReturn(Bundle extrasFromHost) Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Checks if the host supports returning variables from the plugin. ```APIDOC ## hostSupportsVariableReturn(Bundle extrasFromHost) ### Description Indicates to the plugin whether the host will process variables which it passes back. ### Parameters - **extrasFromHost** (Bundle) - Required - Intent extras from the intent received by the QueryReceiver. ``` -------------------------------- ### hostSupportsSynchronousExecution(Bundle extrasFromHost) Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Checks if the host supports synchronous execution of the plugin. ```APIDOC ## boolean hostSupportsSynchronousExecution(Bundle extrasFromHost) ### Description Checks if the host supports synchronous execution of the plugin. ### Parameters - **extrasFromHost** (Bundle) - Required - The intent extras received by the edit activity. ``` -------------------------------- ### getHintTimeoutMS(Bundle extrasFromHost) Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Retrieves the timeout hint value set by the host for the action. ```APIDOC ## getHintTimeoutMS ### Description Check for a hint on the timeout value the host is using. Requires Tasker 4.7+. ### Parameters - **extrasFromHost** (Bundle) - Required - Intent extras from the intent received by the FireReceiver. ### Returns - **timeoutMS** (int) - The host's timeout setting for the action or -1 if no hint is available. ``` -------------------------------- ### Present Task Selection Dialog Source: https://tasker.joaoapps.com/invoketasks.html Launches a dialog for the user to select a task, returning the result to onActivityResult. ```java startActivityForResult( TaskerIntent.getTaskSelectIntent(), requestCode ); ``` -------------------------------- ### TaskerIntent Private Helper Methods Source: https://tasker.joaoapps.com/code/TaskerIntent.java Internal methods for managing random data, action bundles, and preference verification. ```java private String getRandomString() { return Long.toString( rand.nextLong() ); } ``` ```java private void setRandomData() { setData( Uri.parse( TASK_ID_SCHEME + ":" + getRandomString() ) ); } ``` ```java private Bundle getActionBundle() { Bundle toReturn = null; if ( argCount > MAX_NO_ARGS ) Log.e( TAG, "maximum number of arguments exceeded (" + MAX_NO_ARGS + ")" ); else { String key = EXTRA_ACTION_INDEX_PREFIX + Integer.toString( actionCount ); if ( this.hasExtra( key ) ) toReturn = getBundleExtra( key ); else Log.e( TAG, "no actions added yet" ); } return toReturn; } ``` ```java private void putMetaExtras( String taskName ) { putExtra( EXTRA_INTENT_VERSION_NUMBER, INTENT_VERSION_NUMBER ); putExtra( EXTRA_TASK_NAME, taskName ); } ``` ```java private static boolean prefSet( Context context, String col ) { String [] proj = new String [] { col }; Cursor c = context.getContentResolver().query( Uri.parse( TASKER_PREFS_URI ), proj, null, null, null ); boolean acceptingFlag = false; if ( c == null ) Log.w( TAG, "no cursor for " + TASKER_PREFS_URI ); else { c.moveToFirst(); if ( Boolean.TRUE.toString().equals( c.getString( 0 ) ) ) acceptingFlag = true; c.close(); } return acceptingFlag; } ``` -------------------------------- ### Check Host Relevant Variable Support Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Verifies if the host supports the relevant variables feature. ```java public static boolean hostSupportsRelevantVariables( Bundle extrasFromHost ) { return hostSupports( extrasFromHost, EXTRA_HOST_CAPABILITY_RELEVANT_VARIABLES ); } ``` -------------------------------- ### Set Variable Replacement Keys Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Specifies which bundle keys should have variables replaced by the host when the setting fires. ```java public static void setVariableReplaceKeys( Bundle resultBundleToHost, String [] listOfKeyNames ) { addStringArrayToBundleAsString( listOfKeyNames, resultBundleToHost, BUNDLE_KEY_VARIABLE_REPLACE_STRINGS, "setVariableReplaceKeys" ); } ``` -------------------------------- ### Host.addCompletionIntent Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Attaches a completion intent to a fire intent to signal the host when the plugin has finished execution. ```APIDOC ## public static void addCompletionIntent(Intent fireIntent, Intent completionIntent, ComponentName callService, boolean foreground) ### Description Adds an intent to the fire intent that the plugin can use to signal completion. This is intended for use when synchronous execution is required. ### Parameters - **fireIntent** (Intent) - Required - The fire intent going to the plugin. - **completionIntent** (Intent) - Required - The intent used to signal the host. - **callService** (ComponentName) - Optional - The service component to handle the completion. - **foreground** (boolean) - Required - Whether the service should run in the foreground. ``` -------------------------------- ### hostSupportsVariableReturn(Bundle extrasFromHost) Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Checks if the host supports processing variables returned by the plugin. ```APIDOC ## hostSupportsVariableReturn ### Description Indicates to the plugin whether the host will process variables which it passes back. ### Parameters - **extrasFromHost** (Bundle) - Required - Intent extras from the intent received by the FireReceiver. ``` -------------------------------- ### getSettingResultCode Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Retrieves the result code from a plugin completion intent. ```APIDOC ## public static int getSettingResultCode(Intent completionIntent) ### Description Retrieves the result code from the intent returned by a plugin when it finishes its execution. ### Parameters - **completionIntent** (Intent) - Required - The intent returned from the plugin. ### Returns - **int** - The result code of the plugin, or Setting.RESULT_CODE_UNKNOWN if not found. ``` -------------------------------- ### addHintTimeoutMS Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Informs a setting plugin of the timeout value the host is using. ```APIDOC ## public static void addHintTimeoutMS(Intent toPlugin, int timeoutMS) ### Description Adds a timeout hint to the intent being sent to a plugin. ### Parameters - **toPlugin** (Intent) - Required - The intent being sent to the plugin. - **timeoutMS** (int) - Required - The timeout value in milliseconds. ``` -------------------------------- ### hostSupportsRelevantVariables(Bundle extrasFromHost) Source: https://tasker.joaoapps.com/code/TaskerPlugin.java Checks if the host supports relevant variables. ```APIDOC ### hostSupportsRelevantVariables(Bundle extrasFromHost) ### Description Checks if the host supports relevant variables by inspecting the provided extras bundle. ### Parameters - **extrasFromHost** (Bundle) - Required - The extras bundle received from the host. ``` -------------------------------- ### Configure Output Class Source: https://tasker.joaoapps.com/pluginslibrary.html Specify the output class in the plugin configuration to define the return type for Tasker. ```kotlin override val outputClass = Array::class.java ``` -------------------------------- ### Define a Tasker Config Helper Source: https://tasker.joaoapps.com/pluginslibrary.html The Config Helper manages plugin configuration, such as input/output variables and the UI blurb. It must extend TaskerPluginConfigHelper. ```kotlin class HelloWorldHelper(config: TaskerPluginConfig) : TaskerPluginConfigHelperNoOutputOrInput(config) { override val runnerClass = HelloWorldRunner::class.java override fun addToStringBlurb(input: TaskerInput, blurbBuilder: StringBuilder) { blurbBuilder.append("This will show a toast saying 'Hello Tasker World'") } } ``` -------------------------------- ### Check Host Encoding Support Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Determines if the host supports a specific encoding type. ```java public static boolean hostSupportsKeyEncoding( Bundle extrasFromHost, Encoding encoding ) { switch ( encoding ) { case JSON: return hostSupports( extrasFromHost, EXTRA_HOST_CAPABILITY_ENCODING_JSON ); default: return false; } } ``` -------------------------------- ### Check for Synchronous Execution Support Source: https://tasker.joaoapps.com/code/TaskerPluginBeta.java Verifies if the host supports synchronous execution via the provided bundle extras. ```java public static boolean hostSupportsSynchronousExecution( Bundle extrasFromHost ) { return hostSupports( extrasFromHost, EXTRA_HOST_CAPABILITY_SETTING_SYNCHRONOUS_EXECUTION ); } ```