Saturday, March 30, 2013

Blocking Incoming call - Android

Step 1:
Create Broadcast receiver class for incoming call
package com.javaorigin.android.sample;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneCallReceiver extends BroadcastReceiver {
Context context = null;
private static final String TAG = "Phone call";
private ITelephony telephonyService;

@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Receving....");
TelephonyManager telephony = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Class c = Class.forName(telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
//telephonyService.silenceRinger();
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
}

}


}

Step 2:
Create IDL interface for getting core Telephony service
package name must be com.android.internal.telephony

FileName : ITelephony.aidl
package com.android.internal.telephony;

interface ITelephony {


boolean endCall();


void answerRingingCall();


void silenceRinger();

}

Step 3:
AndroidManifest.xml configuration


package="com.javaorigin.android.sample"
android:versionCode="1"
android:versionName="1.0">

















Thursday, March 28, 2013

Android Simple Calendar

In this tutorial, I am implementing the Calendar.

Java Code:

package com.examples;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class SimpleCalendarViewActivity extends Activity implements OnClickListener
{
private static final String tag = "SimpleCalendarViewActivity";

private ImageView calendarToJournalButton;
private Button selectedDayMonthYearButton;
private Button currentMonth;
private ImageView prevMonth;
private ImageView nextMonth;
private GridView calendarView;
private GridCellAdapter adapter;
private Calendar _calendar;
private int month, year;
private final DateFormat dateFormatter = new DateFormat();
private static final String dateTemplate = "MMMM yyyy";

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

_calendar = Calendar.getInstance(Locale.getDefault());
month = _calendar.get(Calendar.MONTH) + 1;
year = _calendar.get(Calendar.YEAR);
Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: " + year);

selectedDayMonthYearButton = (Button) this.findViewById(R.id.selectedDayMonthYear);
selectedDayMonthYearButton.setText("Selected: ");

prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
prevMonth.setOnClickListener(this);

currentMonth = (Button) this.findViewById(R.id.currentMonth);
currentMonth.setText(dateFormatter.format(dateTemplate, _calendar.getTime()));

nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
nextMonth.setOnClickListener(this);

calendarView = (GridView) this.findViewById(R.id.calendar);

// Initialised
adapter = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, month, year);
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
}

/**
*
* @param month
* @param year
*/
private void setGridCellAdapterToDate(int month, int year)
{
adapter = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, month, year);
_calendar.set(year, month - 1, _calendar.get(Calendar.DAY_OF_MONTH));
currentMonth.setText(dateFormatter.format(dateTemplate, _calendar.getTime()));
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
}

@Override
public void onClick(View v)
{
if (v == prevMonth)
{
if (month <= 1)
{
month = 12;
year--;
}
else
{
month--;
}
Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month: " + month + " Year: " + year);
setGridCellAdapterToDate(month, year);
}
if (v == nextMonth)
{
if (month > 11)
{
month = 1;
year++;
}
else
{
month++;
}
Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month: " + month + " Year: " + year);
setGridCellAdapterToDate(month, year);
}

}

@Override
public void onDestroy()
{
Log.d(tag, "Destroying View ...");
super.onDestroy();
}

// ///////////////////////////////////////////////////////////////////////////////////////
// Inner Class
public class GridCellAdapter extends BaseAdapter implements OnClickListener
{
private static final String tag = "GridCellAdapter";
private final Context _context;

private final List list;
private static final int DAY_OFFSET = 1;
private final String[] weekdays = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
private final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
private final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
private final int month, year;
private int daysInMonth, prevMonthDays;
private int currentDayOfMonth;
private int currentWeekDay;
private Button gridcell;
private TextView num_events_per_day;
private final HashMap eventsPerMonthMap;
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy");

// Days in Current Month
public GridCellAdapter(Context context, int textViewResourceId, int month, int year)
{
super();
this._context = context;
this.list = new ArrayList();
this.month = month;
this.year = year;

Log.d(tag, "==> Passed in Date FOR Month: " + month + " " + "Year: " + year);
Calendar calendar = Calendar.getInstance();
setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
Log.d(tag, "New Calendar:= " + calendar.getTime().toString());
Log.d(tag, "CurrentDayOfWeek :" + getCurrentWeekDay());
Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());

// Print Month
printMonth(month, year);

// Find Number of Events
eventsPerMonthMap = findNumberOfEventsPerMonth(year, month);
}
private String getMonthAsString(int i)
{
return months[i];
}

