Wednesday, February 22, 2012

Bluetooth Device Periodic Check in Android

public BluetoothAdapter bluetoothAdapter;

//start search
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter==null)return;
bluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
bluetoothflag=true;
registerReceiver(mReceiver, new IntentFilter(
BluetoothAdapter.ACTION_DISCOVERY_FINISHED));

///////////////////////////

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

String bluetooth = new String("111111111");
BluetoothDevice remote=bluetoothAdapter.getRemoteDevice(bluetooth);

if(device.equals(remote)){
deviceFoundFlag=true;
// bluetoothAdapter.cancelDiscovery();
}

}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

if(!deviceFoundFlag){
//////////alert if no device found
bluetoothflag=false;
}
if(bluetoothflag){
bluetoothAdapter.startDiscovery();
deviceFoundFlag=false;
}

}
}};

Android Wifi Connected info such as signal strength

WifiManager mainWifi;
String cSummary="Not Connected" ;
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = mainWifi.getConnectionInfo();
if(wifiInfo.getBSSID()!=null){
int strength=WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5);
int speed=wifiInfo.getLinkSpeed();
String units=WifiInfo.LINK_SPEED_UNITS;
String ssid=wifiInfo.getSSID();
cSummary=String.format("Connected to %s at %s%s. Strength %s/5", ssid,speed,units,strength);
if(strength==1)play();
}
return cSummary;

Saturday, February 4, 2012

Android Camera Capture

Manifest File

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

PhotoCaptureExample.java

package com.sarath.camera;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class PhotoCaptureExample extends Activity
{
protected Button _button;
protected ImageView _image;
protected TextView _field;
protected String _path;
protected boolean _taken;

protected static final String PHOTO_TAKEN = "photo_taken";

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

_image = ( ImageView ) findViewById( R.id.image );
_field = ( TextView ) findViewById( R.id.field );
_button = ( Button ) findViewById( R.id.button );
_button.setOnClickListener( new ButtonClickHandler() );

_path = Environment.getExternalStorageDirectory() + "/make_machine_example.jpg";
}

public class ButtonClickHandler implements View.OnClickListener
{
public void onClick( View view ){
Log.i("MakeMachine", "ButtonClickHandler.onClick()" );
startCameraActivity();
}
}

protected void startCameraActivity()
{
Log.i("MakeMachine", "startCameraActivity()" );
File file = new File( _path );

Uri outputFileUri = Uri.fromFile( file );

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

startActivityForResult( intent, 0 );
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.i( "MakeMachine", "resultCode: " + resultCode );
switch( resultCode )
{
case 0:
Log.i( "MakeMachine", "User cancelled" );
break;

case -1:
onPhotoTaken();
break;
}
}

protected void onPhotoTaken()
{
Log.i( "MakeMachine", "onPhotoTaken" );

_taken = true;

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;

Bitmap bitmap = BitmapFactory.decodeFile( _path, options );

_image.setImageBitmap(bitmap);

_field.setVisibility( View.GONE );
}

@Override
protected void onRestoreInstanceState( Bundle savedInstanceState){
Log.i( "MakeMachine", "onRestoreInstanceState()");
if( savedInstanceState.getBoolean( PhotoCaptureExample.PHOTO_TAKEN ) ) {
onPhotoTaken();
}
}

@Override
protected void onSaveInstanceState( Bundle outState ) {
outState.putBoolean( PhotoCaptureExample.PHOTO_TAKEN, _taken );
}
}

Friday, February 3, 2012

PDF In Android

Here is an application to create a pdf in android using iText file
First download the iText jar file the iTextxtra jar is not needed and then use the following code to create a table view pdf


