Wednesday, 19 October 2016

Android Image Preview Activity


                       Here I am going to explain how to show image preview in android using Dialog Fragment



                           


To pass image string to dailog fragment use bundle

               Bundle bundle = new Bundle();
               bundle.putString("data", imageData);


To call dialog fragment 

                FragmentManager fm = activity.getFragmentManager();
                ImageDialogFragment newFragment =                                                                                                   ImageDialogFragment.newInstance();
                newFragment .setArguments(bundle);

                newFragment .show(fm, "slideshow");




ImageDialogFragment.java


import android.app.DialogFragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageView;

 public class ImageDialogFragment extends DialogFragment {


   public    static ImageDialogFragment newInstance()
   {
        ImageDialogFragment f = new ImageDialogFragment();

        return ;
    }

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.image_popup, container, false);

        ImageView imageViewPreview =(ImageView)v
                                                .findViewById(R.id.image_preview);

        try {
              showImage(getArguments().getString("data"),imageViewPreview );
           }
       catch (Exception e)
       {

       }

        return v;
    }

    private void showImage(String data,ImageView image) {
   
          try {

            Bitmap bitmap = null;
            try {
                byte[] bytes = android.util.Base64.decode(data,                                                                                               android.util.Base64.DEFAULT);

                bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes .length);
                image.setImageBitmap(bitmap);


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        catch (Exception e)
        {

        }
  }

   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
           setStyle(DialogFragment.STYLE_NORMAL,
             android.R.style.Theme_Black_NoTitleBar_Fullscreen);
       }
}


image_popup.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black">

    <ImageView
         android:id="@+id/close"
        android:background="@android:drawable/ic_menu_close_clear_cancel"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="27dp"
        android:layout_marginEnd="27dp"
        android:layout_marginTop="14dp" />

    <ImageView
        android:id="@+id/image_preview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitCenter"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>



Happy Coding :)
            

Tuesday, 20 September 2016

TreeMap vs LinkedHashMap

Here I am going to explain difference between HashMap vs TreeMap  vs LinkedHashMap

HashMap 

     HashMap accepts key-value pair,It allows null value for both key and Value and HashMap is Unsynchronized.

  HashMap<String,String> hashmap=new HashMap<String,String>();

  hashmap.put("1","Dhina");
  hashmap.put("2",null);


TreeMap  

    TreeMap accepts key-value pair,It didn't allows null value for key and  allows null value for Value and TreeMap is Unique.It is same as HashMap instead maintains ascending order.

  TreeMap <String,String> treemap=new TreeMap <String,String>();

  treemap.put("1","Dhina");
  treemap.put("2",null);




LinkedHashMap

    LinkedHashMap accepts key-value pair,It allows one null  key and  allows null value for Value and LinkedHashMap is Unique.It is same as HashMap instead maintains insertion order.

  LinkedHashMap <String,String> linkedhash=new LinkedHashMap<String,String>();

  linkedhash.put("1","Dhina");
  linkedhash.put("null",Karan);





HashMap vs Hashtable vs HashSet


  Here I am going to explain difference between HashMap vs HasTable vs HashSet 

HashMap 

     HashMap accepts key-value pair,It allows null value for both key and Value and HashMap is Unsynchronized.

  HashMap<String,String> hashmap=new HashMap<String,String>();

  hashmap.put("1","Dhina");
  hashmap.put("2",null);

HasTable 

 HasTable accepts key-value pair,It didn't allows null value for both key and Value and HasTable is Synchronized.


  HasTable <String,String> hashtable=new HasTable <String,String>();

  hashtable.put("1","Dhina");
  hashtable.put("2","Karan");


HashSet 

     HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet HashSet can be used where you want to maintain a unique list.


  HashSet<String> set= new HashSet<String>();
  set.add ("DH");
  set.add ("IN");
  

Saturday, 10 September 2016

Otto Event Bus library on Android

Otto


            Otto is an Open Source project designed to provide an event bus implementation so that components can publish and subscribe to events.

PUBLISHING
  
            Event publishing is the most important part of the bus as it allows you to tell subscribers that an action has occurred. An instance of any class may be published on the bus and it will only be dispatched to subscribers for that type.

To publish a new event, call the post method:

    BusProvider.getInstance().post(new TestData());

SUBSCRIBING

        Subscription is the complement to event publishing—it lets you receive notification that an event has occurred. To subscribe to an event, annotate a method with @Subscribe. The method should take only a single parameter, the type of which will be the event you wish to subscribe to.