private String getWeekDayAsString(int i)
{
return weekdays[i];
}

private int getNumberOfDaysOfMonth(int i)
{
return daysOfMonth[i];
}

public String getItem(int position)
{
return list.get(position);
}

@Override
public int getCount()
{
return list.size();
}

/**
* Prints Month
*
* @param mm
* @param yy
*/
private void printMonth(int mm, int yy)
{
Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
// The number of days to leave blank at
// the start of this month.
int trailingSpaces = 0;
int leadSpaces = 0;
int daysInPrevMonth = 0;
int prevMonth = 0;
int prevYear = 0;
int nextMonth = 0;
int nextYear = 0;

int currentMonth = mm - 1;
String currentMonthName = getMonthAsString(currentMonth);
daysInMonth = getNumberOfDaysOfMonth(currentMonth);

Log.d(tag, "Current Month: " + " " + currentMonthName + " having " + daysInMonth + " days.");

// Gregorian Calendar : MINUS 1, set to FIRST OF MONTH
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());

if (currentMonth == 11)
{
prevMonth = currentMonth - 1;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 0;
prevYear = yy;
nextYear = yy + 1;
Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
}
else if (currentMonth == 0)
{
prevMonth = 11;
prevYear = yy - 1;
nextYear = yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 1;
Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
}
else
{
prevMonth = currentMonth - 1;
nextMonth = currentMonth + 1;
nextYear = yy;
prevYear = yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
}

// Compute how much to leave before before the first day of the
// month.
// getDay() returns 0 for Sunday.
int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
trailingSpaces = currentWeekDay;

Log.d(tag, "Week Day:" + currentWeekDay + " is " + getWeekDayAsString(currentWeekDay));
Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);

if (cal.isLeapYear(cal.get(Calendar.YEAR)) && mm == 1)
{
++daysInMonth;
}

// Trailing Month days
for (int i = 0; i < trailingSpaces; i++)
{
Log.d(tag, "PREV MONTH:= " + prevMonth + " => " + getMonthAsString(prevMonth) + " " + String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i));
list.add(String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i) + "-GREY" + "-" + getMonthAsString(prevMonth) + "-" + prevYear);
}

// Current Month Days
for (int i = 1; i <= daysInMonth; i++)
{
Log.d(currentMonthName, String.valueOf(i) + " " + getMonthAsString(currentMonth) + " " + yy);
if (i == getCurrentDayOfMonth())
{
list.add(String.valueOf(i) + "-BLUE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
}
else
{
list.add(String.valueOf(i) + "-WHITE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
}
}

// Leading Month days
for (int i = 0; i < list.size() % 7; i++)
{
Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
list.add(String.valueOf(i + 1) + "-GREY" + "-" + getMonthAsString(nextMonth) + "-" + nextYear);
}
}

/**
* NOTE: YOU NEED TO IMPLEMENT THIS PART Given the YEAR, MONTH, retrieve
* ALL entries from a SQLite database for that month. Iterate over the
* List of All entries, and get the dateCreated, which is converted into
* day.
*
* @param year
* @param month
* @return
*/
private HashMap findNumberOfEventsPerMonth(int year, int month)
{
HashMap map = new HashMap();
// DateFormat dateFormatter2 = new DateFormat();
//
// String day = dateFormatter2.format("dd", dateCreated).toString();
//
// if (map.containsKey(day))
// {
// Integer val = (Integer) map.get(day) + 1;
// map.put(day, val);
// }
// else
// {
// map.put(day, 1);
// }
return map;
}

@Override
public long getItemId(int position)
{
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.calendar_day_gridcell, parent, false);
}

