Я разрабатываю приложение, используя Wi-Fi direct для отправки файлов на другое устройство, сейчас я могу отправить один файл с помощью этого кода, указанного ниже, но когда я отправляю несколько файлов на первых общих файловых ресурсах, а остальные не отправляются в моем onConnectionInfoAvailable метод я использую этот код
@Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
Log.e(TAG, "Connect success");
Log.e(TAG, info.groupOwnerAddress.getHostAddress());
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Transfer files...");
mProgressDialog.setCancelable(false);
if (info.isGroupOwner) {
Intent receiveIntent = new Intent(this, ServerService.class);
receiveIntent.setAction(ServerService.ACTION_RECEIVE);
this.startService(receiveIntent);
} else {
if (mTransferFilesTask == null) {
getFragmentManager().popBackStackImmediate();
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setProgress(0);
/*File file = makeDataFile("dropItFile", sendingFilesModelList.toString());*/
new TransferFilesTask(sendingFilesModelList,
info.groupOwnerAddress.getHostAddress(), "1234").execute("");
} else mTransferFilesTask = null;
}
mProgressDialog.show();
}
В моем классе AsyncTask
@SuppressLint("StaticFieldLeak")
private class TransferFilesTask extends AsyncTask<String, Integer, Long> {
private String mAddress;
private String mPort;
private List<SendingFilesModel> mFiles;
private static final int SOCKET_TIMEOUT = 8000;
TransferFilesTask(List<SendingFilesModel> files, String address, String port) {
mFiles = files;
mAddress = address;
mPort = port;
}
@Override
protected Long doInBackground(String... params) {
while (!isCancelled()) {
Socket socket = new Socket();
try {
Log.e(TAG, "Opening client socket - ");
socket.bind(null);
Log.e(TAG, mAddress + " port: " + mPort);
socket.connect((new InetSocketAddress(mAddress, Integer.parseInt(mPort))), SOCKET_TIMEOUT);
Log.e(TAG, "Client socket - " + socket.isConnected());
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(mFiles.size());
Log.e(TAG, mFiles.size() + "");
int added = 100 / mFiles.size();
int status = 100 % mFiles.size();
for (SendingFilesModel file : mFiles) {Here SendingFilesModel is a custom object list in which i am getting files name, size and path
Log.e("getFilePath", file.getFilePath());
long wrtLong = Long.parseLong(file.getFileSize());
dos.writeLong(wrtLong);
Log.e("length Main", "length: " + file.getFileActullSize());
String name = file.getFileName();
dos.writeUTF(name);
FileInputStream fis = new FileInputStream(file.getFilePath());
BufferedInputStream bis = new BufferedInputStream(fis);
int theByte;
byte[] buffer = new byte[1024];
while ((theByte = bis.read(buffer)) > 0) {
bos.write(buffer, 0, theByte);
bos.flush();
}
bis.close();
status = status + added;
mProgressDialog.setProgress(status);
Log.e(TAG, "Client: Data written");
dos.close();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
mProgressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Log.e(TAG, "Client: stop service");
mProgressDialog.dismiss();
this.cancel(true);
}
return null;
}
}
и в моем классе ServerService
public class ServerService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
String dirPath;
private static final String TAG = ServerService.class.getName();
public static final String ACTION_RECEIVE = "action_receive";
public static final String FILES_NAME = "files_name";
private List<String> mFileName = new ArrayList<>();
public ServerService(String name) {
super(name);
}
public ServerService() {
super("ServerService");
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_RECEIVE.equals(action)) {
Log.d(TAG, action);
String dirPath = Environment.getExternalStorageDirectory() + "/MyFiles";
File folder = new File(dirPath + "/MyFiles");
folder.mkdirs();
if (folder.exists()) {
Log.e("FOLDER EXISTS", "FOLDER EXISTS");
} else {
Log.e("FOLDER CREATED", "FOLDER CREATED");
}
try {
/**
* Create a server socket and wait for client connections. This
* call blocks until a connection is accepted from a client
*/
Log.e(TAG, "server create");
ServerSocket serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(1234));
Socket client = serverSocket.accept();
Log.e(TAG, "client accept");
BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for (int i = 0; i <= filesCount; i++) {
long fileLength = dis.readLong();
String fileName = dis.readUTF();
Log.e(TAG, "name: " + fileName);
Log.e(TAG, "length: " + fileLength);
files[i] = new File(dirPath + "/" + fileName);
FileOutputStream fos = new FileOutputStream(files[i]);
int theByte;
byte[] buffer = new byte[1024];
while (fileLength > 0 && (theByte = dis.read(buffer, 0, (int) Math.min(buffer.length, fileLength))) != -1) {
fos.write(buffer, 0, theByte);
fileLength -= theByte;
}
fos.close();
Log.e(TAG, "get file: " + fileName);
mFileName.add(fileName);
//bos.close();
//new MediaScannerWrapper(getApplicationContext(), dirPath + "/" + fileName, "music/*").scan();
}
dis.close();
serverSocket.close();
Log.e(TAG, "saved file and close server");
} catch (IOException e) {
Log.e("IOException", e.getMessage() + "");
}
Intent transferDoneIntent = new Intent();
transferDoneIntent.setAction(MainReceiver.ACTION_TRANSFER_DONE);
//transferDoneIntent.putStringArrayListExtra(FILES_NAME, (ArrayList<String>) mFileName);
sendBroadcast(transferDoneIntent);
stopSelf();
}
}
private class MediaScannerWrapper implements MediaScannerConnection.MediaScannerConnectionClient {
private MediaScannerConnection mConnection;
private String mPath;
private String mMimeType;
public MediaScannerWrapper(Context context, String filePath, String mime) {
mPath = filePath;
mMimeType = mime;
mConnection = new MediaScannerConnection(context, this);
}
public void scan() {
mConnection.connect();
}
@Override
public void onMediaScannerConnected() {
mConnection.scanFile(mPath, mMimeType);
}
@Override
public void onScanCompleted(String path, Uri uri) {
}
}
} После отправки первого файла в классе serverservice это код дает мне IOException
com.example.youxian.wifidirecttransfer E/IOException: malformed input around byte 0
, где я делаю ошибку? либо я не посылаю правильный список объектов в FileInputStream, либо не обращаюсь к серверу для получения файла. я не знаю, пожалуйста, помогите ....