Friday, December 16, 2016

Android NANOHttpd share images example

Android NANOHttpd

Share files between the device using local network.

* Pic images from phone gallery and share with local network.
*It will work only same wifi network
*share files have used GET method.

add gradle

dependencies {
  
    compile 'org.nanohttpd:nanohttpd:2.2.0'   
}
 
 
Activity source code  


package nanohttpd.test.com.postimage;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.esafirm.imagepicker.features.ImagePicker;

public class MainActivity extends AppCompatActivity {

    public  static int REQUEST_CODE_PICKER =103;
    NanoTest mService;
    Button btn;
    String imagePath ="";
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         btn = (Button)findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                ImagePicker.create(MainActivity.this) // Activity or Fragment                        .start(REQUEST_CODE_PICKER);
            }
        });
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICKER && resultCode == RESULT_OK && data != null) {

          //  printImages(images);
            imagePath = ""+ImagePicker.getImages(data).get(0).getPath();
            if(mService != null) {
                mService.setImagePath(imagePath);
            }
            Log.e("MainActivity","imagePath :: " +ImagePicker.getImages(data).get(0).getPath());
            Intent mIntent = new Intent(this, NanoTest.class);
            bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
            return;
        }
    }

    private ServiceConnection mConnection = new ServiceConnection () {
        @Override        public void onServiceConnected(ComponentName className, IBinder service) {
            NanoTest.NanoTestBinder binder = (NanoTest.NanoTestBinder) service;
            mService = binder.getService();
            if(mService != null) {
                mService.setImagePath(imagePath);
            }
            mService.initializeServices(true,imagePath);
        }
        @Override        public void onServiceDisconnected(ComponentName arg0) {
            mService = null;
        }
    };



}


NanoHttpUtils Class

package nanohttpd.test.com.postimage;

import android.app.Service;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Method;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NanoTest extends Service  implements Callback<String> {
   private static final String AUTH_TYPE            = "Basic ";
   private static final String TAG                = "[NANO]";
   private static final int BUFFER_SIZE               = 128;       // 128 bytes   private static final int RECEIVE_TIMEOUT         = 1000*30;        // 30 sec   private static final String BROADCAST_MESSAGE_HELLO = "Hello";
   private static final String BROADCAST_MESSAGE_REPLY = "HRU";
   public static final int PORT = 1507;
   private final IBinder mBinder                 = new NanoTestBinder();
   private static String[] ipAddresses             = null;
   private TestNanoHttpD server                  = null;
   private HashMap<String, ServerSyncService>
                              allSyncServices = null;
   private volatile DatagramSocket socket              = null;
   // Client specific   private static InetAddress lastKnownServerAddress  = null;          /*< Auto-detected server address */   private boolean bRunDetection                 = true;
   private static final int SLEEP_TIME             = 30*60*1000;  // 30 minutes   private static final int NONE_FOUND_SLEEP_TIME    = 1000*30;    // 30 sec   private static final String MIME_JSON = "application/json";
   String imagePath ="";

   @Override   public void onResponse(Call<String> call, Response<String> response) {

      Log.d("response","response ::: " +response);
   }

   @Override   public void onFailure(Call<String> call, Throwable t) {

   }

   public class NanoTestBinder extends Binder {
      public NanoTest getService() {
            return NanoTest.this;
        }
   }
   
   public static abstract class ServerSyncService {
      protected static final String OLDEST_TIMESTAMP = "2016-05-10T00:00:00.000Z";
      public abstract String processData(Method method, String json, String offset);
      public abstract String getListenUri();
      public static String getJsonStatus(String status) {
         if(status == null)
            status = "success";
         return "{\"data\":\""+status+"\"}";
      }

   };
   
   public static final String[] getCurrentIpAddresses() {
      return ipAddresses;
   }
   
   public static final InetAddress getLastKnownServerAddress() {
      return lastKnownServerAddress;
   }
    
   @Override   public void onCreate() {
      super.onCreate();
   }

   @Override   public IBinder onBind(Intent intent) {
      return mBinder;
   }
   
   @Override   public boolean onUnbind(Intent intent) {
      stopServer();
      stopServerDetection();
      return false;
   }
   
   public void initializeServices(boolean bServer,String imagePaths) {
      imagePath = imagePaths;
      getAllIpAddresses();
         restartServer();
   }
   
   private void stopServerDetection() {
      bRunDetection = false;
   }
   
   private void startServerDetection() {
      bRunDetection = true;
      Thread thread = new Thread(new Runnable() {
         @Override         public void run() {
            try {
               while(bRunDetection) {
                  findServer();
                  Thread.sleep(lastKnownServerAddress == null ? NONE_FOUND_SLEEP_TIME : SLEEP_TIME);
               }
            } catch(Exception e) {
               e.printStackTrace();
            }
            
         }
      });
      thread.start();
   }
   
   public void stopServer() {
      // Close Broadcast Server      if(socket != null)
         socket.close();
      socket = null;

      // Close API Server      if(server != null && server.isAlive())
         server.stop();
      server = null;
      
   }

   public void setImagePath(String imagePath) {
      this.imagePath = imagePath;
   }

   private void startBroadcastServer() {
      try {
         // Start Broadcast server         socket = new DatagramSocket(PORT, InetAddress.getByName("0.0.0.0"));
         socket.setBroadcast(true);
         Thread thread = new Thread(new Runnable() {
            @Override            public void run() {
               byte[] recvBuf = new byte[BUFFER_SIZE];
               while(socket != null) {
                  try {
                     DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
                     socket.receive(packet);
                     String message = new String(packet.getData()).trim();
                     Log.d(TAG, "Server Received:"+message+":"+packet.getAddress().getHostAddress()+":"+packet.getPort());
                     if(message.equalsIgnoreCase(BROADCAST_MESSAGE_HELLO)) {
                        byte[] sendData = BROADCAST_MESSAGE_REPLY.getBytes();
                        DatagramPacket sendPacket = new DatagramPacket(sendData,
                                                            sendData.length,
                                                            packet.getAddress(),
                                                            packet.getPort());
                        socket.send(sendPacket);
                     }
                  } catch(SocketException e) {
                     e.printStackTrace();
                     socket = null;
                  } catch(Exception e) {
                     e.printStackTrace();
                  }
               }
            }
         });
         thread.start();
      } catch(Exception e) {
         e.printStackTrace();
      }
   }

   /**    * Tries finding a server.    *    * Requires to be run on a different thread.    *     * @return Returns lastKnownServerAddress (can be null)    */   public static InetAddress findServer() {
      DatagramSocket client = null;
      try {
         client = new DatagramSocket();
         byte[] helloMessage = BROADCAST_MESSAGE_HELLO.getBytes();
         client.setBroadcast(true);

         // Try Broadcast IP         DatagramPacket sendPacket = new DatagramPacket(helloMessage,
                                             helloMessage.length,
                                             InetAddress.getByName("255.255.255.255"),
                                             PORT);
         client.send(sendPacket);

         // Try Receiving response         byte[] recvBuf = new byte[BUFFER_SIZE];
         Log.d(TAG, "Starting receive...");
         DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
         client.setSoTimeout(RECEIVE_TIMEOUT);
         client.receive(packet);
         String message = new String(packet.getData()).trim();
         Log.d(TAG, "Client Received:"+message);
         if(message.equalsIgnoreCase(BROADCAST_MESSAGE_REPLY)) {
            lastKnownServerAddress = packet.getAddress();
            Log.d(TAG, "Found Server:"+lastKnownServerAddress.getHostAddress()+":"+lastKnownServerAddress.getHostName());
         }
      } catch(SocketTimeoutException e) {
         Log.d(TAG, "Timedout...");
      } catch(Exception e) {
         e.printStackTrace();
      } finally {
         if(client != null)
            client.close();
      }
      return lastKnownServerAddress;
   }

   private void startServer() throws IOException {
      // Start API Server      server = new TestNanoHttpD();
      server.start();
      
      startBroadcastServer();
   }

   private void restartServer() {
      try {
         stopServer();

         startServer();
      } catch(IOException e) {
         e.printStackTrace();
      }
   }
   
   private void getAllIpAddresses() {
      ArrayList<String> addresses = new ArrayList<String>();
       try {
           for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
               NetworkInterface intf = en.nextElement();
               for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                   InetAddress inetAddress = enumIpAddr.nextElement();
                   if(!inetAddress.isLoopbackAddress()) {
                      Log.e(TAG, "Adding IP Address:"+inetAddress.getHostAddress().toString());
                       addresses.add(inetAddress.getHostAddress().toString());
                   }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        ipAddresses = addresses.toArray(new String[0]);
   }

   private class TestNanoHttpD extends NanoHTTPD {
      
      public TestNanoHttpD() throws IOException {
         super(PORT);
      }

      private String mapToString(Map<String, String> params) {
         final StringBuilder buf = new StringBuilder();
         for(Map.Entry<String, String> entry : params.entrySet()) {
            buf.append(entry.getKey() + ":" + entry.getValue() + "\n");
         }
         return buf.toString();
      }

      @Override      public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> params, Map<String, String> files) {
         FileInputStream fis = null;
         try {
            fis = new FileInputStream(imagePath);
         } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block            e.printStackTrace();
         }

         return newFixedLengthResponse(Response.Status.OK, "image/jpeg", fis,50000000);
      }


   }


}



1 comment:

  1. Your website is really cool and this is a great inspiring article.
    send big file

    ReplyDelete

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...