// Get a reference to the Day gridcell
gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
gridcell.setOnClickListener(this);

// ACCOUNT FOR SPACING

Log.d(tag, "Current Day: " + getCurrentDayOfMonth());
String[] day_color = list.get(position).split("-");
String theday = day_color[0];
String themonth = day_color[2];
String theyear = day_color[3];
if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null))
{
if (eventsPerMonthMap.containsKey(theday))
{
num_events_per_day = (TextView) row.findViewById(R.id.num_events_per_day);
Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
num_events_per_day.setText(numEvents.toString());
}
}

// Set the Day GridCell
gridcell.setText(theday);
gridcell.setTag(theday + "-" + themonth + "-" + theyear);
Log.d(tag, "Setting GridCell " + theday + "-" + themonth + "-" + theyear);

if (day_color[1].equals("GREY"))
{
gridcell.setTextColor(Color.LTGRAY);
}
if (day_color[1].equals("WHITE"))
{
gridcell.setTextColor(Color.WHITE);
}
if (day_color[1].equals("BLUE"))
{
gridcell.setTextColor(getResources().getColor(R.color.static_text_color));
}
return row;
}
@Override
public void onClick(View view)
{
String date_month_year = (String) view.getTag();
selectedDayMonthYearButton.setText("Selected: " + date_month_year);

try
{
Date parsedDate = dateFormatter.parse(date_month_year);
Log.d(tag, "Parsed Date: " + parsedDate.toString());

}
catch (ParseException e)
{
e.printStackTrace();
}
}

public int getCurrentDayOfMonth()
{
return currentDayOfMonth;
}

private void setCurrentDayOfMonth(int currentDayOfMonth)
{
this.currentDayOfMonth = currentDayOfMonth;
}
public void setCurrentWeekDay(int currentWeekDay)
{
this.currentWeekDay = currentWeekDay;
}
public int getCurrentWeekDay()
{
return currentWeekDay;
}
}
}

layout/simpl_calandar_view.xml



























Calander_day_gridcell.xml









drawable/calendar_button_selected.xml






drawable/calendar_left_arrowsselected.xml






drawable/calendar_right_arrowseleceted.xml






values/style_calandar_events.xml






Friday, March 22, 2013

Insert ImageView dynamically using Java code

Here demonstrate how to create and add ImageView in LinearLayout (inside HorizontalScrollView/ScrollView) dynamically using Java code.
package com.example.androidinsertimages;

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

public class MainActivity extends Activity {

Button addinHorizontalScrollView, addinScrollView;
LinearLayout inHorizontalScrollView, inScrollView;

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

inHorizontalScrollView = (LinearLayout)findViewById(R.id.inhorizontalscrollview);
inScrollView = (LinearLayout)findViewById(R.id.inscrollview);

addinHorizontalScrollView = (Button)findViewById(R.id.addinhorizontalscrollview);
addinHorizontalScrollView.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
addImageView(inHorizontalScrollView);
}});

addinScrollView = (Button)findViewById(R.id.addinscrollview);
addinScrollView.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
addImageView(inScrollView);
}});

}

private void addImageView(LinearLayout layout){
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_launcher);
layout.addView(imageView);
}

}

xml code:









Insert ImageView dynamically using Java code

Save and Restore Instance State

The methods onSaveInstanceState(Bundle outState) and onRestoreInstanceState(Bundle savedInstanceState) are the good place to Save and Restore Instance State.

  • onSaveInstanceState (Bundle outState)

    Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

    This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).

    Do not confuse this method with activity lifecycle callbacks such as onPause(), which is always called when an activity is being placed in the background or on its way to destruction, or onStop() which is called before destruction. One example of when onPause() and onStop() is called and not this method is when a user navigates back from activity B to activity A: there is no need to call onSaveInstanceState(Bundle) on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause() is called and not onSaveInstanceState(Bundle) is when activity B is launched in front of activity A: the system may avoid calling onSaveInstanceState(Bundle) on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.

    The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

    If called, this method will occur before onStop(). There are no guarantees about whether it will occur before or after onPause().

  • onRestoreInstanceState (Bundle savedInstanceState)

    This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

    This method is called between onStart() and onPostCreate(Bundle).

