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

How to creat Hidden Directory Android



We can create Hidden Directory Very Simple As



File direct = new File(Environment.getExternalStorageDirectory()
                           + "/.test");

              if (!direct.exists()) {
                     if (direct.mkdir()) {
                           // directory is created;
                     }

              }



above code is create folder with name ".test" (in SD CARD) then save your data(file, video.. whatever) in this folder user cant access it in normal situations because its hidden.

Wednesday, 14 August 2013

Android Exception

Android Exception

This section on Android exceptions explains the exceptions and the work around for android exception that occur in android application development  Android system creates some problems or errors and here we are discussing how to handle these errors. These are the type errors generated by an android system and define how to handle these errors.
  1. Clean Project
  2. Problems with Android Debug Bridge (adb)
  3. LogCat
  4. Emulator does not start
  5. Timeout during deployment
  6. Install failed due to insufficient storage
  7. Debug Certificate expired
  8. Error message for @override
  9. Missing Imports
  10. Eclipse Tips
1)      Clean Project
An android system generates the following errors.
a)      Project … is missing required source folder: ‘gen’
b)      The project could not be built until build path errors are resolved.
c)      Unable to open class file R.java.
In order to solve the above errors we are using clean project operation. Here we are selecting the project menu and after that we select Project→ Clean.
2)       Problems with Android Debug Bridge (adb)
Android system generates communication error. This error generated at the time of communication between emulator and our android device.
Eclipse allows resetting the adb in case this causes problems. Select therefore the DDMS perspective via Window → Open Perspective → Other → DDMS
To restart the adb, select the “Reset adb” in the Device View.
Android Device View
Android Device View
3)      LogCat
The LogCat view helps to display the log messages of our android device and also it helps to analyze the problems.
Eg: – Java exception of our program will display here.
To open this view, select Window → Show View → Other → Android → LogCat.
4)      Emulator does not start:-
If your emulator does not start, make sure that the android-sdk version is in a path without any spaces in the path name.
5)      Timeout during deployment
For solving the timeout issues during deployment we can increase the default timeout in the eclipse. These are the steps to set the default timeout.
Select Window → Preferences → Android → DDMS and increase the “ADB connection timeout (in ms)” value.
6)      Install failed due to insufficient storage
Sometime the android shows an installation error message or the emulator will refuse to install an application. At this time it shows the below error message.
INSTALL_FAILED_INSUFFICIENT_STORAGE.
By default the AVD gives only 64M for storing the android applications. By solving installation error we are using two methods
1)      Clean our installed application by restarting the emulator and selecting the “Wipe user data” flag.
2)      Set the data partition size, if we press edit on the AVD we can set the “Ideal size of data partition” property through the “New” button.
Edit Android Virtual Device
Edit Android Virtual Device
7)      Debug Certificate expired
If you switch to the folder which consists of the android AVD we get an error message like “Debug Certificate expired”.
Eg: – “.android” under Linux and delete the “debug.keystore” file. This file is only valid for a year and if not present Eclipse will regenerate the password.
8)      Error message for @override
This error is a type of annotation error. If this error happens for @override we change the Java compiler level to Java 1.6. These are the steps to handle this type of error.
Right-click on the project, select Properties → Java Compiler → Compiler compliance level and select “1.6″ in the drop-down box.
9)      Missing Imports
Java required the classes which are either fully qualified or declared through imports. Missing of fully qualified or declaration leads to an error message. The error message is shown like this “XX cannot be resolved to a variable”. For solving this problem, right-click in our Editor and select Source → Organize Imports to important required packages.
10)  Eclipse Tips
For creating the efficient Eclipse choose Window → Preferences → Java → Editor → Save Actions and select that the source code should be formatted and that the imports should be organized at every save.

Hope the above tips on the android exception will provide an insight on solving the exceptions that you encounter during android application development.

Tips every Android developer should know


Tips every Android developer should know, or things we're doing wrong and need to fix in our Android builds.




A couple Google engineers, Dan Galpin and Ian Lewis, gave a talk at GDC this morning on things people do that prevent their apps from getting featured. Here are my notes on what they said.

