Monday, 26 August 2013

How to open a PDF via Intent from SD card



Here simple Intent call that use to open pdf Documents from our app.

                           File file = new File(Environment.getExternalStorageDirectory()
                                         .getAbsolutePath() + "/droidText/mysample.pdf");
                           Intent intent = new Intent(Intent.ACTION_VIEW);
                           intent.setDataAndType(Uri.fromFile(file), "application/pdf");
                           intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

                           startActivity(intent);

I hope this will help you 
Happy codddding :) 

Manage start activity for result in Android


Here is simple code to describe how to Manage start activity for result in Android. 
From your FirstActivity call the SecondActivity using startActivityForResult() method

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In your SecondActivity set the data which you want to return back to FirstActivity, If you don't want to return back don't set any.

 In secondActivity if you want to send back data:

 Intent returnIntent = new Intent();
 returnIntent.putExtra("result",result);
 setResult(RESULT_OK,returnIntent);    
 finish();


if you don't want to return data:

Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);       
finish();

Now in your FirstActivity class write following code for onActivityResult() method

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == 1) {
     if(resultCode == RESULT_OK){     
         String result=data.getStringExtra("result");         
     }
     if (resultCode == RESULT_CANCELED) {   
         //Write your code if there's no result
     }
  }
}
//onActivityResult


Friday, 16 August 2013

Encryption Decryption in Android


Hi friends today I made very simple Encryption Decryption Example in Android for you. where we use simple text file as example which we Encrypt it on Encrypt Btn click and Decrypt on decrypt button click
and save on sd card. but be sure to put file name as
sampleFile.

PS. we can also use Mp3 and videos file.

MainActivity.java




package com.example.encryptdecrypt;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

              Button encryptButton = (Button) findViewById(R.id.button1);
              Button DecryptButton = (Button) findViewById(R.id.button2);
              encryptButton.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           try {
                                  encrypt();
                           } catch (InvalidKeyException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (NoSuchAlgorithmException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (NoSuchPaddingException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (IOException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           }
                     }
              });

              DecryptButton.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           try {
                                  decrypt();
                           } catch (InvalidKeyException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (NoSuchAlgorithmException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (NoSuchPaddingException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (IOException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           }
                     }
              });

       }

       /**
        * Here is Both function for encrypt and decrypt file in Sdcard folder. we
        * can not lock folder but we can encrypt file using AES in Android, it may
        * help you.
        *
        * @throws IOException
        * @throws NoSuchAlgorithmException
        * @throws NoSuchPaddingException
        * @throws InvalidKeyException
        */

       static void encrypt() throws IOException, NoSuchAlgorithmException,
                     NoSuchPaddingException, InvalidKeyException {
              // Here you read the cleartext.
              File extStore = Environment.getExternalStorageDirectory();
              FileInputStream fis = new FileInputStream(extStore + "/sampleFile");
              // This stream write the encrypted text. This stream will be wrapped by
              // another stream.
              FileOutputStream fos = new FileOutputStream(extStore + "/encrypted");

              // Length is 16 byte
              SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
                           "AES");
              // Create cipher
              Cipher cipher = Cipher.getInstance("AES");
              cipher.init(Cipher.ENCRYPT_MODE, sks);
              // Wrap the output stream
              CipherOutputStream cos = new CipherOutputStream(fos, cipher);
              // Write bytes
              int b;
              byte[] d = new byte[8];
              while ((b = fis.read(d)) != -1) {
                     cos.write(d, 0, b);
              }
              // Flush and close streams.
              cos.flush();
              cos.close();
              fis.close();
       }

       static void decrypt() throws IOException, NoSuchAlgorithmException,
                     NoSuchPaddingException, InvalidKeyException {

              File extStore = Environment.getExternalStorageDirectory();
              FileInputStream fis = new FileInputStream(extStore + "/encrypted");

              FileOutputStream fos = new FileOutputStream(extStore + "/decrypted");
              SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
                           "AES");
              Cipher cipher = Cipher.getInstance("AES");
              cipher.init(Cipher.DECRYPT_MODE, sks);
              CipherInputStream cis = new CipherInputStream(fis, cipher);
              int b;
              byte[] d = new byte[8];
              while ((b = cis.read(d)) != -1) {
                     fos.write(d, 0, b);
              }
              fos.flush();
              fos.close();
              cis.close();
       }

}




Xml file
Activity_main.xml




<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="147dp"
        android:text="Encrypt" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_centerVertical="true"
        android:text="Decrypt" />

</RelativeLayout>


and Android manifest.xml requires WriteExternal_Storage permition




<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.encryptdecrypt"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.encryptdecrypt.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>




you can download complete example from here