Monday, 27 April 2015

Encrypt Decry pt for android and NODE JS

 package com.LOLnet;
 2 import java.security.MessageDigest;  
 3   
 4 import javax.crypto.Cipher;  
 5 import javax.crypto.spec.SecretKeySpec;  
 6   
 7 public class AESForNodejs {  
 8     public static final String DEFAULT_CODING = "utf-8";  
 9   
10     //Decrypt
11     public static String decrypt(String encrypted, String seed) throws Exception {  
12         byte[] keyb = seed.getBytes(DEFAULT_CODING);  
13         MessageDigest md = MessageDigest.getInstance("MD5");  
14         byte[] thedigest = md.digest(keyb);  
15         SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");  
16         Cipher dcipher = Cipher.getInstance("AES");  
17         dcipher.init(Cipher.DECRYPT_MODE, skey);  
18   
19         byte[] clearbyte = dcipher.doFinal(toByte(encrypted));  
20         return new String(clearbyte);  
21     }  
22   
23     //Encryption
24     public static String encrypt(String content, String key) throws Exception {  
25         byte[] input = content.getBytes(DEFAULT_CODING);  
26           
27         MessageDigest md = MessageDigest.getInstance("MD5");  
28         byte[] thedigest = md.digest(key.getBytes(DEFAULT_CODING));  
29         SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");  
30         Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");  
31         cipher.init(Cipher.ENCRYPT_MODE, skc);  
32           
33         byte[] cipherText = new byte[cipher.getOutputSize(input.length)];  
34         int ctLength = cipher.update(input, 0, input.length, cipherText, 0);  
35         ctLength += cipher.doFinal(cipherText, ctLength);  
36               
37         return parseByte2HexStr(cipherText);  
38     }  
39       
40     //String to byte
41     private static byte[] toByte(String hexString) {  
42         int len = hexString.length() / 2;  
43         byte[] result = new byte[len];  
44         for (int i = 0; i <len; i++) {  
45             result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();  
46         }  
47         return result;  
48     }  
49       
50     
51     //16 hexadecimal byte array     
52     private static String parseByte2HexStr(byte buf[]) {  
53         StringBuffer sb = new StringBuffer();  
54         for (int i = 0; i <buf.length; i++) {  
55             String hex = Integer.toHexString(buf[i] & 0xFF);  
56             if (hex.length() == 1) {  
57                 hex = '0' + hex;  
58             }  
59             sb.append(hex);  
60         }  
61         return sb.toString();  
62     }  
63 }  


Node:
var crypto = require('crypto');

/**
 * Aes128 encryption
 * @Param data plaintext
 * @Param secretKey key
 * @returns {*}
 */
exports.encrypt = function (data, secretKey) {
    var cipher = crypto.createCipher('aes-128-ecb',secretKey);
    return cipher.update(data,'utf8','hex') + cipher.final('hex');
};

/**
 * Aes128 decryption
 * @Param data ciphertext
 * @Param secretKey key
 * @returns {*}
 */
exports.decrypt = function(data, secretKey) {
    var cipher = crypto.createDecipher('aes-128-ecb',secretKey);
    return cipher.update(data,'hex','utf8') + cipher.final('utf8');
}

Wednesday, 15 April 2015

Android Install APK by prommatically




call this method  where u needed or u can use the broadcast receiver when the new updated APK is uploaded.
-----------------------------------------------------------------------------------------------

private void update() {

new updateAPK().execute();
System.out.println("updating..done");


}
---------------------------------------------------------------------------------------------
use the asyntask

class updateAPK extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... params) {
downloadapk();
return null;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
installApk();
}

}


-----------------------------------------------------------------------------
download the APK

private void downloadapk(){
   try {
       URL url = new URL("http://bluetaxi.in/apk/Spot.apk");
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
       urlConnection.setRequestMethod("GET");
       urlConnection.setDoOutput(true);
       urlConnection.connect();

       File sdcard = Environment.getExternalStorageDirectory();
       File file = new File(sdcard, "filename.apk");

       FileOutputStream fileOutput = new FileOutputStream(file);
       InputStream inputStream = urlConnection.getInputStream();

       byte[] buffer = new byte[1024];
       int bufferLength = 0;

       while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
           fileOutput.write(buffer, 0, bufferLength);
       }
       fileOutput.close();
    //   this.checkUnknownSourceEnability();
     //  this.initiateInstallation();

   } catch (MalformedURLException e) {
           e.printStackTrace();
   } catch (IOException e) {
           e.printStackTrace();
   }
   }

---------------------------------------------------------------------------------------------
install by programm

private void installApk(){
System.out.println("start install");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File("/sdcard/filename.apk"));
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
        System.out.println("complete install");
    }

Monday, 13 April 2015

Android auto update apk implementation

public class UpdateApp extends AsyncTask<String,Void,Void>{
private Context context;
public void setContext(Context contextf){
    context = contextf;
}

@Override
protected Void doInBackground(String... arg0) {
      try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "update.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);


        } catch (Exception e) {
            Log.e("UpdateAPP", "Update error! " + e.getMessage());
        }
    return null;
}}
To use it, in your main activity call by this way:
            atualizaApp = new UpdateApp();
            atualizaApp.setContext(getApplicationContext());
            atualizaApp.execute("http://serverurl/appfile.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
    .setDataAndType(Uri.parse("file:///path/to/your.apk"), 
                    "application/vnd.android.package-archive");
startActivity(promptInstall); 
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
    .setData(Uri.parse("market://details?id=com.package.name"));
startActivity(goToMarket);

References:

  1. http://stackoverflow.com/questions/4967669/android-install-apk-programmatically
  2. http://stackoverflow.com/questions/4604239/install-application-programmatically-on-android

Sunday, 12 April 2015

In android, we can easily check whether GPS is enabled in device or not using LocationManager.

public void turnGPSOn()
{
     Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
     intent.putExtra("enabled", true);
     this.ctx.sendBroadcast(intent);

    String provider = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        this.ctx.sendBroadcast(poke);


    }
}
// automatic turn off the gps
public void turnGPSOff()
{
    String provider = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        this.ctx.sendBroadcast(poke);
    }
}

Thursday, 2 April 2015

Android Sart and Stop Service from Alaram Manager every 30 second

package com.example.alarmmanagerexample;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AlarmManagerExample extends Activity {
   
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_manager_example);
       
       
        Button buttonStart=(Button)findViewById(R.id.buttonStart);
        Button buttonStop=(Button)findViewById(R.id.buttonStop);
       
       
        buttonStart.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                startCall();
            }

            private void startCall() {
               
                Log.d("****", "Start");
                Calendar calendar = Calendar.getInstance();
                Intent intent = new Intent(AlarmManagerExample.this, MyService.class);
                PendingIntent pintent = PendingIntent.getService(AlarmManagerExample.this, 0, intent, 0);
                AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10*1000, pintent);
                Log.d("****", "Start");
               
            }
        });
       
        //stop service
       
        buttonStop.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
               
                stopService(new Intent(getBaseContext(), MyService.class));
            }
        });
       
       
    }

   
}