To listen for the event published in the previous section we would need the following:

 @Subscribe public  void showMessage(TestData msg)
    {
        Toast.makeText(getApplicationContext(),"Service Started",Toast.LENGTH_LONG).show();
    }


PRODUCING

     If new components, like a dynamically created fragment, should receive event data during their creation, components can register as producer for such event data with the @Produce annotation.

Event receivers must register via the register method of the Bus class.

@Produce
public String produceEvent() {
  return "Starting up"; 

To Register and UnRegister

 BusProvider.getInstance().register(MainActivity.this);

 BusProvider.getInstance().unregister(MainActivity.this);



Uses
 
  •         Communicate between your activity and fragments
  •          Communicate between your activity and service


Otto Example

build.gradle

 compile 'com.squareup:otto:1.3.8'



Singleton Class BusProvider


  public final class BusProvider
  {
    private static Bus mInstance = null;

   public BusProvider()
    {

    }

    public static Bus getInstance(){
        if(mInstance == null)
        {
            mInstance = new Bus();
        }
        return mInstance;
    }

}


MainActivity.java


import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.squareup.otto.Subscribe;

public class MainActivity extends AppCompatActivity {

    Button registerButtton,unregisterButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        registerButtton=(Button)findViewById(R.id.register);
        unregisterButton=(Button)findViewById(R.id.unregister);

        registerButtton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                BusProvider.getInstance().register(MainActivity.this);
            
      }
        });
        unregisterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {

                    BusProvider.getInstance().unregister(MainActivity.this);
                }
                catch (Exception e)
                {

                }
            }
        });


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {



                Intent serviceIntent=new Intent(MainActivity.this,MyService.class);

                if(MyService.isRunning) {
                    stopService(serviceIntent);
                }
                startService(serviceIntent);




            }
        });
    }

//To Subscribe event

    @Subscribe public  void showMessage(TestData msg)
    {
        Toast.makeText(getApplicationContext(),"Service Started",Toast.LENGTH_LONG).show();
    }



}


Myservice.java


import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;


public class MyService extends Service
{

   public  static  boolean isRunning =false;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {

        isRunning =true;

    }
    @Override
    public void onStart(Intent intent, int startid) {

  //To Publish event

     BusProvider.getInstance().post(new TestData());
   
 }
    @Override
    public void onDestroy() {

    }
}

 
TestData.java


public class TestData
{
        public String msg;


}



Happy Coding :)

 
           

Wednesday, 31 August 2016

How to make our application Device administrator in Android


                Here I am going to explain Device Administration in Android


    Device Administration API provides device administration features at the system level. These APIs allow you to create security-aware applications that are useful in enterprise settings, in which IT professionals require rich control over employee devices


  Here are examples of the types of applications that might use the Device Administration API:


  •           Email clients.
  •           Security applications that do remote wipe.
  •           Device management services and applications.
  •           Change Password.
  •           Lock Screen


                                      




Example

    public class MainActivity extends AppCompatActivity {

    private DevicePolicyManager mgr=null;
    private ComponentName cn=null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar );

        cn = new ComponentName(this, AdminReceiver.class);
        mgr =(DevicePolicyManager)getSystemService(DEVICE_POLICY_SERVICE);
        lockMe();
    }
     public void lockMe() {
            if (mgr.isAdminActive(cn)) {
                mgr.lockNow();
            }
            else {
                Intent intent=new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cn);
                intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                        "AndroidDhina");
                startActivity(intent);
            }
        }
    }


AndroidManifest

  <uses-feature
        android:name="android.software.device_admin"
        android:required="true"/>

AdminReceiver

 public class AdminReceiver extends DeviceAdminReceiver 
  {
  }


xml

 <device-admin xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-policies>
        <force-lock/>
    </uses-policies>

</device-admin>


Happy Coding :)

Thursday, 25 August 2016

Android MQTT Client example Part-2



  In last post we have discuss about ,What is Mqtt and how to publish message using MQTT.Here I am going to explain how to receive message using Mqtt

MQTTService.class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.app.Service;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import  android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.internal.ExceptionHelper;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.UnsupportedEncodingException;
import java.security.spec.ECField;

/**
 * Created by AS0060 on 8/24/2016.
 */
public class MQTTService extends Service {

    private static final String TAG = "MQTTService";
    private static boolean hasWifi = false;
    private static boolean hasMmobile = false;
    private ConnectivityManager mConnMan;
    public static volatile IMqttAsyncClient mqttClient;
    private String deviceId;

