Monday 22 December 2014

Android Example of Reading File From raw Folder

Hello friends'

Here is an example of reading file from raw folder in Android.

Make a file named my_file.txt (example) in raw folder of res and write some content on it.



In the Layout file one button and one textview is used.

when click on button, file will be read and its content will display on textview.

The layout file code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click here to read file" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:text="Small Text"
        android:gravity="center"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>


MainActivity java file code:

package in.blogspot.longjamcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

private Button button;
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
String string="";
StringBuffer stringBuffer = new StringBuffer();
InputStream inputStream = MainActivity.this.getResources().openRawResource(R.raw.my_file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
if (inputStream!=null) {
while ((string = reader.readLine()) != null) {
stringBuffer.append(string + "\n" );
}
}
inputStream.close();
textView.setText(stringBuffer);
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}

The sample output:





















For full source code click here

Sunday 21 December 2014

Full Screen Dialog Example


Hello Friends'

Here is a simple example of full screen dialog.

Two layout is used
One is main layout and other is dialog layout.

activity_main Layout file code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center" >

    <TextView
        android:id="@+id/dialogTextView"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:textSize="18sp"
        android:textStyle="bold"
        android:gravity="center_vertical"
        android:padding="5dp"
<--setting backgroung from drawable folder-->
        android:background="@drawable/rectanguler_background"
        android:text="Click Here For Full Screen Dialog" />

</LinearLayout>

full_screen_dialog_layout code

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/blue"
        android:gravity="center_vertical" >
    </LinearLayout>
<--used edit text to add search functionality-->
    <EditText
        android:id="@+id/searchEditText"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_margin="2dp"
<--setting backgroung from drawable folder-->
        android:background="@drawable/rectanguler_background"
        android:hint="Search..."
        android:padding="5dp" />
<--List View to display list item-->
    <ListView
        android:id="@+id/cityListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>


</LinearLayout>


rectanguler_background file put this file in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#CABBBBBB" />
        </shape>
    </item>

    <item
        android:bottom="1dp"
        android:left="1dp"
        android:top="1dp"
        android:right="1dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
        </shape>
    </item>
</layer-list>

MainActivity java file code

package in.blogspot.longjamcode;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

private TextView dialogTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialogTextView = (TextView) findViewById(R.id.dialogTextView);
dialogTextView.setOnClickListener(clickListener);
}
private OnClickListener clickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.this, android.R.style.DeviceDefault_Light_ButtonBar); // making dialog full screen

//inflating dialog layout
dialog.setContentView(R.layout.full_screen_dialog_layout);
ListView cityListView = (ListView) dialog.findViewById(R.id.cityListView);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,  android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.city_array));
cityListView.setAdapter(adapter);
cityListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dialogTextView.setText(parent.getAdapter().getItem(position).toString());
dialog.dismiss();
}
});
//adding search functionality 
EditText searchEditText = (EditText) dialog.findViewById(R.id.searchEditText);
searchEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
dialog.show();
}
};
}

Output:





For full source code click here

Saturday 20 December 2014

Highlight Selected Items in ListView


Hello Friends'

In this post i will show how to highlight selected items in ListView.


For this took two layout.

Main layout containing ListView. 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
<--choiceMode is multipleChoice-->
        android:choiceMode="multipleChoice" >
    </ListView>

</LinearLayout>

This layout is used for each row of ListView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
<--This attribute will highlight the row-->
    android:background="?android:attr/activatedBackgroundIndicator"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center_vertical"
        android:paddingLeft="10dp"
        android:text="TextView" />

</LinearLayout>


MainActivity java file code is:

package in.blogspot.longjamcode;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting String array fron res folder
String[] array = getResources().getStringArray(R.array.city_array);
ListView listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_row_layout, R.id.textView1, array);
listView.setAdapter(adapter);
}
}

The Output is:

For full source code click here

Thursday 18 December 2014

Reading Call Log

Hello Friends


Here i am showing you how to read call log's information in android.
Its pretty simple.

First in order to read call logs we need to give permission to manifest file.

The manifest file code:

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

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

Mandatory to give this permission
    <uses-permission android:name="android.permission.READ_CALL_LOG" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>


Here i am using a TextView to print call logs information and its inside a Scroll View.

The layout file code:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:padding="5dp"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/callLogTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>
    </ScrollView>

</LinearLayout>

Here the MainActivity java file code:

package in.blogspot.longjamcode;

import java.util.Date;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView callLogTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callLogTextView = (TextView) findViewById(R.id.callLogTextView);

