### LocalHTTPRequest Execution Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Executes an HTTP request from the watch via the phone companion app. Requires the AmazfitInternetCommunication app to be installed. ```APIDOC ## POST /request/execute ### Description Executes HTTP requests from the watch through the phone companion app. Requires the AmazfitInternetCommunication app to be installed on the phone. ### Method POST ### Response #### Success Response (200) - **responseCode** (integer) - HTTP status code - **responseBody** (string) - The content returned from the server #### Error Response (400/500) - **errorBody** (string) - Error details from the error stream ### Response Example { "responseCode": 200, "responseBody": "{\"temp\": \"20C\"}" } ``` -------------------------------- ### Implement Bidirectional Communication with Transporter API Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Demonstrates how to initialize the Transporter service, handle incoming data via DataListener, and send messages to a companion app. This implementation includes lifecycle management to ensure listeners are cleaned up correctly. ```java public class WatchActivity extends Activity { private TransporterClassic transporter; private Transporter.DataListener dataListener; private Transporter.ChannelListener channelListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize transporter with unique module name transporter = (TransporterClassic) Transporter.get(this, "com.myapp.watchphone"); // Setup channel listener to know when communication is ready channelListener = new Transporter.ChannelListener() { @Override public void onChannelChanged(boolean ready) { if (ready) { // Request initial data from phone DataBundle request = new DataBundle(); request.putString("request_type", "get_notifications"); request.putInt("limit", 10); transporter.send("fetch_data", request); } } }; transporter.addChannelListener(channelListener); // Setup data listener for incoming messages from phone dataListener = new Transporter.DataListener() { @Override public void onDataReceived(TransportDataItem item) { String action = item.getAction(); DataBundle data = item.getData(); switch (action) { case "notifications_response": int count = data.getInt("count"); String jsonData = data.getString("notifications"); processNotifications(jsonData); break; case "phone_battery_update": int batteryLevel = data.getInt("level"); updatePhoneBatteryDisplay(batteryLevel); break; case "sync_complete": showToast("Sync completed successfully"); break; } } }; transporter.addDataListener(dataListener); // Connect to transport service transporter.connectTransportService(); } // Send user action to phone private void dismissNotification(String notificationId) { DataBundle data = new DataBundle(); data.putString("notification_id", notificationId); data.putString("action", "dismiss"); transporter.send("notification_action", data, new Transporter.DataSendResultCallback() { @Override public void onResultBack(DataTransportResult result) { if (result.getResultCode() == 0) { refreshNotificationList(); } } }); } @Override protected void onStop() { super.onStop(); // Always clean up listeners and disconnect transporter.removeChannelListener(channelListener); transporter.removeDataListener(dataListener); transporter.disconnectTransportService(); } } ``` -------------------------------- ### Configure HTTP Request Parameters with LocalURLConnection in Java Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Shows how to configure HTTP request parameters using the LocalURLConnection class, mimicking Java's URLConnection. It supports various HTTP methods and custom headers, allowing for detailed control over outgoing requests. ```java // Create and configure a URL connection LocalURLConnection connection = new LocalURLConnection(); // Set the target URL try { connection.setUrl(new URL("https://api.example.com/data")); } catch (MalformedURLException e) { e.printStackTrace(); } // Configure request method (GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE) connection.setRequestMethod(LocalURLConnection.POST); // Set request options connection.setFollowRedirects(true); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); // Set timeout in milliseconds (-1 for no timeout) connection.setTimeout(30000); // Add custom headers connection.addHeader("Content-Type", "application/json"); connection.addHeader("Authorization", "Bearer token123"); connection.addHeader("X-Custom-Header", "custom-value"); ``` -------------------------------- ### Create Transporter Instance (Java) Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Creates a Transporter instance for communication between watch and phone apps. The module name must be identical on both devices for successful communication. Supports both standard and BLE transporters. ```java Transporter transporter = Transporter.get(context, "com.myapp.module"); Transporter bleTransporter = Transporter.getBLE(context, "com.myapp.module"); ``` -------------------------------- ### Execute HTTP Requests with LocalHTTPRequest in Java Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Illustrates how to execute HTTP requests from a watch through a phone companion app using LocalHTTPRequest. This requires the AmazfitInternetCommunication app on the phone and includes handling for successful responses, connection errors, and timeouts. ```java // Configure the request LocalURLConnection connection = new LocalURLConnection(); try { connection.setUrl(new URL("https://api.weather.com/current?city=London")); } catch (MalformedURLException e) { e.printStackTrace(); } connection.setTimeout(15000); // Execute the request with response handling LocalHTTPRequest request = new LocalHTTPRequest(this, connection, new LocalHTTPResponse() { @Override public void onResult(HttpURLConnection httpURLConnection) { try { // Read response - httpURLConnection doesn't need connect()/disconnect() int responseCode = httpURLConnection.getResponseCode(); String responseMessage = httpURLConnection.getResponseMessage(); if (responseCode == 200) { // Success - read the input stream InputStream inputStream = httpURLConnection.getInputStream(); String responseBody = IOUtils.toString(inputStream); // Update UI on main thread runOnUiThread(() -> displayWeather(responseBody)); } else { // Error - check error stream InputStream errorStream = httpURLConnection.getErrorStream(); String errorBody = IOUtils.toString(errorStream); Log.e("HTTP", "Error " + responseCode + ": " + errorBody); } } catch (IOException e) { e.printStackTrace(); } } @Override public void onConnectError() { // Companion app not installed or connection failed runOnUiThread(() -> showError("Please install AmazfitInternetCommunication on your phone")); } @Override public void onTimeout() { // Request timed out runOnUiThread(() -> showError("Request timed out")); } }); ``` -------------------------------- ### Perform HTTP Requests via LocalHTTPRequest Source: https://github.com/kieronquinn/amazfitcommunication/blob/master/README.md Demonstrates how to initiate an internet request from a watch app using the LocalURLConnection and LocalHTTPRequest classes. This implementation requires the AmazfitInternetCommunication app on the connected phone and handles responses asynchronously. ```java LocalURLConnection localURLConnection = new LocalURLConnection(); try { localURLConnection.setUrl(new URL("http://quinny898.co.uk/test.txt")); } catch (MalformedURLException e) { e.printStackTrace(); } LocalHTTPRequest localHTTPRequest = new LocalHTTPRequest(this, localURLConnection, new LocalHTTPResponse() { @Override public void onResult(HttpURLConnection httpURLConnection) { try { setText(IOUtils.toString(httpURLConnection.getInputStream())); } catch (IOException e) { e.printStackTrace(); } } @Override public void onConnectError() { setText(getString(R.string.error)); } @Override public void onTimeout() { setText(getString(R.string.timeout)); } }); ``` -------------------------------- ### Send Custom Actions via Transporter Source: https://github.com/kieronquinn/amazfitcommunication/blob/master/README.md Initializes the Transporter service and sends a custom action string once the channel is ready. Requires a unique module name consistent across both watch and phone applications. ```java transporter = Transporter.get(this, "example_module"); transporter.addChannelListener(new Transporter.ChannelListener() { @Override public void onChannelChanged(boolean ready) { if(ready)transporter.send("hello_world!"); } }); transporter.connectTransportService(); ``` -------------------------------- ### LocalURLConnection Configuration Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Configures HTTP request parameters including URL, method, headers, and timeout settings. ```APIDOC ## POST /connection/configure ### Description Configures HTTP request parameters similar to Java's URLConnection. Supports all standard HTTP methods and custom headers. ### Method POST ### Parameters #### Request Body - **url** (string) - Required - The target URL - **method** (string) - Required - HTTP method (GET, POST, PUT, DELETE, etc.) - **timeout** (integer) - Optional - Timeout in milliseconds - **headers** (object) - Optional - Key-value pairs for request headers ### Request Example { "url": "https://api.example.com/data", "method": "POST", "headers": { "Content-Type": "application/json", "Authorization": "Bearer token123" } } ``` -------------------------------- ### Configure Gradle Dependencies for Amazfit Communication Source: https://github.com/kieronquinn/amazfitcommunication/blob/master/README.md Instructions for adding the library JAR and the required Apache Commons IO dependency to an Android project's build.gradle file. ```gradle implementation fileTree(dir: 'libs', include: ['*.jar']) compile group: 'commons-io', name: 'commons-io', version: '2.0.1' ``` -------------------------------- ### Add Data Listener for Incoming Data (Java) Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Registers a listener to receive incoming data from the connected device. The listener receives TransportDataItem objects containing action strings and data bundles, allowing for processing of received information and sending acknowledgments. ```java transporter.addDataListener(new Transporter.DataListener() { @Override public void onDataReceived(TransportDataItem item) { String action = item.getAction(); Log.d("Transport", "Received action: " + action); if (action.equals("calendar_events")) { DataBundle data = item.getData(); String eventTitle = data.getString("title"); long eventTime = data.getLong("timestamp"); // Process received data displayEvent(eventTitle, eventTime); // Send acknowledgment back transporter.send("event_received"); } } }); ``` -------------------------------- ### Receive Custom Actions and Data Source: https://github.com/kieronquinn/amazfitcommunication/blob/master/README.md Registers a data listener to handle incoming TransportDataItem objects. It allows for parsing the action string and extracting associated DataBundles. ```java transporter.addDataListener(new Transporter.DataListener() { @Override public void onDataReceived(TransportDataItem transportDataItem) { Log.d("TransporterExample", "Item received action: " + transportDataItem.getAction()); if(transportDataItem.getAction().equals("hello_world")) { DataBundle receivedData = transportDataItem.getData(); } } }); ``` -------------------------------- ### Connect to Transport Service (Java) Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Initiates the connection to the transport service, which must be called before sending or receiving data. A ChannelListener is used to notify when the connection is ready for communication. ```java Transporter transporter = Transporter.get(this, "example_module"); transporter.addChannelListener(new Transporter.ChannelListener() { @Override public void onChannelChanged(boolean ready) { if (ready) { Log.d("Transport", "Channel is ready for communication"); } else { Log.d("Transport", "Channel disconnected"); } } }); transporter.connectTransportService(); ``` -------------------------------- ### Send Data via Transporter (Java) Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Sends an action string with optional data to the connected device. Data can only be sent after the channel is ready. Supports sending with or without a DataBundle and includes an option for a callback to confirm delivery. ```java // Simple send - action only transporter.send("hello_world"); // Send with data bundle DataBundle dataBundle = new DataBundle(); dataBundle.putString("message", "Hello from watch!"); dataBundle.putInt("count", 42); dataBundle.putBoolean("isActive", true); transporter.send("custom_action", dataBundle); // Send with callback to confirm delivery transporter.send("important_action", dataBundle, new Transporter.DataSendResultCallback() { @Override public void onResultBack(DataTransportResult result) { int resultCode = result.getResultCode(); Log.d("Transport", "Send result code: " + resultCode); // Result codes: 0 = success, 4 = service not connected } }); ``` -------------------------------- ### Listen for Service Connection State Changes (Java) Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Listens for transport service connection state changes, including successful connections, failures, and disconnections. Provides callbacks for onServiceConnected, onServiceConnectionFailed, and onServiceDisconnected events. ```java transporter.addServiceConnectionListener(new Transporter.ServiceConnectionListener() { @Override public void onServiceConnected(Bundle bundle) { ComponentName component = bundle.getParcelable("component"); Log.d("Transport", "Service connected: " + component); } @Override public void onServiceConnectionFailed(Transporter.ConnectionResult result) { // Result codes: // R_SUCCESS = 0 // R_SERVICE_UNAVAILABLE = 1 // R_SERVICE_AUTH_FAILED = 2 // R_SERVICE_DISCONNECTED = 3 // R_SERVICE_CONNECTING = 4 Log.e("Transport", "Connection failed: " + result.toString()); } @Override public void onServiceDisconnected(Transporter.ConnectionResult result) { Log.d("Transport", "Service disconnected"); } }); ``` -------------------------------- ### Disconnect Transport Service in Java Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Demonstrates how to properly disconnect from the transport service and clean up resources in a Java Android Activity. This method should be called when the activity or application is stopped to prevent resource leaks. ```java public class MyWatchActivity extends Activity { private TransporterClassic transporter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); transporter = (TransporterClassic) Transporter.get(this, "my_module"); // ... setup listeners and connect transporter.connectTransportService(); } @Override protected void onStop() { super.onStop(); // Clean up all listeners before disconnecting transporter.removeAllChannelListeners(); transporter.removeAllDataListeners(); transporter.disconnectTransportService(); } } ``` -------------------------------- ### Transporter.disconnectTransportService Source: https://context7.com/kieronquinn/amazfitcommunication/llms.txt Disconnects the transport service and releases associated resources. This should be invoked during the activity or application stop lifecycle event. ```APIDOC ## POST /transporter/disconnect ### Description Properly disconnects from the transport service and cleans up resources. Should always be called when the activity/app is stopped. ### Method POST ### Endpoint Transporter.disconnectTransportService() ### Request Example { "action": "disconnect" } ### Response #### Success Response (200) - **status** (string) - Disconnection successful ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.