Considering the minimal documentation on using the ChannelClient class to send files from a phone to a wearable, I've gotten it to work. However, I'm getting an ANR error when sending larger files. I'm using a Foreground Service to handle the uploading which I thought was meant for long-running tasks. The strange thing is the ANR is happening in the Activity where the user selects a file to upload.
Service
public class UploadFile extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createForegroundNotification();
Uri fileUri = Uri.parse(intent.getExtras().getString("file"));
String fileName = getFileName(fileUri);
List<Node> nodes = Utilities.getNodesAsync();
for (Node node : nodes) {
ChannelClient channelClient = Wearable.getChannelClient(context);
channelClient.openChannel(node.getId(), fileName).addOnSuccessListener(channel -> {
Task<OutputStream> outputStreamTask = channelClient.getOutputStream(channel);
outputStreamTask.addOnSuccessListener(outputStream -> {
try {
InputStream inputStream = context.getContentResolver().openInputStream(fileUri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0)
byteBuffer.write(buffer, 0, len);
outputStream.write(byteBuffer.toByteArray());
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
stopForeground(true);
}
});
});
}
}
}
UserAddActivity:
mFileUploadButton.setOnClickListener(view -> mFileUpload.launch("*/*"));
final ActivityResultLauncher<String> mFileUpload = registerForActivityResult(new ActivityResultContracts.GetContent(),
uri -> {
final Intent serviceIntent = new Intent(this, UploadFile.class);
final Bundle extrasService = new Bundle();
extrasService.putString("file", uri.toString());
serviceIntent.putExtras(extrasService);
ContextCompat.startForegroundService(this, serviceIntent);
});
Error:
2021-07-26 09:26:56.391 1558-13178/? E/ActivityManager: ANR in com.my.app (com.my.app/.Activities.UserAddActivity)
PID: 13090
Reason: Input dispatching timed out (1c8d463 com.my.app/com.my.app.Activities.UserAddActivity (server) is not responding. Waited 5003ms for FocusEvent(hasFocus=false))
Parent: com.my.app/.Activities.UserAddActivity
The ANR is only happening for large files. The one I'm testing is 63MB. The strange this is the file does transfer to the wearable but the phone is throwing an ANR before it's complete.
I've even tried putting the code into an asynchronous task in the Service.