java code:

package com.example.androidsavestate;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

TextView textviewSavedState;
EditText edittextEditState;

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

textviewSavedState = (TextView)findViewById(R.id.savedstate);
edittextEditState = (EditText)findViewById(R.id.editstate);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);

String stateSaved = savedInstanceState.getString("saved_state");

if(stateSaved == null){
Toast.makeText(MainActivity.this,
"onRestoreInstanceState:\n" +
"NO state saved!",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,
"onRestoreInstanceState:\n" +
"saved state = " + stateSaved,
Toast.LENGTH_LONG).show();
textviewSavedState.setText(stateSaved);
edittextEditState.setText(stateSaved);
}

}

@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);

String stateToSave = edittextEditState.getText().toString();
outState.putString("saved_state", stateToSave);

Toast.makeText(MainActivity.this,
"onSaveInstanceState:\n" +
"saved_state = " + stateToSave,
Toast.LENGTH_LONG).show();
}

}



Save and Restore Instance State

 

Thursday, March 21, 2013

Image Upload on Server

Now in this example I will show you how to send an image file.

Java Code:

package com.example.imageuploadonserver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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 android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;

public class UploadImage extends Activity {
InputStream inputStream;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_image_upload);

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList nameValuePairs = new ArrayList();

nameValuePairs.add(new BasicNameValuePair("image",image_str));

try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.23/Upload_image_ANDROID/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error in http connection "+e.toString());
}
}

public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length�..
Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer�..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream�..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string�..

Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}

Base64 Code:


Now download a file from here which encodeBytes in Base64 Format. Put this file in the same package of UploadImage.java. See the screenshot.

Now the server part.
Create a folder named Upload_image_ANDROID in your htdocs folder and inside that create a file named upload_image.php and copy this code into it.



$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory��';
?>

Saturday, March 16, 2013

streaming video mediaplayer

My player have individual style. What features does the player have:
  • Nice MediaController. I don�t use MediaController from Android API.
  • New SeekBar style
  • Animation for MedeaController. If user don�t touch screen for the 5 seconds then MediaController slow disapears.

java code: Main Activity

package com.sunil.video;

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

public class MainActivity extends Activity implements OnClickListener {

private static String TAG = "androidEx2";

private Button buttonVideoSample;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.main);

buttonVideoSample = (Button) findViewById(R.id.buttonVideoSample);
buttonVideoSample.setOnClickListener(this);
}

public void onClick(View v) {
if (v.getId() == R.id.buttonVideoSample) {
// **********************************
// HERE SET YOUR VIDEO URI
//String video_uri = "VIDEO_URI";
// For example: http://www.pocketjourney.com/downloads/pj/video/famous.3gp
// **********************************
String video_uri = "http://www.pocketjourney.com/downloads/pj/video/famous.3gp";
Intent intent = new Intent(this, VideoSample.class);
intent.putExtra("video_path", video_uri);
startActivity(intent);
}
}

}

Java Code: VideoSapmle

package com.sunil.video;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.SurfaceHolder.Callback;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;


public class VideoSample extends Activity implements OnSeekBarChangeListener, Callback, OnPreparedListener, OnCompletionListener, OnBufferingUpdateListener,
OnClickListener, OnSeekCompleteListener, AnimationListener {
private TextView textViewPlayed;
private TextView textViewLength;
private SeekBar seekBarProgress;
private SurfaceView surfaceViewFrame;
private ImageView imageViewPauseIndicator;
private MediaPlayer player;
private SurfaceHolder holder;
private ProgressBar progressBarWait;
private Timer updateTimer;
private Bundle extras;
private Animation hideMediaController;
private LinearLayout linearLayoutMediaController;
private static final String TAG = "androidEx2 = VideoSample";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videosample);
extras = getIntent().getExtras();

linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
linearLayoutMediaController.setVisibility(View.GONE);

hideMediaController = AnimationUtils.loadAnimation(this, R.anim.disapearing);
hideMediaController.setAnimationListener(this);

imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
imageViewPauseIndicator.setVisibility(View.GONE);
if (player != null) {
if (!player.isPlaying()) {
imageViewPauseIndicator.setVisibility(View.VISIBLE);
}
}

textViewPlayed = (TextView) findViewById(R.id.textViewPlayed);
textViewLength = (TextView) findViewById(R.id.textViewLength);

surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
surfaceViewFrame.setOnClickListener(this);
surfaceViewFrame.setClickable(false);

seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);
seekBarProgress.setOnSeekBarChangeListener(this);
seekBarProgress.setProgress(0);

progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);

holder = surfaceViewFrame.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnBufferingUpdateListener(this);
player.setOnSeekCompleteListener(this);
player.setScreenOnWhilePlaying(true);
player.setDisplay(holder);
}

private void playVideo() {
if (extras.getString("video_path").equals("VIDEO_URI")) {
showToast("Please, set the video URI in HelloAndroidActivity.java in onClick(View v) method");
} else {
new Thread(new Runnable() {
public void run() {
try {
player.setDataSource(extras.getString("video_path"));
player.prepare();
} catch (IllegalArgumentException e) {
showToast("Error while playing video");
Log.i(TAG, "========== IllegalArgumentException ===========");
e.printStackTrace();
} catch (IllegalStateException e) {
showToast("Error while playing video");
Log.i(TAG, "========== IllegalStateException ===========");
e.printStackTrace();
} catch (IOException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, "========== IOException ===========");
e.printStackTrace();
}
}
}).start();
}
}

private void showToast(final String string) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(VideoSample.this, string, Toast.LENGTH_LONG).show();
finish();
}
});
}

private void hideMediaController() {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
linearLayoutMediaController.startAnimation(hideMediaController);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.i(TAG, "========== onProgressChanged : " + progress + " from user: " + fromUser);
if (!fromUser) {
textViewPlayed.setText(Utils.durationInSecondsToString(progress));
}
}

public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

public void onStopTrackingTouch(SeekBar seekBar) {
if (player.isPlaying()) {
progressBarWait.setVisibility(View.VISIBLE);
player.seekTo(seekBar.getProgress() * 1000);
Log.i(TAG, "========== SeekTo : " + seekBar.getProgress());
}
}

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub

}

public void surfaceCreated(SurfaceHolder holder) {
playVideo();
}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub

}

public void onPrepared(MediaPlayer mp) {
Log.i(TAG, "========== onPrepared ===========");
int duration = mp.getDuration() / 1000; // duration in seconds
seekBarProgress.setMax(duration);
textViewLength.setText(Utils.durationInSecondsToString(duration));
progressBarWait.setVisibility(View.GONE);

// Get the dimensions of the video
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: " + videoHeight + " PROP: " + videoProportion);

// Get the width of the screen
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: " + screenHeight + " PROP: " + screenProportion);

// Get the SurfaceView layout parameters
android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams();

if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
}

// Commit the layout parameters
surfaceViewFrame.setLayoutParams(lp);

// Start video
if (!player.isPlaying()) {
player.start();
updateMediaProgress();
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
surfaceViewFrame.setClickable(true);
}

public void onCompletion(MediaPlayer mp) {
mp.stop();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}

/**
* Change progress of mediaController
* */
private void updateMediaProgress() {
updateTimer = new Timer("progress Updater");
updateTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
seekBarProgress.setProgress(player.getCurrentPosition() / 1000);
}
});
}
}, 0, 1000);
}

public void onBufferingUpdate(MediaPlayer mp, int percent) {
int progress = (int) ((float) mp.getDuration() * ((float) percent / (float) 100));
seekBarProgress.setSecondaryProgress(progress / 1000);
}