1) Don't run in compatibility mode. Google hates the menu button on newer Android devices, so set the target SDK version to the newest (15).
2) Games that use the lights out menu option are cool. This is View.Status_Bar_Hidden.
3) Don't override the basic button behavior like volume or home or power. The back button is fair game though. Back should be treated as the escape key and not a quick exit button because it is easy to accidentally press it on honeycomb and ice cream sandwich.
4) Don't use a "do you want to quit" button when hitting back from the main menu. Just exit.
5) Don't play music on the lock screen when coming back from sleep. This one has driven us nuts trying to figure out. You have to overload onWindowFocusChanged as well as the sleep functions, and they can be called in any order.
6) Gracefully cleanup your OGL contexts.
7) For in-app purchases, don't assume your app will be open when the confirmation comes through.
8) Always have a tablet promo graphic. They scale this down to use it for feature spots on phones. This is the big banner that shows up when viewing the game on the web or on a tablet.
9) Localizing the market text is recommended, with the languages EFIGS-CJK.

Best Android Resources



http://labs.rampinteractive.co.uk/android_dp_px_calculator/


http://wptrafficanalyzer.in/blog/

http://www.technotalkative.com/

http://angrytools.com/

http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html

http://www.vogella.com/


http://www.freepik.com/free-psd/active-button-dark-power_566923.htm

Top 11 Resources By Hasmukh

1 http://hasmukhbhadani.blogspot.in/
2.http://android-er.blogspot.in/
4.http://saigeethamn.blogspot.in/2010/05/gallery-view-android-developer tutorial.html
5.http://coderzheaven.com/2011/10/
6.http://androidcodesnips.blogspot.in/2011/05/dom-parsing-example.html
7.http://androiddevelopement.blogspot.in/
8.db= http://mobdev.olin.edu/mobdevwiki/FrontPage/Tutorials/Databases
http://matrix-examplecode.blogspot.in/2011/08/sqlite-external-database-connectivity.html
9.http://www.technotalkative.com/
**XMl parsing:**
10.http://drdobbs.com/blogs/jvm/231002580
http://matrix-examplecode.blogspot.in/2012/03/android-dom-parser-example.html
11.http://android-coding.blogspot.in
12.http://blackberryfeeds.blogspot.in/
13.http://www.jmanzano.es/blog/?p=220&lang=en

14 http://androidcustomviews.com/

15  http://www.androidviews.net/

16 https://www.parse.com/

17  https://github.com/

http://developer.digitalaria.com/devguide/gama/en/gama/pageflip_android.php

http://square.github.io/picasso/
http://www.androidviews.net/2013/01/pinterest-like-adapterview/

 Be Gradient Expert With following links
http://www.dibbus.com/2011/02/gradient-buttons-for-android/
http://krisanthonyviceral.blogspot.in/2012/03/ams-part-4-placing-and-customizing.html
http://krisviceral.com/2012/03/03/ams4/

UI Design Patterns
http://sixrevisions.com/user-interface/mobile-ui-design-patterns-inspiration/

My Best Json Viewer

http://www.jsoneditoronline.org/


http://mobisys.in/blog/

http://www.androidbegin.com/
http://www.androidhive.info/
http://www.vogella.com/
http://www.inappsquared.com/

www.mkyong.com

http://www.bongizmo.com/blog/android-resources-each-developer-should-know/
https://www.elance.com/q/blog/2010/05/the_10_best_android_resources_on_the_web.html
http://www.youtube.com/playlist?list=PLLnpHn493BHF33bSvIA0ySchxXkrib8TK
http://www.kilobolt.com/day-4-parts-of-an-android-application.html
http://www.ashokgelal.com/2013/01/writing-a-real-android-app-from-scratch-part-27-tabs-and-fragments/
http://www.androidviews.net/
http://androidweekly.net/