StringBuilder sb = new StringBuilder();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CallLog.Calls.CONTENT_URI, null,null, null, null);
while (cursor.moveToNext()) {
String phoneNumber = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
String callType = cursor.getString(cursor.getColumnIndex(CallLog.Calls.TYPE));
String callDate = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
String callDuration = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION));
String callTypeTemp = null;
Date date = new Date(Long.parseLong(callDate));
if(callType.equals("1"))
callTypeTemp = "INCOMING_TYPE";
else if(callType.equals("2"))
callTypeTemp = "OUTGOING_TYPE";
else if(callType.equals("3"))
callTypeTemp = "MISSED_TYPE";
sb.append("\nPhone Number:   " + phoneNumber + " \nName:   " + name + " \nCall Type:   "
+ callTypeTemp + " \nCall Date:   " + date + " \nCall duration:   " + callDuration+" sec");
sb.append("\n \n");
}
cursor.close();
callLogTextView.setText(sb);
}
}




For full source code click here

Circular ImageView

Hello friends'

Today i will show, how to make a circular image through code.
Its pretty simple...
Lets see,

For this i am taking an ImageView and a sample image named default_image in drawable folder.

The Layout file code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="100dp"
        android:layout_height="100dp" />

</LinearLayout>


The MainActivity java file code:

package in.blogspot.longjamcode;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image = (ImageView) findViewById(R.id.imageView);

//getting bitmap from drawable
Bitmap originalImageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.default_image);

//resizing original bitmap, passed originalImageBitmap, the new bitmap's desired width, new bitmap's desired height, true if the source should be filtered.

Bitmap resized = Bitmap.createScaledBitmap(originalImageBitmap, 100, 100, false);
image.setImageBitmap(getRoundedBitmap(resized, 100));
}

//method to get rounded bitmap.
private Bitmap getRoundedBitmap(Bitmap bitmap, int pixels) {
Bitmap result = null;
try {
result = Bitmap.createBitmap(100,100, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, 200, 200);
paint.setAntiAlias(true);
canvas.drawCircle(50, 50, 50, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
} catch (NullPointerException e) {
} catch (OutOfMemoryError o) {
}
return result;
}
}

The sample output is




For full source code click here

Tuesday 16 December 2014

Dynamic Receiver

Hello Friends'

Here i will show you a very simple example in android about registering and unregistered BroadcastReceiver through code.

In this simple app i put two button
one for registering receiver and other for unregistered.

The sample layout code is as follow...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center" >

    <Button
        android:id="@+id/registerButton"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register Receiver" />

    <Button
        android:id="@+id/unRegisterButton"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="20dp"
        android:text="UnRegister Receiver" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Wait for message to come"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>

Now lets see the SMSReceiver class....


package in.blogspot.longjamcode;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver {

//a boolean variable to check whether receiver is register or not
public static boolean isReceiverRegister;
private static SMSReceiver receiver;

//making constructor private so that it can't call from outside this class
private SMSReceiver(){}

//a method to get object of SMSReceiver class
public static SMSReceiver getSMSReceiver() {
if(receiver == null) {
receiver = new SMSReceiver();
return receiver;
}
else
return receiver;
}

//this method will call whenever a new message is received 
public void onReceive(final Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String message = currentMessage.getDisplayMessageBody();
Toast.makeText(context, ""+message, Toast.LENGTH_LONG).show();
}  
}
}

//method to register receiver
public static void registerBroadcastReceiver (Context context, BroadcastReceiver receiver) {
if(!SMSReceiver.isReceiverRegister) {
SMSReceiver.isReceiverRegister = true;
context.registerReceiver(receiver,  new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
Toast.makeText(context, "Receiver is Register", Toast.LENGTH_SHORT).show();
}
}


//method to unregistered receiver
public static void unRegisterBroadcastReceiver (Context context, BroadcastReceiver receiver) {
if(SMSReceiver.isReceiverRegister) {
SMSReceiver.isReceiverRegister = false;
context.unregisterReceiver(receiver);
Toast.makeText(context, "Receiver is UnRegister", Toast.LENGTH_SHORT).show();
}
}
}


MainActivity java file will like the following...


package in.blogspot.longjamcode;

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

public class MainActivity extends Activity {

private Button registerReceiver, unRegisterReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver = (Button)findViewById(R.id.registerButton);
unRegisterReceiver = (Button)findViewById(R.id.unRegisterButton);
registerReceiver.setTag("register");
unRegisterReceiver.setTag("unregister");
registerReceiver.setOnClickListener(buttonListener);
unRegisterReceiver.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
@Override
public void onClick(View v) {
if(v.getTag().equals("register"))
SMSReceiver.registerBroadcastReceiver(MainActivity.this, SMSReceiver.getSMSReceiver());
else
SMSReceiver.unRegisterBroadcastReceiver(MainActivity.this, SMSReceiver.getSMSReceiver());
}
};

}


