I want to send multiple selected files to the server through wifidirect. Problem is, only the first file selected is sent. According to resources I found online, the FileTransferService which extends IntentService handles asynchronous requests, and the service handles each Intent in turn using a worker thread, and stops itself automatically. Anyone has any idea why the other files are not sent to the server? Any help appreciated.
This is the activity where I start the file transfer service:
ArrayList<String> uris = new ArrayList<String>();
for( int i=0 ; i<f22.size(); i++ )
{
Uri uri = Uri.fromFile(f22.get(i));
uris.add(uri.toString());
}
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
for(int i=0; i<uris.size();i++)
{
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
DeviceDetailFragment.info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uris.get(i).toString());
startService(serviceIntent);
}
This is the onHnadleintent function in FileTransferService
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
}
DeviceDetailFragment.copyFile(is, stream);
Log.d(WiFiDirectActivity.TAG, "Client: Data written");
}
catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}