public void onClick(View v) {
if (v.getId() == R.id.surfaceViewFrame) {
if (linearLayoutMediaController.getVisibility() == View.GONE) {
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
} else if (player != null) {
if (player.isPlaying()) {
player.pause();
imageViewPauseIndicator.setVisibility(View.VISIBLE);
} else {
player.start();
imageViewPauseIndicator.setVisibility(View.GONE);
}
}
}
}

public void onSeekComplete(MediaPlayer mp) {
progressBarWait.setVisibility(View.GONE);
}

public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub

}

public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub

}

public void onAnimationStart(Animation animation) {
linearLayoutMediaController.setVisibility(View.GONE);
}
}
Main Layout:




VedioSaple Layout:
















anim/disapearing.xml




drawable/seekbarcolors.xml






















values/colors.xml


#FFFFFF
#5f5f5f
#141414
#a53130
#875e5e

dependency xml file inside your project folder( pom.xml)


4.0.0
com.hrupin.edu
androidEx2
0.0.1-SNAPSHOT
apk
androidEx2



com.google.android
android
2.2.1
provided




com.google.android.maps
maps
8_r2
provided




com.google.code.gson
gson
1.6
compile




junit
junit
4.0
test






com.jayway.maven.plugins.android.generation2
maven-android-plugin
2.8.3

${project.basedir}/AndroidManifest.xml
${project.basedir}/assets
${project.basedir}/res
${project.basedir}/src/main/native

8

true
true

true



maven-compiler-plugin
2.3.2

1.5
1.5






menifest.xml file

















Here you can see the screenshot:
Android Sample Video Streaming player's screenshot

You can download the source code VideoStreamingAndroid  Enjoy Guys!!

Saturday, March 9, 2013

Resize bitmap: Bitmap.createScaledBitmap vs BitmapFactory.Options.inSampleSize

In this article, two approach are provided to resize bitmap:
- Bitmap.createScaledBitmap
- BitmapFactory.Options.inSampleSize

But...which one is better? In the code, the process time are also provided for reference.

java code:

package com.resize.image;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

Button btnProcessA, btnProcessB;
ImageView processedImgA, processedImgB;
TextView statusA, statusB;
String fullUrl=null;

/*
* Normally do not hardcode "/sdcard/";
* use Environment.getExternalStorageDirectory().getPath() instead
*/
static String imgSouce = "/sunil.png";

static int w = 250;
static int h = 250;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btnProcessA = (Button)findViewById(R.id.processbtna);
btnProcessB = (Button)findViewById(R.id.processbtnb);
processedImgA = (ImageView)findViewById(R.id.processedimg_a);
processedImgB = (ImageView)findViewById(R.id.processedimg_b);
statusA = (TextView)findViewById(R.id.statusa);
statusB = (TextView)findViewById(R.id.statusb);

btnProcessA.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
resizeA();

}});

btnProcessB.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
resizeB();

}});

}

private void resizeA(){

Long startTime = System.currentTimeMillis();
fullUrl = Environment.getExternalStorageDirectory().getAbsolutePath().toString()
+ "/"
+ imgSouce;
Bitmap bitmap_Source = BitmapFactory.decodeFile(fullUrl);
float factorH = h / (float)bitmap_Source.getHeight();
float factorW = w / (float)bitmap_Source.getWidth();
float factorToUse = (factorH > factorW) ? factorW : factorH;
Bitmap bm = Bitmap.createScaledBitmap(bitmap_Source,
(int) (bitmap_Source.getWidth() * factorToUse),
(int) (bitmap_Source.getHeight() * factorToUse),
false);

Long endTime = System.currentTimeMillis();
Long processTime = endTime - startTime;
statusA.setText("Process Time (MilliSeconds): " + String.valueOf(processTime));

processedImgA.setImageBitmap(bm);

}

private void resizeB(){

Long startTime = System.currentTimeMillis();

BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bm = BitmapFactory.decodeFile(fullUrl , bmpFactoryOptions);

int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)h);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)w);