Lastly Manifest file...

In this manifest we are not registering receiver

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

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
give this two uses permission
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />

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

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

</manifest>


The output will be like...






Full source code download click here

Loading Image after cropping


Hi Friends,

In this blog i will make a simple app in which one image view is here by clicking image view a dialog will popup with option "Take Photo", "Choose from Library" and "Cancel".

In Take Photo user will click a photo to set on ImageView.
In Choose from Library user will allow to set image from library.

Here is the code.....

In the activity_main.xml file I simple take a ImageView....
Just paste the following in your code.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

<--Here i took a default image which is set on ImageView dy default-->
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/default_image" />

</LinearLayout>

Here comes the main code.
In MainActivity.java File paste the following code

package in.blogspot.longjamcode;

import java.io.File;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainActivity extends Activity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);

//here I set OnClickListener for ImageView
imageView.setOnClickListener(imageClickListener);
}

//here is imageClickListener when user click imageView this listener will called
private OnClickListener imageClickListener = new OnClickListener() {
@Override
public void onClick(View v) {

//A dialog will popup to user to choose their preference 
final CharSequence[] items = { "Take Photo", "Choose from Library","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
//intent to start up camera 
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

//on finished it will called the onActivityResult callback method with request code 101
startActivityForResult(intent, 101);
} else if (items[item].equals("Choose from Library")) {

//intent to pick image from library
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

//on finished it will called the onActivityResult callback method with request code 102
startActivityForResult(i, 102);
} else if (items[item].equals("Cancel")) {

//This will simply dismiss the dialog
dialog.dismiss();
}
}
});
builder.show();
}
};

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap photo = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101 && resultCode == RESULT_OK ) {
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
try {
cropCapturedImage(Uri.fromFile(file));
}
catch(ActivityNotFoundException aNFE){
}
}
else if (requestCode == 102 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
File file = new File(picturePath);
try {
cropCapturedImage(Uri.fromFile(file));
}
catch(ActivityNotFoundException aNFE){
}
}
else if(requestCode == 2 && resultCode == RESULT_OK && data != null) {
Bundle extras = data.getExtras();
photo = extras.getParcelable("data");

//here set image on imageView
imageView.setImageBitmap(photo);
}

}

//Method  to crop Image
public void cropCapturedImage(Uri picUri){
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
//this will called the onActivityResult callback method with request code 2
startActivityForResult(cropIntent, 2);
}
}

The output will be like...























For full project Click here

Google Cloud Integration (Android + Java Server)


Hello Friends,


Today i will show you how to integrate GCM in android app.
For this i will make an app server in java servlet.

steps to follow
  1. Go to Google Developers Console
  2. Build GCM Client  an android app
  3. Build GCM Server java app server
Google Developers Console is a place where you  activate Google services that you want to integrate in your application.
steps to follow
  • 1 Create a Project
  • 2 Get Project Number
  • 3 Enable Google Cloud Messaging for Android
  • 4 Create Server API Key
Go to Google Developers Console















Give your project name















You will get your project number note it down...















go to APIs and enable Google Cloud Messaging for Android















go to Credentials















Click at Server Key to generate Server Key















Type "my public ip address" at google and note down your public ip address















do as the following image...















Finally you will get your server key note it down















Note down your Server key and Project Number.

Thats all with Google Developers Console

For GCM Server go to next post click here

For GCM client click here

GCM Integration (Android App)

Hello Friends,

Here i will show code for client side android.

Manifest file


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

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

<--give all these uses-permission-->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <permission
        android:name="in.blogspot.longjamcode.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.gcmdemo.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />
 
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>

<--here is Receiver-->
        <receiver
            android:name=".GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="in.blogspot.longjamcode" />
            </intent-filter>
        </receiver>
    </application>

</manifest>


Simple Layout file 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="center"
    tools:context="in.blogspot.longjamcode.MainActivity" >
<--This button is for Registering with cloud server-->
    <Button
        android:id="@+id/registerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register with cloud server" />
<--This button is to share RegisterId with App server-->
    <Button
        android:id="@+id/sendButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Share register id with app server" />

</LinearLayout>

Following is MainActivity.java file


package in.blogspot.longjamcode;

import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLPeerUnverifiedException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

