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:)
   

Wednesday, 24 August 2016

Android MQTT Client example Part-1


               Mqtt is lightweight messaging protocol,  GCM replacement for android push notification.

Mqtt

      MQTT stands for MQ Telemetry Transport. It is a publish/subscribe, extremely simple and lightweight messaging protocol, designed for constrained devices and low-bandwidth, high-latency or unreliable networks.


Mosquitto 

    Mosquitto is an open source (EPL/EDL licensed) message broker that implements the MQTT protocol versions 3.1 and 3.1.1. MQTT provides a lightweight method of carrying out messaging using a publish/subscribe model.



Add Mqtt jar file to your lib folder and right click on it and select Add as a library .Download


MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import java.io.UnsupportedEncodingException;

public class MainActivity extends AppCompatActivity {

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

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


                Intent intent = new Intent(getApplicationContext(), MQTTService.class);
                startService(intent);
            }
        });
        Button fab1 = (Button) findViewById(R.id.publish);
        fab1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                doPublish("test", "Android Dhina");


            }
        });

    }

    public void doPublish(String topic, String payload)

    {
      if (BuildConfig.DEBUG)
            if (MQTTService.mqttClient == null) {
                return;
            }
        IMqttToken token;
        try {
            byte[] encodedPayload;
            encodedPayload = payload.getBytes("UTF-8");
            MqttMessage message = new MqttMessage(encodedPayload);
            token = MQTTService.mqttClient.publish(topic, message);
            token.waitForCompletion(5000);
        } catch (MqttSecurityException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MqttException e) {
            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:
                    if (BuildConfig.DEBUG)
                        e.printStackTrace();
                    break;
                case MqttException.REASON_CODE_FAILED_AUTHENTICATION:
                    Intent i = new Intent("ANDROIDDHINA");
                    i.putExtra("ALLARM", e);
                    if (BuildConfig.DEBUG)
                        break;
                default:
                    if (BuildConfig.DEBUG)
                        break;
            }
        }

    }
}


So for we have seen how to publish message using Mqtt.In next part we will discuss receiving message using MQTT