if (heightRatio > 1 || widthRatio > 1)
{
if (heightRatio > widthRatio){
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}

bmpFactoryOptions.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(fullUrl, bmpFactoryOptions);

Long endTime = System.currentTimeMillis();
Long processTime = endTime - startTime;
statusB.setText("Process Time (MilliSeconds): " + String.valueOf(processTime));

processedImgB.setImageBitmap(bm);
}

}

xml code:







The Result is:
Cheers Guys!!
 

Display image in WebView

If you are so lazy as me! Display image in WebView is a good choice.

Java Code:

package com.image.webview;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.webkit.WebView;

public class MainActivity extends Activity {

WebView webView;
String imagePath = "/sunil.png";

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

webView = new WebView(this);
setContentView(webView);

String fullUrl = "file://"
+ Environment.getExternalStorageDirectory().getAbsolutePath().toString()
+ "/"
+ imagePath;
webView.loadUrl(fullUrl);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);

}

}

Need To add INTERNET permission.


 Cheers Guys!!

Sunday, March 3, 2013

Custom MapView

It's a simple example of using MapView, with everything implement in main activity.

In this article, I'm going to implement a custom MyMapView extends MapView. Most of the routine works will be moved in MyMapView, include MyItemizedOverlay, MyLocationOverlay and some initialization such as setClickable(true), setBuiltInZoomControls(true)...etc. Such that the main activity will become simple and clear.
 
package com.AndroidCustomMapView;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;

public class MyMapView extends MapView {

MyItemizedOverlay myItemizedOverlay = null;
MyLocationOverlay myLocationOverlay = null;

public MyMapView(Context context, String apiKey) {
super(context, apiKey);
init(context);
}

public MyMapView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}

public MyMapView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}

private void init(Context ctx){
setClickable(true);
setBuiltInZoomControls(true);

Drawable marker=getResources().getDrawable(android.R.drawable.star_big_on);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);

myItemizedOverlay = new MyItemizedOverlay(marker);
getOverlays().add(myItemizedOverlay);

myLocationOverlay = new MyLocationOverlay(ctx, this);
getOverlays().add(myLocationOverlay);

}

public void addMarker(GeoPoint p, String title, String snippet){
myItemizedOverlay.addItem(p, title, snippet);
}

public void callOnResume(){
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
}

public void callOnPause(){
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
}

public class MyItemizedOverlay extends ItemizedOverlay {

private ArrayList overlayItemList = new ArrayList();

public MyItemizedOverlay(Drawable defaultMarker) {
//super(defaultMarker);
super(boundCenterBottom(defaultMarker));
populate();
}

@Override
protected OverlayItem createItem(int i) {
return overlayItemList.get(i);
}

@Override
public int size() {
return overlayItemList.size();
}

public void addItem(GeoPoint p, String title, String snippet){
OverlayItem newItem = new OverlayItem(p, title, snippet);
overlayItemList.add(newItem);
populate();
}

}

}

Modify main.xml to add <com.AndroidCustomMapView.MyMapView> in the layout.
 







Modify the activity, AndroidCustomMapViewActivity to use our MyMapView. It become much clear now.
 
package com.AndroidCustomMapView;

import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;

public class AndroidCustomMapViewActivity extends MapActivity {

MyMapView myMapView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMapView = (MyMapView)findViewById(R.id.mymapview);

GeoPoint myPoint1 = new GeoPoint(0*1000000, 0*1000000);
myMapView.addMarker(myPoint1, "myPoint1", "myPoint1");
GeoPoint myPoint2 = new GeoPoint(50*1000000, 50*1000000);
myMapView.addMarker(myPoint2, "myPoint2", "myPoint2");
}

@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
myMapView.callOnPause();
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
myMapView.callOnResume();
}

}
Remember to modify AndroidManifest.xml to include uses-library of "com.google.android.maps", and grant permission of "android.permission.INTERNET" and "android.permission.ACCESS_FINE_LOCATION".























Custom MapView

 

Copyright @ 2013 Android Developers Tipss.