package com.myapp.qr;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFCreator {
public static String FILE = "c:/temp/FirstPdf.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
public static ArrayList headings = new ArrayList();
public static ArrayList contents = new ArrayList();

public static void create() {
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
// addTitlePage(document);
addContent(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private static void addMetaData(Document document) {
document.addTitle("Bill");

}

private static void addContent(Document document) throws DocumentException {
createTable(document);

}

private static void createTable(Document subCatPart)
throws DocumentException {
PdfPTable table = new PdfPTable(3);

for (int i = 0; i < headings.size(); i++) {
String heading = headings.get(i);
PdfPCell c1 = new PdfPCell(new Phrase(heading));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);

}

table.setHeaderRows(1);

for (int i = 3; i < contents.size(); i++) {
String conStr = contents.get(i);

table.addCell(conStr);
}

subCatPart.add(table);

}

}

Android Wifi Analysis

Manifest file

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView android:id="@+id/mainText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

</LinearLayout>

WifiTester.java

package com.kites.wifi;

import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class WifiTester extends Activity {
TextView mainText;
WifiManager mainWifi;
WifiReceiver receiverWifi;
List wifiList;
StringBuilder sb = new StringBuilder();

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainText = (TextView) findViewById(R.id.mainText);
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mainText.setText(mainWifi+"");
WifiInfo wifiInfo = mainWifi.getConnectionInfo();
receiverWifi = new WifiReceiver();

registerReceiver(receiverWifi, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

mainWifi.startScan();
mainText.setText("\nStarting Scan...\n"+wifiInfo.toString());
}

public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Refresh");
return super.onCreateOptionsMenu(menu);
}

public boolean onMenuItemSelected(int featureId, MenuItem item) {
mainWifi.startScan();
mainText.setText("Starting Scan");
return super.onMenuItemSelected(featureId, item);
}

protected void onPause() {
unregisterReceiver(receiverWifi);
super.onPause();
}

protected void onResume() {
registerReceiver(receiverWifi, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}

class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++){
sb.append(new Integer(i+1).toString() + ".");
sb.append((wifiList.get(i)).toString());
sb.append("\n");
}
mainText.setText(sb);
}
}
}

Friday, December 9, 2011

AES Encryption

The program is a total solution for all who needs to implements AES Encryption

The Code:
/************************************************************************/
AESEncrypter.java



import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.*;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;

import java.security.spec.AlgorithmParameterSpec;

public class AESEncrypter
{
Cipher ecipher;
Cipher dcipher;

public AESEncrypter(SecretKey key)
{
// Create an 8-byte initialization vector
byte[] iv = new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
};

AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
try
{
ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

// CBC requires an initialization vector
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
}
catch (Exception e)
{
e.printStackTrace();
}
}

// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];

public void encrypt(InputStream in, OutputStream out)
{
try
{
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);

// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0)
{
out.write(buf, 0, numRead);
}
out.close();
}
catch (java.io.IOException e)
{
}
}

public void decrypt(InputStream in, OutputStream out)
{
try
{
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);

// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0)
{
out.write(buf, 0, numRead);
}
out.close();
}
catch (java.io.IOException e)
{
}
}

public static void main(String args[])
{
try
{
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key =(SecretKey)new SecretKeySpec(new byte[]{'0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5'},"AES");//kgen.generateKey();

AESEncrypter encrypter = new AESEncrypter(key);
encrypter.encrypt(new FileInputStream("2.pdf"),new FileOutputStream("1.txt"));


encrypter.decrypt(new FileInputStream("1.txt"),new FileOutputStream("100.pdf"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

/**********************************************************************/

Accessing Accelerometer In Android

This program can be used to measure the level of x,y,z acc.

The manifest file
<uses-permission android:name="android.permission.LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

The layout file(main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/accText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

The Activity Class(AccelerometerTest.java)

package com.sarath.accelerometertest;

import android.app.Activity;
import android.os.Bundle;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;

public class AccelerometerTest extends Activity {

private TextView accText;
private SensorManager myManager;
private List sensors;
private Sensor accSensor;
private float oldX, oldY, oldZ = 0f;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

accText = (TextView)findViewById(R.id.accText);

// Set Sensor + Manager
myManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensors = myManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(sensors.size() > 0)
{
accSensor = sensors.get(0);
}
}

private void updateTV(float x, float y, float z)
{
/*float thisX = x - oldX * 10;
float thisY = y - oldY * 10;
float thisZ = z - oldZ * 10;
*/
float thisX = (x - oldX) * 10;
float thisY = (y - oldY) * 10;
float thisZ = (z - oldZ) * 10;
accText.setText("x: " + Math.round(thisX) + ";\n y:" + Math.round(thisY) + ";\n z: " + Math.round(thisZ));

oldX = x;
oldY = y;
oldZ = z;
}

private final SensorEventListener mySensorListener = new SensorEventListener()
{
public void onSensorChanged(SensorEvent event)
{
updateTV(event.values[0],
event.values[1],
event.values[2]);
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {}
};

@Override
protected void onResume()
{
super.onResume();
myManager.registerListener(mySensorListener, accSensor, SensorManager.SENSOR_DELAY_GAME);
}

@Override
protected void onStop()
{
myManager.unregisterListener(mySensorListener);
super.onStop();
}
}