- Home
- >> Nerd Digest
- >> Android
-
How to share files without using internet?
over 8 years ago
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.
/** * Created by arvind on 14/7/16. */ public class FilePicker extends ListActivity { public final static String EXTRA_FILE_PATH = "file_path"; public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files"; public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions"; private final static String DEFAULT_INITIAL_DIRECTORY = "/"; protected File Directory; protected ArrayList<File> Files; protected FilePickerListAdapter Adapter; protected boolean ShowHiddenFiles = false; protected String[] acceptedFileExtensions; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View emptyView = inflator.inflate(R.layout.empty_view, null); ((ViewGroup) getListView().getParent()).addView(emptyView); getListView().setEmptyView(emptyView); // Set initial directory Directory = new File(DEFAULT_INITIAL_DIRECTORY); // Initialize the ArrayList Files = new ArrayList<File>(); // Set the ListAdapter Adapter = new FilePickerListAdapter(this, Files); setListAdapter(Adapter); // Initialize the extensions array to allow any file extensions acceptedFileExtensions = new String[] {}; // Get intent extras if(getIntent().hasExtra(EXTRA_FILE_PATH)) Directory = new File(getIntent().getStringExtra(EXTRA_FILE_PATH)); if(getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES)) ShowHiddenFiles = getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false); if(getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) { ArrayList<String> collection = getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS); acceptedFileExtensions = (String[]) collection.toArray(new String[collection.size()]); } } @Override protected void onResume() { refreshFilesList(); super.onResume(); } protected void refreshFilesList() { Files.clear(); ExtensionFilenameFilter filter = new ExtensionFilenameFilter(acceptedFileExtensions); File[] files = Directory.listFiles(filter); if(files != null && files.length > 0) { for(File f : files) { if(f.isHidden() && !ShowHiddenFiles) { continue; } Files.add(f); } Collections.sort(Files, new FileComparator()); } Adapter.notifyDataSetChanged(); } @Override public void onBackPressed() { if(Directory.getParentFile() != null) { Directory = Directory.getParentFile(); refreshFilesList(); return; } super.onBackPressed(); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { File newFile = (File)l.getItemAtPosition(position); if(newFile.isFile()) { System.out.println("selected file path" +newFile.getAbsolutePath().toString()); Intent extra = new Intent(); extra.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath()); setResult(RESULT_OK, extra); finish(); } else { Directory = newFile; refreshFilesList(); } super.onListItemClick(l, v, position, id); } private class FilePickerListAdapter extends ArrayAdapter<File> { private List<File> mObjects; public FilePickerListAdapter(Context context, List<File> objects) { super(context, R.layout.list_item, android.R.id.text1, objects); mObjects = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = null; if(convertView == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.list_item, parent, false); } else row = convertView; File object = mObjects.get(position); ImageView imageView = (ImageView)row.findViewById(R.id.file_picker_image); TextView textView = (TextView)row.findViewById(R.id.file_picker_text); textView.setSingleLine(true); textView.setText(object.getName()); /* if(!object.isFile()) { imageView.setImageResource(R.drawable.check); }*/ /* else // imageView.setImageResource(R.drawable.folder); */ return row; } } private class FileComparator implements Comparator<File> { public int compare(File f1, File f2) { if(f1 == f2) return 0; if(f1.isDirectory() && f2.isFile()) // Show directories above files return -1; if(f1.isFile() && f2.isDirectory()) // Show files below directories return 1; // Sort the directories alphabetically return f1.getName().compareToIgnoreCase(f2.getName()); } } private class ExtensionFilenameFilter implements FilenameFilter { private String[] Extensions; public ExtensionFilenameFilter(String[] extensions) { super(); Extensions = extensions; } public boolean accept(File dir, String filename) { if(new File(dir, filename).isDirectory()) { // Accept all directory names return true; } if(Extensions != null && Extensions.length > 0) { for(int i = 0; i < Extensions.length; i++) { if(filename.endsWith(Extensions[i])) { // The filename ends with the extension return true; } } // The filename did not match any of the extensions return false; } // No extensions has been set. Accept all file extensions. return true; } } }
2- MainActivity.java:-
This is an main client side implementation class.
Layout File:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.androidsocketfiletransferclient.MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:autoLink="web" android:text="http://android-er.blogspot.com/" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="File Transfer Client" android:textStyle="bold" /> <EditText android:id="@+id/address" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="192.168.1.94" android:hint="dstAddress" /> <TextView android:id="@+id/port" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/select" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Select file " /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/browse" android:layout_marginTop="20dp" android:id="@+id/selected" android:textStyle="bold" android:textColor="#4189E1" android:textSize="20sp" android:text="Selected file" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/selected" android:layout_marginTop="20dp" android:id="@+id/file_path" android:text="No file has been selected" android:textSize="18sp" /> <Button android:id="@+id/connect" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Connect..." /> </LinearLayout>
empty_view.xml:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:text="No files or directories" android:background="@android:drawable/toast_frame" android:textSize="28sp" android:gravity="center_vertical|center_horizontal" />
list_item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:id="@+id/file_picker_image" android:layout_width="40dip" android:layout_height="40dip" android:layout_marginTop="5dip" android:layout_marginBottom="5dip" android:layout_marginLeft="5dip" android:scaleType="centerCrop" /> <TextView android:id="@+id/file_picker_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_gravity="left|center_vertical" android:textSize="28sp" android:layout_marginLeft="10dip" android:singleLine="true" android:text="Filename" /> </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:
public class MainActivity extends ActionBarActivity { TextView infoIp, infoPort; static final int SocketServerPORT = 8080; ServerSocket serverSocket; ServerSocketThread serverSocketThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); infoIp = (TextView) findViewById(R.id.infoip); infoPort = (TextView) findViewById(R.id.infoport); infoIp.setText(getIpAddress()); serverSocketThread = new ServerSocketThread(); serverSocketThread.start(); } @Override protected void onDestroy() { super.onDestroy(); if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private String getIpAddress() { String ip = ""; try { Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface .getNetworkInterfaces(); while (enumNetworkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = enumNetworkInterfaces .nextElement(); Enumeration<InetAddress> enumInetAddress = networkInterface .getInetAddresses(); while (enumInetAddress.hasMoreElements()) { InetAddress inetAddress = enumInetAddress.nextElement(); if (inetAddress.isSiteLocalAddress()) { ip += "SiteLocalAddress: " + inetAddress.getHostAddress() + "\n"; } } } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); ip += "Something Wrong! " + e.toString() + "\n"; } return ip; } public class ServerSocketThread extends Thread { @Override public void run() { Socket socket = null; try { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8081); } catch (IOException ex) { System.out.println("Can't setup server on this port number. "); } try { while (true) { socket = serverSocket.accept(); FileTxThread fileTxThread = new FileTxThread(socket); fileTxThread.start(); } } catch (IOException ex) { System.out.println("Can't accept client connection. "); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } public class FileTxThread extends Thread { Socket socket; InputStream in = null; OutputStream out = null; FileTxThread(Socket socket){ this.socket= socket; } @Override public void run() { try { in = socket.getInputStream(); DataInputStream clientData = new DataInputStream(in); String fileName = clientData.readUTF(); File file = new File( Environment.getExternalStorageDirectory(), fileName); if(!file.exists()) try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } try { out = new FileOutputStream(file.getAbsolutePath()); } catch (FileNotFoundException ex) { System.out.println("File not found. "); } byte[] bytes = new byte[16*1024]; int count; while ((count = in.read(bytes)) > 0) { out.write(bytes, 0, count); } Toast.makeText(MainActivity.this,"File received successfully",Toast.LENGTH_SHORT).show(); out.close(); in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
Supporting Layout files
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.androidsocketfiletransferserver.MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:autoLink="web" android:text="http://android-er.blogspot.com/" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="File Transfer Server" android:textStyle="bold" /> <TextView android:id="@+id/infoport" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="italic" /> <TextView android:id="@+id/infoip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="italic" /> </LinearLayout>
Note:- You can download the attachment to get complete source code.
0 Comment(s)