1 // Copyright 2011 Google Inc. All Rights Reserved. 2 3 package com.example.android.wifidirect; 4 5 import android.app.IntentService; 6 import android.content.ContentResolver; 7 import android.content.Context; 8 import android.content.Intent; 9 import android.net.Uri; 10 import android.util.Log; 11 12 import java.io.FileNotFoundException; 13 import java.io.IOException; 14 import java.io.InputStream; 15 import java.io.OutputStream; 16 import java.net.InetSocketAddress; 17 import java.net.Socket; 18 19 /** 20 * A service that process each file transfer request i.e Intent by opening a 21 * socket connection with the WiFi Direct Group Owner and writing the file 22 */ 23 public class FileTransferService extends IntentService { 24 25 private static final int SOCKET_TIMEOUT = 5000; 26 public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE"; 27 public static final String EXTRAS_FILE_PATH = "file_url"; 28 public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host"; 29 public static final String EXTRAS_GROUP_OWNER_PORT = "go_port"; 30 31 public FileTransferService(String name) { 32 super(name); 33 } 34 35 public FileTransferService() { 36 super("FileTransferService"); 37 } 38 39 /* 40 * (non-Javadoc) 41 * @see android.app.IntentService#onHandleIntent(android.content.Intent) 42 */ 43 @Override 44 protected void onHandleIntent(Intent intent) { 45 46 Context context = getApplicationContext(); 47 if (intent.getAction().equals(ACTION_SEND_FILE)) { 48 String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH); 49 String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS); 50 Socket socket = new Socket(); 51 int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT); 52 53 try { 54 Log.d(WiFiDirectActivity.TAG, "Opening client socket - "); 55 socket.bind(null); 56 socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT); 57 58 Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected()); 59 OutputStream stream = socket.getOutputStream(); 60 ContentResolver cr = context.getContentResolver(); 61 InputStream is = null; 62 try { 63 is = cr.openInputStream(Uri.parse(fileUri)); 64 } catch (FileNotFoundException e) { 65 Log.d(WiFiDirectActivity.TAG, e.toString()); 66 } 67 DeviceDetailFragment.copyFile(is, stream); 68 Log.d(WiFiDirectActivity.TAG, "Client: Data written"); 69 } catch (IOException e) { 70 Log.e(WiFiDirectActivity.TAG, e.getMessage()); 71 } finally { 72 if (socket != null) { 73 if (socket.isConnected()) { 74 try { 75 socket.close(); 76 } catch (IOException e) { 77 // Give up 78 e.printStackTrace(); 79 } 80 } 81 } 82 } 83 84 } 85 } 86 } 87