Thursday, 24 May 2018

Monday, 14 May 2018

Broadcast Receiver in Android (kotlin)


Broadcast Receiver in Android (kotlin)


//desing intentfilter name

var intentfilterSetList = "set_list"

Define variable

lateinit var brSetList: BroadcastReceiver
var ifSetList: IntentFilter = IntentFilter(AppConstant.intentfilterSetList)


Declare brodcast in activity

brSetList = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {

         // do your stuff
 
    }
}
// register broadcast in activity

activity.registerReceiver(brSetList, ifSetList)


// send broadcast from anywhere

sendBroadcast(Intent(AppConstant.intentfilterSetList))

Interface in Android (kotlin)


RecyclerViewClick.kt
interface RecyclerViewClick {
    fun onItemClick(position: Int)

}



// declare interface in activity

internal var recyclerListener: RecyclerViewClick = object : RecyclerViewClick {

    override fun onItemClick(position: Int) {

         // do you stuff

    }
}


// connection between two class using interface

// first place
adapter = ArtistSelectListAdapter(context, artistList, recyclerListener, true)


// for call interface
holder.rlTop.setOnClickListener(View.OnClickListener {
    recyclerListener.onItemClick(position) // this line call interfacewhere declare

})



Validation in Android


useful validation for android

Email:- 

1) // default validation funtionality
if (!Patterns.EMAIL_ADDRESS.matcher(edt_email.getText().toString()).matches()) {
 
}


2) First charactor dont allow to "."(dot) or " "space.

edt_email.addTextChangedListener(new TextWatcher() {
    @Override    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override    public void afterTextChanged(Editable s) {

        try {

            String inputChar = edt_email.getText().toString();

            if (edt_email.getText().length() == 1) {

                if (inputChar.equalsIgnoreCase(".") || inputChar.equalsIgnoreCase(" ")) {
                    edt_email.setText("");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
});


Mobile No.

1) First character allow only "+" sign.

edt_mobile.addTextChangedListener(new TextWatcher() {
    @Override    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override    public void afterTextChanged(Editable s) {

        try {

            String last = edt_mobile.getText().toString();
            String inputChar = last.substring(last.length() - 1);


            if (edt_mobile.getText().length() > 1) {

                if (inputChar.equalsIgnoreCase("+")) {
                    edt_mobile.setText(edt_mobile.getText().toString().substring(0, edt_mobile.getText().length() - 1));
                    edt_mobile.setSelection(edt_mobile.getText().length());
                }
            }

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

    }
});

2) Only allow particular digits (only allow declared digit or characters)

<string name="mobile_digits">+9876543210</string>

in xml

android:digits="@string/mobile_digits"



Wednesday, 9 May 2018

Get Online Time from Google Server




public static void getTimeFromGoogleServerNoAsync(final Context context) {


    try {

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            String dateStr = response.getFirstHeader("Date").getValue();
            //Here I do something with the Date String            //System.out.println("Google Time "+dateStr);
            PreferencesHelper preferencesHelper = new PreferencesHelper(context);
            preferencesHelper.setGoogleTime(dateStr);

            SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
            Date d1 = null;
            try {
                d1 = sdf3.parse(dateStr);
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println("OTP Google Time" + d1);
            Calendar calendar = Calendar.getInstance();
            System.out.println("OTP Device Time" + calendar.getTime());

        } else {
            //Closes the connection.            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        Log.d("Response", e.getMessage());
    } catch (IOException e) {
        Log.d("Response", e.getMessage());
    }

}



Encrypt/Decrypt string in Android (using your own secret key)

   
 // create secrete key of sting token/key    String keystr = "hkjhgsdghhg";
    byte[] bytearr = new Base32().decode(keystr);
    SecretKey secret = new SecretKeySpec(bytearr, 0, bytearr.length, "AES");

    String password = "123456";

    //Encrept    byte[] cipherText = encryptMsg(password, secret))
    

    public static byte[] encryptMsg(String message, SecretKey secret)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
    {
        /* Encrypt the message. */        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));
        return cipherText;
    }

    //Decrept
    password =  decryptMsg(cipherText, secret))

    public static String decryptMsg(byte[] cipherText, SecretKey secret)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException
    {
        /* Decrypt the message, given derived encContentValues and initialization vector. */        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret);
        String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
        return decryptString;
    }


Run/install/debug Android applications over Wi-Fi ?

Open Teminal/cmd --------------- Below steps is for Android 10 or lower Step 1 - Connect the device via USB and make sure debugging is work...