http://thenewboston.org/list.php?cat=6
http://libgdx.badlogicgames.com/
http://www.makeuseof.com/tag/6-android-websites-you-should-check-out/
http://www.androidtapp.com/25-awesome-google-android-websites-you-should-follow/
http://www.fromdev.com/2013/07/Android-Tutorials.html
http://mashable.com/2010/12/19/android-resources/


Removing an app icon from launcher


Removing an app icon from launcher

Creating an application that does not appear among the launchable applications with an icon is easy.
Just do not put a launcher activity into AndroidManifest.xml

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>


Removing an application icon after installation programatically is a bit more tricky.
You can not disable the icon itself, but you can disable one component of an application. So disabling the applications launcher activity will result its icon to be removed from launcher.

The code to do this is simple:

ComponentName componentToDisable =new ComponentName("com.helloandroid.apptodisable",
"com.helloandroid.apptodisable.LauncherActivity");
getPackageManager().setComponentEnabledSetting(componentToDisable,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);


There is a few things to know about this solution:
the disabled component will not be launchable in any way
other non disabled activities will be launchable from other applications
an application can only disable its own component. There is a permission "android.permission.CHANGE_COMPONENT_ENABLED_STATE", but it wont work, 3rd party applications can not have this permission
the icon will only disapper when the launcher is restarted, so likely on next phone reboot, forcing the launcher to restart is not recommended.

Security Permissions in Android

Security Permissions in Android


As we all know whenever we use a particular feature or API we need to request the permission in AndroidManifest.xml file with uses-permission element. If we don’t specify any permissions, then the application will not have any permission and application can do anything that does not require a permission. This link explains the permissions in android in more detail and this link lists the permissions in Android.

Permissions are granted to the application by package installer while installing. But not all the permissions will be granted to the system. There are some system permission which will not be granted to the user applications, but only to the system applications. Following are some of the permissions that may NOT be granted to the user application.


android.permission.ACCESS_CHECKIN_PROPERTIES
android.permission.ACCESS_SURFACE_FLINGER
android.permission.ACCOUNT_MANAGER
android.permission.BIND_APPWIDGET
android.permission.BIND_DEVICE_ADMIN
android.permission.BIND_INPUT_METHOD
android.permission.BIND_WALLPAPER
android.permission.BRICK
android.permission.BROADCAST_PACKAGE_REMOVED
android.permission.BROADCAST_SMS
android.permission.BROADCAST_WAP_PUSH
android.permission.CALL_PRIVILEGED
android.permission.CHANGE_COMPONENT_ENABLED_STATE
android.permission.CLEAR_APP_USER_DATA
android.permission.CONTROL_LOCATION_UPDATES
android.permission.DELETE_CACHE_FILES
android.permission.DELETE_PACKAGES
android.permission.DEVICE_POWER
android.permission.DIAGNOSTIC
android.permission.FACTORY_TEST
android.permission.FORCE_BACK
android.permission.GLOBAL_SEARCH
android.permission.HARDWARE_TEST
android.permission.INJECT_EVENTS
android.permission.INSTALL_LOCATION_PROVIDER
android.permission.INSTALL_PACKAGES
android.permission.INTERNAL_SYSTEM_WINDOW
android.permission.MANAGE_APP_TOKENS
android.permission.MASTER_CLEAR
android.permission.READ_FRAME_BUFFER
android.permission.READ_INPUT_STATE
android.permission.REBOOT
android.permission.SET_ACTIVITY_WATCHER
android.permission.SET_ORIENTATION
android.permission.SET_PREFERRED_APPLICATIONS
android.permission.SET_TIME
android.permission.STATUS_BAR
android.permission.UPDATE_DEVICE_STATS
android.permission.WRITE_GSERVICES
android.permission.WRITE_SECURE_SETTINGS


To get these permissions, the application must be signed with the key which used to sign the platform. This may be different for manufacturers. So it practically not possible to get these permissions granted to a user application.

Note: While playing with PowerManager.reboot I was so stupid I thought my application will be granted the permission android.permission.REBOOT, but it was not granted. Then I created an application requesting all the permissions and above list of permissions are not granted. Hope this will help you when you request a permission next time.