    MQTTBroadcastReceiver broadcastReceiver;


    class MQTTBroadcastReceiver extends BroadcastReceiver {

        MQTTBroadcastReceiver() {

        }


        @Override
        public void onReceive(Context context, Intent intent) {


            IMqttToken token;


            boolean hasConnectivity = false;
            boolean hasChanged = false;
            NetworkInfo infos[] = mConnMan.getAllNetworkInfo();

            for (int i = 0; i < infos.length; i++) {
                if (infos[i].getTypeName().equalsIgnoreCase("MOBILE")) {
                    if ((infos[i].isConnected() != hasMmobile)) {
                        hasChanged = true;
                        hasMmobile = infos[i].isConnected();
                    }
                 
                } else if (infos[i].getTypeName().equalsIgnoreCase("WIFI")) {
                    if ((infos[i].isConnected() != hasWifi)) {
                        hasChanged = true;
                        hasWifi = infos[i].isConnected();
                    }
                   
                }
            }

            hasConnectivity = hasMmobile || hasWifi;

            if (hasConnectivity && hasChanged && (mqttClient == null || !mqttClient.isConnected()))
           {
                doConnect();
            } else if (!hasConnectivity && mqttClient != null && mqttClient.isConnected()) {

                try {
                    token = mqttClient.disconnect();
                    token .waitForCompletion(1000);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        }

    }



    public class MQTTBinder extends Binder {
        public MQTTService getService() {
            return MQTTService.this;
        }
    }



    @Override
    public void onCreate()
    {
        IntentFilter intentf = new IntentFilter();
        setClientID();
        broadcastReceiver = new MQTTBroadcastReceiver();
        intentf.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(broadcastReceiver,
        new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 
        mConnMan = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);                                                                                    
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.d(TAG, "onConfigurationChanged()");
        android.os.Debug.waitForDebugger();
        super.onConfigurationChanged(newConfig);

    }

    private void setClientID() {
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
        WifiInfo wInfo = wifiManager.getConnectionInfo();
        deviceId = wInfo.getMacAddress();
        if (deviceId == null) {
            deviceId = MqttAsyncClient.generateClientId();
        }
    }

    private void doConnect()
    {
       
        IMqttToken token;
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        try {
            mqttClient = new MqttAsyncClient("tcp://test.mosquitto.org:1883",                                                               deviceId, new MemoryPersistence());
            token= mqttClient.connect();
            token.waitForCompletion(3500);
            mqttClient.setCallback(new MqttEventCallback());
            token = mqttClient.subscribe("test", 1);
            token.waitForCompletion(5000);
        } catch (MqttSecurityException e) {
            e.printStackTrace();
        } catch (MqttException e) {
            doConnect();
            switch (e.getReasonCode()) {
                case MqttException.REASON_CODE_BROKER_UNAVAILABLE:
                case MqttException.REASON_CODE_CLIENT_TIMEOUT:
                case MqttException.REASON_CODE_CONNECTION_LOST:
                case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
                    Log.v(TAG, "c" + e.getMessage());
                    e.printStackTrace();
                    break;
                case MqttException.REASON_CODE_FAILED_AUTHENTICATION:
                    Intent i = new Intent("ANDROIDDHINA");
                    i.putExtra("ALLARM", e);
                    Log.e(TAG, "b" + e.getMessage());
                    break;
                default:
                    Log.e(TAG, "a" + e.getMessage());
            }
        }
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v(TAG, "onStartCommand()");


        return START_STICKY;
    }

    private class MqttEventCallback implements MqttCallback {

        @Override
        public void connectionLost(Throwable arg0) {


        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {

        }

        @Override
        @SuppressLint("NewApi")
        public void messageArrived(String topic, final MqttMessage msg
        throws Exception {

            Handler h = new Handler(getMainLooper());
            h.post(new Runnable() {
                @Override
                public void run() {

                Toast.makeText(getApplicationContext(), "MQTT Message:\n" +new String(msg.getPayload()),Toast.LENGTH_SHORT).show();                   
                }
            });
        }
    }


    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind called");
        return null;
    }

   

}



AndroidManifest.xml


  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission 
             android:name="android.permission.CHANGE_WIFI_STATE"/> 
 <uses-permission 
             android:name="android.permission.ACCESS_WIFI_STATE"/  >
  <uses-permission                                                                                                     android:name="android.permission.ACCESS_NETWORK_STATE" /> 

 <service android:name=".MQTTService"></service>


Happy Coding:)