private final String PROJECT_NUMBER = "YOUR PROJECT NUMBER";
private Button registerButton, sendButton;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerButton = (Button) findViewById(R.id.registerButton);
sendButton = (Button) findViewById(R.id.sendButton);
preferences = getSharedPreferences("gcm", Context.MODE_PRIVATE);
registerButton.setOnClickListener(register);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MyAsynClass asynClass = new MyAsynClass();
asynClass.execute("http://YOUR IP ADDRESS:8080/GCMServer/RegisterServlet");
}
});
}
OnClickListener register = new OnClickListener() {
@Override
public void onClick(View v) {

//Getting gcm_id from preference and check it whether it exist or not if not call registerWithCloudServer() method

if(preferences.getString("gcm_id", "").length() == 0) {
registerWithCloudServer();
}
else {
Toast.makeText(MainActivity.this, "Already Register", Toast.LENGTH_SHORT).show();
}
}
};

//Method to register with cloud server
public void registerWithCloudServer(){
Intent registrationIntent=new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
registrationIntent.putExtra("sender", PROJECT_NUMBER);
startService(registrationIntent);
}

private class MyAsynClass extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
HttpPost httpPost= new HttpPost(params[0]);
DefaultHttpClient client = new DefaultHttpClient();
try {
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("gcm_id", preferences.getString("gcm_id", "")));
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
return responseText;
}catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
return null;
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
}

Following is receiver....

package in.blogspot.longjamcode;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.widget.Toast;

public class GCMBroadcastReceiver extends WakefulBroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {      
String action=intent.getAction();
if(action.equalsIgnoreCase("com.google.android.c2dm.intent.REGISTRATION")){
onRegistration(context,intent);
}else if(action.equalsIgnoreCase("com.google.android.c2dm.intent.RECEIVE")){
NotificationManager notificationManager = (NotificationManager) 
context.getSystemService(context.NOTIFICATION_SERVICE); 
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(), Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notify=new Notification(R.drawable.ic_launcher,"icon",System.currentTimeMillis());
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(alarmSound!=null)
notify.sound = alarmSound;
notify.setLatestEventInfo(context, "Notification", intent.getExtras().getString("message"), pendingIntent);
notificationManager.notify(0, notify); 
}
}
public void onRegistration(Context context,Intent intent){
String registrationID=intent.getStringExtra("registration_id");
if(registrationID!=null){
SharedPreferences preferences = context.getSharedPreferences("gcm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("gcm_id",registrationID);
editor.commit();
Toast.makeText(context, ""+registrationID, Toast.LENGTH_SHORT).show();
}else
Toast.makeText(context, "error in registration" , Toast.LENGTH_LONG).show();
}
}

And don't to add google-play-services-lib to your project

The output will be like


when message came it will notify on notification bar like...






GCM Integration (Java Server)


Hello Friends,

I will code here GCM AppServer in java.

You need gcm-server.jar and json-simple-1.1.1 jar
click here to get jar files.



Don't forget to import this two jar....


Here two servlet class one for getting registration id from android app.
Other for sending message to GCM server which will in turn sent to android app.
One jsp file name index.jsp the message we pass on this will forwarded to android app through GCM.

Following is RegisterServlet class....

package in.blogspot.longjamcode;

import java.io.BufferedWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**

 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// gcm registration id from client android device will get here

String gcm_id = request.getParameter("gcm_id");

  //we store gcm_id on a file which will be used latter

File file = new File("/YOUR_FILE_NAME.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(gcm_id);
bw.close();
}
}

Following is SentServlet Class this class will sent message to mobile device through GCM


package in.blogspot.longjamcode;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Sender;
import com.google.android.gcm.server.Result;

/**
 * Servlet implementation class SentServlet
 */
@WebServlet("/SentServlet")
public class SentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String GOOGLE_SERVER_KEY = "YOUR SERVER KEY";
static final String MESSAGE_KEY = "message";

/**
* @see HttpServlet#HttpServlet()
*/
public SentServlet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// reading regId which save in file before
BufferedReader br = new BufferedReader(new FileReader("YOUR_FILE_NAME.txt"));
String regId = br.readLine();
br.close();

                //userMessage will get from jsp file
String userMessage = request.getParameter("message");
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(30)
.delayWhileIdle(true).addData(MESSAGE_KEY, userMessage).build();
System.out.println("regId: " + regId);
Result result = sender.send(message, regId, 1);
request.setAttribute("pushStatus", result.toString());
}
}

and following is index.jsp file....

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>App Server</title>
</head>
<body>

<h1>GCM Server in Java</h1>

<form action="SentServlet" method="post">

<div>

<--Message which is going to forward will get from this textarea-->
<textarea rows="2" name="message" cols="23"
></textarea>
</div>
<div>

<--When hit this will call the SentServlet class -->
<input type="submit" value="Push Notification" />
</div>
</form>
</body>
</html>


You can download full project...

full source code click here