Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to share files without using internet?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 172
    Comment on it

    Hello guys,

    This tutorial will help you to guide that "to share files without using an internet". Through this tutorial, we can share any type of files between android devices. I am explaining this step by step.

     

    Step1- Introduction

    We are creating client-server communication using Socket programming. At client side, we pass IP address of server side and PORT number to Socket class and then try to connect that server. Once connected to server, server reply to the query.

     

     Client side implementation

    First, we implementing client side. We select share file from our device then connect to the server and send file. At this side, we are creating following class files.

    1- File Picker:-

    2- MainActivity: This is main client side activity class

    1- FilePicker.java

    This class file will display the list of files and folder to pick any type of files such as audio, images etc. To display the list of files press select button.

    1. /**
    2. * Created by arvind on 14/7/16.
    3. */
    4. public class FilePicker extends ListActivity {
    5.  
    6. public final static String EXTRA_FILE_PATH = "file_path";
    7. public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files";
    8. public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions";
    9. private final static String DEFAULT_INITIAL_DIRECTORY = "/";
    10.  
    11. protected File Directory;
    12. protected ArrayList<File> Files;
    13. protected FilePickerListAdapter Adapter;
    14. protected boolean ShowHiddenFiles = false;
    15. protected String[] acceptedFileExtensions;
    16.  
    17. @Override
    18. protected void onCreate(Bundle savedInstanceState) {
    19. super.onCreate(savedInstanceState);
    20.  
    21. LayoutInflater inflator = (LayoutInflater)
    22. getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    23.  
    24. View emptyView = inflator.inflate(R.layout.empty_view, null);
    25. ((ViewGroup) getListView().getParent()).addView(emptyView);
    26. getListView().setEmptyView(emptyView);
    27.  
    28. // Set initial directory
    29. Directory = new File(DEFAULT_INITIAL_DIRECTORY);
    30.  
    31. // Initialize the ArrayList
    32. Files = new ArrayList<File>();
    33.  
    34. // Set the ListAdapter
    35. Adapter = new FilePickerListAdapter(this, Files);
    36. setListAdapter(Adapter);
    37.  
    38. // Initialize the extensions array to allow any file extensions
    39. acceptedFileExtensions = new String[] {};
    40.  
    41. // Get intent extras
    42. if(getIntent().hasExtra(EXTRA_FILE_PATH))
    43. Directory = new File(getIntent().getStringExtra(EXTRA_FILE_PATH));
    44.  
    45. if(getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES))
    46. ShowHiddenFiles = getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false);
    47.  
    48. if(getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) {
    49.  
    50. ArrayList<String> collection =
    51. getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS);
    52.  
    53. acceptedFileExtensions = (String[])
    54. collection.toArray(new String[collection.size()]);
    55. }
    56. }
    57.  
    58. @Override
    59. protected void onResume() {
    60. refreshFilesList();
    61. super.onResume();
    62. }
    63.  
    64. protected void refreshFilesList() {
    65.  
    66. Files.clear();
    67. ExtensionFilenameFilter filter =
    68. new ExtensionFilenameFilter(acceptedFileExtensions);
    69.  
    70. File[] files = Directory.listFiles(filter);
    71.  
    72. if(files != null && files.length > 0) {
    73.  
    74. for(File f : files) {
    75.  
    76. if(f.isHidden() && !ShowHiddenFiles) {
    77.  
    78. continue;
    79. }
    80.  
    81. Files.add(f);
    82. }
    83.  
    84. Collections.sort(Files, new FileComparator());
    85. }
    86.  
    87. Adapter.notifyDataSetChanged();
    88. }
    89.  
    90. @Override
    91. public void onBackPressed() {
    92.  
    93. if(Directory.getParentFile() != null) {
    94.  
    95. Directory = Directory.getParentFile();
    96. refreshFilesList();
    97. return;
    98. }
    99.  
    100. super.onBackPressed();
    101. }
    102.  
    103. @Override
    104. protected void onListItemClick(ListView l, View v, int position, long id) {
    105.  
    106. File newFile = (File)l.getItemAtPosition(position);
    107.  
    108. if(newFile.isFile()) {
    109.  
    110. System.out.println("selected file path" +newFile.getAbsolutePath().toString());
    111.  
    112. Intent extra = new Intent();
    113. extra.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath());
    114. setResult(RESULT_OK, extra);
    115. finish();
    116. }
    117. else {
    118.  
    119. Directory = newFile;
    120. refreshFilesList();
    121. }
    122.  
    123. super.onListItemClick(l, v, position, id);
    124. }
    125.  
    126. private class FilePickerListAdapter extends ArrayAdapter<File> {
    127.  
    128. private List<File> mObjects;
    129.  
    130. public FilePickerListAdapter(Context context, List<File> objects) {
    131.  
    132. super(context, R.layout.list_item, android.R.id.text1, objects);
    133. mObjects = objects;
    134. }
    135.  
    136. @Override
    137. public View getView(int position, View convertView, ViewGroup parent) {
    138.  
    139. View row = null;
    140.  
    141. if(convertView == null) {
    142.  
    143. LayoutInflater inflater = (LayoutInflater)
    144. getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    145.  
    146. row = inflater.inflate(R.layout.list_item, parent, false);
    147. }
    148. else
    149. row = convertView;
    150.  
    151. File object = mObjects.get(position);
    152.  
    153. ImageView imageView = (ImageView)row.findViewById(R.id.file_picker_image);
    154. TextView textView = (TextView)row.findViewById(R.id.file_picker_text);
    155. textView.setSingleLine(true);
    156. textView.setText(object.getName());
    157.  
    158. /* if(!object.isFile()) {
    159. imageView.setImageResource(R.drawable.check);
    160. }*/
    161.  
    162. /* else
    163. // imageView.setImageResource(R.drawable.folder);
    164. */
    165. return row;
    166. }
    167. }
    168.  
    169. private class FileComparator implements Comparator<File> {
    170.  
    171. public int compare(File f1, File f2) {
    172.  
    173. if(f1 == f2)
    174. return 0;
    175.  
    176. if(f1.isDirectory() && f2.isFile())
    177. // Show directories above files
    178. return -1;
    179.  
    180. if(f1.isFile() && f2.isDirectory())
    181. // Show files below directories
    182. return 1;
    183.  
    184. // Sort the directories alphabetically
    185. return f1.getName().compareToIgnoreCase(f2.getName());
    186. }
    187. }
    188.  
    189. private class ExtensionFilenameFilter implements FilenameFilter {
    190.  
    191. private String[] Extensions;
    192.  
    193. public ExtensionFilenameFilter(String[] extensions) {
    194.  
    195. super();
    196. Extensions = extensions;
    197. }
    198.  
    199. public boolean accept(File dir, String filename) {
    200.  
    201. if(new File(dir, filename).isDirectory()) {
    202.  
    203. // Accept all directory names
    204. return true;
    205. }
    206.  
    207. if(Extensions != null && Extensions.length > 0) {
    208.  
    209. for(int i = 0; i < Extensions.length; i++) {
    210.  
    211. if(filename.endsWith(Extensions[i])) {
    212.  
    213. // The filename ends with the extension
    214. return true;
    215. }
    216. }
    217. // The filename did not match any of the extensions
    218. return false;
    219. }
    220. // No extensions has been set. Accept all file extensions.
    221. return true;
    222. }
    223. }
    224. }

     

    2- MainActivity.java:-

    This is an main client side implementation class.

     

    Layout File:

    activity_main.xml

    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    2. xmlns:tools="http://schemas.android.com/tools"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. android:orientation="vertical"
    6. android:paddingBottom="@dimen/activity_vertical_margin"
    7. android:paddingLeft="@dimen/activity_horizontal_margin"
    8. android:paddingRight="@dimen/activity_horizontal_margin"
    9. android:paddingTop="@dimen/activity_vertical_margin"
    10. tools:context="com.example.androidsocketfiletransferclient.MainActivity" >
    11.  
    12. <TextView
    13. android:layout_width="wrap_content"
    14. android:layout_height="wrap_content"
    15. android:layout_gravity="center_horizontal"
    16. android:autoLink="web"
    17. android:text="http://android-er.blogspot.com/"
    18. android:textStyle="bold" />
    19.  
    20. <TextView
    21. android:layout_width="match_parent"
    22. android:layout_height="wrap_content"
    23. android:text="File Transfer Client"
    24. android:textStyle="bold" />
    25.  
    26. <EditText
    27. android:id="@+id/address"
    28. android:layout_width="match_parent"
    29. android:layout_height="wrap_content"
    30. android:text="192.168.1.94"
    31. android:hint="dstAddress" />
    32.  
    33. <TextView
    34. android:id="@+id/port"
    35. android:layout_width="match_parent"
    36. android:layout_height="wrap_content" />
    37.  
    38.  
    39. <Button
    40. android:id="@+id/select"
    41. android:layout_width="match_parent"
    42. android:layout_height="wrap_content"
    43. android:text="Select file " />
    44.  
    45.  
    46. <TextView
    47. android:layout_width="wrap_content"
    48. android:layout_height="wrap_content"
    49. android:layout_below="@+id/browse"
    50. android:layout_marginTop="20dp"
    51. android:id="@+id/selected"
    52. android:textStyle="bold"
    53. android:textColor="#4189E1"
    54. android:textSize="20sp"
    55. android:text="Selected file" />
    56.  
    57. <TextView
    58. android:layout_width="wrap_content"
    59. android:layout_height="wrap_content"
    60. android:layout_below="@+id/selected"
    61. android:layout_marginTop="20dp"
    62. android:id="@+id/file_path"
    63. android:text="No file has been selected"
    64. android:textSize="18sp" />
    65.  
    66.  
    67. <Button
    68. android:id="@+id/connect"
    69. android:layout_width="match_parent"
    70. android:layout_height="wrap_content"
    71. android:text="Connect..." />
    72.  
    73. </LinearLayout>

     

    empty_view.xml:

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <TextView
    3. xmlns:android="http://schemas.android.com/apk/res/android"
    4. android:layout_width="match_parent"
    5. android:layout_height="match_parent"
    6. android:text="No files or directories"
    7. android:background="@android:drawable/toast_frame"
    8. android:textSize="28sp"
    9. android:gravity="center_vertical|center_horizontal" />
    10.  
    11.  
    12.  

     

    list_item.xml:

    1. <LinearLayout
    2. xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="wrap_content"
    5. android:orientation="horizontal" >
    6.  
    7. <ImageView
    8. android:id="@+id/file_picker_image"
    9. android:layout_width="40dip"
    10. android:layout_height="40dip"
    11. android:layout_marginTop="5dip"
    12. android:layout_marginBottom="5dip"
    13. android:layout_marginLeft="5dip"
    14. android:scaleType="centerCrop" />
    15.  
    16. <TextView
    17. android:id="@+id/file_picker_text"
    18. android:layout_width="wrap_content"
    19. android:layout_height="wrap_content"
    20. android:layout_weight="1"
    21. android:layout_gravity="left|center_vertical"
    22. android:textSize="28sp"
    23. android:layout_marginLeft="10dip"
    24. android:singleLine="true"
    25. android:text="Filename" />
    26.  
    27. </LinearLayout>

     

    Server Side Implementation

    Next, we will implement server side code to receive the file. At this side, Socket accept client side request and create a listener and start to read file from client side.

    MainActivity.java:

    1. public class MainActivity extends ActionBarActivity {
    2.  
    3. TextView infoIp, infoPort;
    4.  
    5. static final int SocketServerPORT = 8080;
    6. ServerSocket serverSocket;
    7. ServerSocketThread serverSocketThread;
    8. @Override
    9. protected void onCreate(Bundle savedInstanceState) {
    10. super.onCreate(savedInstanceState);
    11. setContentView(R.layout.activity_main);
    12. infoIp = (TextView) findViewById(R.id.infoip);
    13. infoPort = (TextView) findViewById(R.id.infoport);
    14.  
    15. infoIp.setText(getIpAddress());
    16. serverSocketThread = new ServerSocketThread();
    17. serverSocketThread.start();
    18. }
    19.  
    20. @Override
    21. protected void onDestroy() {
    22. super.onDestroy();
    23. if (serverSocket != null) {
    24. try {
    25. serverSocket.close();
    26. } catch (IOException e) {
    27. // TODO Auto-generated catch block
    28. e.printStackTrace();
    29. }
    30. }
    31. }
    32.  
    33. private String getIpAddress() {
    34. String ip = "";
    35. try {
    36. Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
    37. .getNetworkInterfaces();
    38. while (enumNetworkInterfaces.hasMoreElements()) {
    39. NetworkInterface networkInterface = enumNetworkInterfaces
    40. .nextElement();
    41. Enumeration<InetAddress> enumInetAddress = networkInterface
    42. .getInetAddresses();
    43. while (enumInetAddress.hasMoreElements()) {
    44. InetAddress inetAddress = enumInetAddress.nextElement();
    45.  
    46. if (inetAddress.isSiteLocalAddress()) {
    47. ip += "SiteLocalAddress: "
    48. + inetAddress.getHostAddress() + "\n";
    49. }
    50.  
    51. }
    52.  
    53. }
    54.  
    55. } catch (SocketException e) {
    56. // TODO Auto-generated catch block
    57. e.printStackTrace();
    58. ip += "Something Wrong! " + e.toString() + "\n";
    59. }
    60.  
    61. return ip;
    62. }
    63. public class ServerSocketThread extends Thread {
    64.  
    65. @Override
    66. public void run() {
    67. Socket socket = null;
    68. try {
    69.  
    70.  
    71.  
    72.  
    73. ServerSocket serverSocket = null;
    74.  
    75. try {
    76. serverSocket = new ServerSocket(8081);
    77. } catch (IOException ex) {
    78. System.out.println("Can't setup server on this port number. ");
    79. }
    80.  
    81.  
    82. try {
    83. while (true) {
    84. socket = serverSocket.accept();
    85. FileTxThread fileTxThread = new FileTxThread(socket);
    86. fileTxThread.start();
    87. }
    88. } catch (IOException ex) {
    89. System.out.println("Can't accept client connection. ");
    90. }
    91.  
    92.  
    93.  
    94. } catch (Exception e) {
    95. // TODO Auto-generated catch block
    96. e.printStackTrace();
    97. } finally {
    98. if (socket != null) {
    99. try {
    100. socket.close();
    101. } catch (IOException e) {
    102. // TODO Auto-generated catch block
    103. e.printStackTrace();
    104. }
    105. }
    106. }
    107. }
    108.  
    109. }
    110. public class FileTxThread extends Thread {
    111. Socket socket;
    112. InputStream in = null;
    113. OutputStream out = null;
    114. FileTxThread(Socket socket){
    115. this.socket= socket;
    116. }
    117.  
    118. @Override
    119. public void run() {
    120.  
    121.  
    122. try {
    123. in = socket.getInputStream();
    124.  
    125. DataInputStream clientData = new DataInputStream(in);
    126. String fileName = clientData.readUTF();
    127.  
    128. File file = new File(
    129. Environment.getExternalStorageDirectory(),
    130. fileName);
    131.  
    132.  
    133. if(!file.exists())
    134. try {
    135. file.createNewFile();
    136. } catch (IOException e) {
    137. e.printStackTrace();
    138. }
    139.  
    140.  
    141.  
    142. try {
    143. out = new FileOutputStream(file.getAbsolutePath());
    144.  
    145. } catch (FileNotFoundException ex) {
    146. System.out.println("File not found. ");
    147. }
    148.  
    149. byte[] bytes = new byte[16*1024];
    150.  
    151. int count;
    152. while ((count = in.read(bytes)) > 0) {
    153. out.write(bytes, 0, count);
    154. }
    155.  
    156. Toast.makeText(MainActivity.this,"File received successfully",Toast.LENGTH_SHORT).show();
    157.  
    158. out.close();
    159. in.close();
    160.  
    161. } catch (FileNotFoundException e) {
    162. // TODO Auto-generated catch block
    163. e.printStackTrace();
    164. } catch (IOException e) {
    165. // TODO Auto-generated catch block
    166. e.printStackTrace();
    167. } finally {
    168. try {
    169. socket.close();
    170. } catch (IOException e) {
    171. // TODO Auto-generated catch block
    172. e.printStackTrace();
    173. }
    174. }
    175. }
    176. }
    177. }

     

    Supporting Layout files

    activity_main.xml
     

    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    2. xmlns:tools="http://schemas.android.com/tools"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. android:orientation="vertical"
    6. android:paddingBottom="@dimen/activity_vertical_margin"
    7. android:paddingLeft="@dimen/activity_horizontal_margin"
    8. android:paddingRight="@dimen/activity_horizontal_margin"
    9. android:paddingTop="@dimen/activity_vertical_margin"
    10. tools:context="com.example.androidsocketfiletransferserver.MainActivity" >
    11.  
    12. <TextView
    13. android:layout_width="wrap_content"
    14. android:layout_height="wrap_content"
    15. android:layout_gravity="center_horizontal"
    16. android:autoLink="web"
    17. android:text="http://android-er.blogspot.com/"
    18. android:textStyle="bold" />
    19.  
    20. <TextView
    21. android:layout_width="match_parent"
    22. android:layout_height="wrap_content"
    23. android:text="File Transfer Server"
    24. android:textStyle="bold" />
    25.  
    26. <TextView
    27. android:id="@+id/infoport"
    28. android:layout_width="wrap_content"
    29. android:layout_height="wrap_content"
    30. android:textStyle="italic" />
    31.  
    32. <TextView
    33. android:id="@+id/infoip"
    34. android:layout_width="wrap_content"
    35. android:layout_height="wrap_content"
    36. android:textStyle="italic" />
    37.  
    38. </LinearLayout>

    Note:- You can download the attachment to get complete source code.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: