Skip to content

Instantly share code, notes, and snippets.

@EXJUSTICE
Created January 4, 2017 07:35
Show Gist options
  • Save EXJUSTICE/81780db849729ce2fa0550fdd9db49bf to your computer and use it in GitHub Desktop.
Save EXJUSTICE/81780db849729ce2fa0550fdd9db49bf to your computer and use it in GitHub Desktop.
package com.xu.consent;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
//CLient side service that sends data, sends directly via SOCKET to grooup owner address, which is passed from intent before from DeviceDetailFragment
public class FileTransferService extends IntentService{
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE=
"com.xu.consent.SEND_FILE";
public static final String EXTRAS_FILE_PATH ="file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS ="go_host";
public static final String EXTRAS_GROUP_OWNER_PORT ="go_port";
public FileTransferService(String name){
super(name);
}
public FileTransferService(){
super("FileTransferService");
}
ArrayList<String> stufftoWrite;
@Override
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);
String username = intent.getExtras().getString("username");
String bool = intent.getExtras().getString("input");
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try{
Log.d("ConsentTag","Opening client socket ");
socket.bind(null);
socket.connect((new InetSocketAddress(host,port)),SOCKET_TIMEOUT);
Log.d("ConsentTag","Client socket "+ socket.isConnected());
//Writing stuff using DataOutputStream
DataOutputStream stream = new DataOutputStream(socket.getOutputStream());
//write username first
//stream.writeUTF(username);
stufftoWrite.add(0,username);
stufftoWrite.add(bool);
//now write everything needed in msgs
for (int i=0;i<stufftoWrite.size();i++){
stream.writeUTF(stufftoWrite.get(i)+",");
stream.flush();
}
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){
e.printStackTrace();
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment