Thursday, 6 September 2012

Gestures Detector

Gestures are patterns drawn by the user on the screen. Simple gestures include tap, scroll, swipe, etc. Complex gestures are more complex patterns drawn on the screen. In Android we can detect simple gestures using GestureDetector class.
Here i am going to create a simple Gestures Detector having scroll and flip on the basis of the Double-tap. 

Create an activity -> FlipperActivity.java 


package com.samples.gesturedetectorsample;

import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class FlipperActivity extends Activity 
implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener{
final private int SWIPE_MIN_DISTANCE = 100;
final private int SWIPE_MIN_VELOCITY = 100;
private ViewFlipper flipper = null;
private ArrayList<TextView> views = null;
private GestureDetector gesturedetector = null;
private Vibrator vibrator = null;
int colors[] = { Color.rgb(255,128,128), Color.rgb(128,255,128), 
Color.rgb(128,128,255), Color.rgb(128,128,128) };
private Animation animleftin = null;
private Animation animleftout = null;
private Animation animrightin = null;
private Animation animrightout = null;
private Animation animupin = null;
private Animation animupout = null;
private Animation animdownin = null;
private Animation animdownout = null;
private boolean isDragMode = false;
private int currentview = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        flipper = new ViewFlipper(this);
        gesturedetector = new GestureDetector(this, this);
        vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
        gesturedetector.setOnDoubleTapListener(this);
        flipper.setInAnimation(animleftin);
        flipper.setOutAnimation(animleftout);
        flipper.setFlipInterval(3000);
        flipper.setAnimateFirstView(true);
        prepareAnimations();
        prepareViews();
        addViews();
        setViewText();        
        setContentView(flipper);
    }
private void prepareAnimations() {
animleftin = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f);       
        animleftout = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f);        
        animrightin = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f);        
        animrightout = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f);       
        animupin = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
        Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,   0.0f);     
        animupout = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f);        
        animdownin = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
        Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,   0.0f);        
        animdownout = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
        Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f);        
        animleftin.setDuration(1000);
        animleftin.setInterpolator(new OvershootInterpolator());
        animleftout.setDuration(1000);
        animleftout.setInterpolator(new OvershootInterpolator());      
        animrightin.setDuration(1000);
        animrightin.setInterpolator(new OvershootInterpolator());
        animrightout.setDuration(1000);
        animrightout.setInterpolator(new OvershootInterpolator());       
        animupin.setDuration(1000);
        animupin.setInterpolator(new OvershootInterpolator());
        animupout.setDuration(1000);
        animupout.setInterpolator(new OvershootInterpolator());       
        animdownin.setDuration(1000);
        animdownin.setInterpolator(new OvershootInterpolator());
        animdownout.setDuration(1000);
        animdownout.setInterpolator(new OvershootInterpolator());
}
private void prepareViews(){
TextView view = null;

views = new ArrayList<TextView>();

for(int color: colors)
{
view = new TextView(this);
view.setBackgroundColor(color);
view.setTextColor(Color.BLACK);
view.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);

views.add(view);
}
}

private void addViews(){
for(int index=0; index<views.size(); ++index)
{
flipper.addView(views.get(index),index,
new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
}

private void setViewText(){
String text = getString(isDragMode ? R.string.app_info_drag : R.string.app_info_flip);
for(int index=0; index<views.size(); ++index)
{
views.get(index).setText(text);
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
return gesturedetector.onTouchEvent(event);
}

@Override
public boolean onDown(MotionEvent e) {
return false;
}

@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX,float velocityY) {
if(isDragMode)
return false;

final float ev1x = event1.getX();
final float ev1y = event1.getY();
final float ev2x = event2.getX();
final float ev2y = event2.getY();
final float xdiff = Math.abs(ev1x - ev2x);
final float ydiff = Math.abs(ev1y - ev2y);
final float xvelocity = Math.abs(velocityX);
final float yvelocity = Math.abs(velocityY);

if(xvelocity > this.SWIPE_MIN_VELOCITY && xdiff > this.SWIPE_MIN_DISTANCE)
{
if(ev1x > ev2x) //Swipe Left
{
--currentview;

if(currentview < 0)
{
currentview = views.size() - 1;
}

flipper.setInAnimation(animleftin);
flipper.setOutAnimation(animleftout);
}
else //Swipe Right
{
++currentview;

if(currentview >= views.size())
{
currentview = 0;
}

flipper.setInAnimation(animrightin);
flipper.setOutAnimation(animrightout);
}

flipper.scrollTo(0,0);
flipper.setDisplayedChild(currentview);
}
else if(yvelocity > this.SWIPE_MIN_VELOCITY && ydiff > this.SWIPE_MIN_DISTANCE)
{
if(ev1y > ev2y) //Swipe Up
{
--currentview;

if(currentview < 0)
{
currentview = views.size() - 1;
}

flipper.setInAnimation(animupin);
flipper.setOutAnimation(animupout);
}
else //Swipe Down
{
++currentview;

if(currentview >= views.size())
{
currentview = 0;
}
flipper.setInAnimation(animdownin);
flipper.setOutAnimation(animdownout);
}

flipper.scrollTo(0,0);
flipper.setDisplayedChild(currentview);
}

return false;
}

@Override
public void onLongPress(MotionEvent e) {
vibrator.vibrate(200);
flipper.scrollTo(0,0);

isDragMode = !isDragMode;

setViewText();
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,float distanceY) {
if(isDragMode)
flipper.scrollBy((int)distanceX, (int)distanceY);

return false;
}

@Override
public void onShowPress(MotionEvent e) {
}

@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}

@Override
public boolean onDoubleTap(MotionEvent e) {
flipper.scrollTo(0,0);

return false;
}

@Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}

@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
}

          The AndroidManifest.xml look like :




<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.samples.gesturedetectorsample"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FlipperActivity"
                  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>
<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
</manifest> 




Note: Modify the above code as you requirements.

Android Battery Level.

The simple application helps to find the followings of the battery from your Android phone.
  • Battery Level
  • Technology
  • plugin 
  • Health
  • Status


img.i

Design The .xml page like the following 

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:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_margin="10dip"
    android:id="@+id/batterylevel_text"
    android:textStyle="bold"
    android:text="batterylevel_info"/>
</LinearLayout>

The source -> MainActivity.java


package com.samples.batteryinfo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView textBatteryLevel = null;
String batteryLevelInfo = "Battery Level";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        textBatteryLevel = (TextView)findViewById(R.id.batterylevel_text);
        
        registerBatteryLevelReceiver();
    }

@Override
protected void onDestroy()
{
unregisterReceiver(battery_receiver);

super.onDestroy();
}

private BroadcastReceiver battery_receiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
boolean isPresent = intent.getBooleanExtra("present", false);
String technology = intent.getStringExtra("technology");
int plugged = intent.getIntExtra("plugged", -1);
int scale = intent.getIntExtra("scale", -1);
int health = intent.getIntExtra("health", 0);
int status = intent.getIntExtra("status", 0);
int rawlevel = intent.getIntExtra("level", -1);
            int level = 0;
            
            Bundle bundle = intent.getExtras();
            
            Log.i("BatteryLevel", bundle.toString());
            
            if(isPresent)
            {
           if (rawlevel >= 0 && scale > 0) {
               level = (rawlevel * 100) / scale;
           }
           
           String info = "Battery Level: " + level + "%\n";
           
           info += ("Technology: " + technology + "\n");
           info += ("Plugged: " + getPlugTypeString(plugged) + "\n");
           info += ("Health: " + getHealthString(health) + "\n");
           info += ("Status: " + getStatusString(status) + "\n");
           
           //setBatteryLevelText(info + "\n\n" + bundle.toString());
           setBatteryLevelText(info + "\n\n");

            }
            else
            {
            setBatteryLevelText("Battery not present!!!");
            }
}
};
private String getPlugTypeString(int plugged){
String plugType = "Unknown";
switch(plugged)
{
case BatteryManager.BATTERY_PLUGGED_AC: plugType = "AC"; break;
case BatteryManager.BATTERY_PLUGGED_USB: plugType = "USB"; break;
}
return plugType;
}
private String getHealthString(int health)
{
String healthString = "Unknown";
switch(health)
{
case BatteryManager.BATTERY_HEALTH_DEAD: healthString = "Dead"; break;
case BatteryManager.BATTERY_HEALTH_GOOD: healthString = "Good"; break;
case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE: healthString = "Over Voltage"; break;
case BatteryManager.BATTERY_HEALTH_OVERHEAT: healthString = "Over Heat"; break;
case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE: healthString = "Failure"; break;
}
return healthString;
}
private String getStatusString(int status)
{
String statusString = "Unknown";
switch(status)
{
case BatteryManager.BATTERY_STATUS_CHARGING: statusString = "Charging"; break;
case BatteryManager.BATTERY_STATUS_DISCHARGING: statusString = "Discharging"; break;
case BatteryManager.BATTERY_STATUS_FULL: statusString = "Full"; break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING: statusString = "Not Charging"; break;
}
return statusString;
}
private void setBatteryLevelText(String text){
textBatteryLevel.setText(text);
}
private void registerBatteryLevelReceiver(){
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(battery_receiver, filter);
}
}

The AndroidManifest.xml look like :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.samples.batteryinfo"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <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>
    <uses-sdk android:minSdkVersion="3" />

</manifest> 



Note: Modify the above code as you requirements.


Friday, 31 August 2012

Simple Android Application Launcher

A Launcher presents the main view of the phone and is responsible for starting other apps and hosting live widgets

Here the resource (res) consist of  "drawable", "layout", "menu", "values" Folders.

Use the following codes in "layout"

app.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="wrap_content">
<ImageView
android:id="@+id/app_icon"
android:layout_width="48px"
android:layout_height="48px"
android:padding="3px"
android:scaleType="fitXY"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/app_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"/>
</LinearLayout>
</LinearLayout>

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">

<ListView 
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content"
   android:id="@android:id/list"/>
   
</LinearLayout>

Use the following to the "menu" folder

menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_about" 
    android:titleCondensed="@string/menu_about" 
    android:title="@string/menu_about_desc" 
    android:icon="@android:drawable/ic_menu_help"></item>
</menu>

Use the following codes in "values"

string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    
    <string name="app_name">App Launcher</string>
<string name="app_desc">Simple application to show how to enumerate and launch external application</string>
<string name="menu_about">About</string>
<string name="menu_about_desc">About App Launcher</string>
</resources>


img.1



The Source (src) consist of two classes 

AppLauncher.java and MainAvtivity.java
follow this cods in the class AppLauncher.java :
package com.samples.applauncher;
import android.app.Application;
import android.content.res.Configuration;

public class AppLauncher extends Application 
{
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}

@Override
public void onCreate() {
super.onCreate();
}

@Override
public void onLowMemory() {
super.onLowMemory();
}

@Override
public void onTerminate() {
super.onTerminate();
}
}

follow this cods in the class MainAvtivity.java :

package com.samples.applauncher;

import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainAvtivity extends ListActivity {
PackageManager packageManager = null;
List<ApplicationInfo> applist = null;
ApplicationAdaptor listadaptor = null;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        packageManager = getPackageManager();
        
        new LoadApplicationTask().execute();
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.menu, menu);
   
return true;
}
    
    public boolean onOptionsItemSelected(MenuItem item) {
    boolean result = true;
   
switch(item.getItemId())
{
case R.id.menu_about:
{
displayAboutDialog();
break;
}
default:
{
result = super.onOptionsItemSelected(item);
break;
}
}
return result;

    }
    
    
    private void displayAboutDialog()
{
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle(getString(R.string.app_name));
    builder.setMessage(getString(R.string.app_desc));
   
    builder.show();
}
        
    @Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try 
{
Intent intent = packageManager.getLaunchIntentForPackage(app.packageName);
if(null != intent)
{
startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(MainAvtivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
catch (Exception e) 
{
Toast.makeText(MainAvtivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}

    private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list)
    {
    ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>(); 
   
    for(ApplicationInfo info: list)
    {
    try {
    if(null != packageManager.getLaunchIntentForPackage(info.packageName))
    {
    applist.add(info);
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
   
return applist;
    }
    
    private class LoadApplicationTask extends AsyncTask<Void, Void, Void>
    {
    private ProgressDialog progress = null;
   
@Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(
        packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
       listadaptor = new ApplicationAdaptor(MainAvtivity.this, R.layout.app, applist);
       
return null;
}

@Override
protected void onCancelled() {
super.onCancelled();
}

@Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
progress = ProgressDialog.show(
MainAvtivity.this, null, "Loading application info...");
super.onPreExecute();
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
    }
    
private class ApplicationAdaptor extends ArrayAdapter<ApplicationInfo>
    {
    private List<ApplicationInfo> objects = null;

public ApplicationAdaptor(Context context, 
int textViewResourceId,
List<ApplicationInfo> objects) 
{
super(context, textViewResourceId, objects);
this.objects = objects;
}
   
@Override
public int getCount() {
return ((null != objects) ? objects.size() : 0);
}

@Override
public ApplicationInfo getItem(int position) {
return ((null != objects) ? objects.get(position) : null);
}

@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(null == view)
{
LayoutInflater vi = (LayoutInflater)MainAvtivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.app, null);
}
ApplicationInfo data = objects.get(position);
if(null != data)
{
TextView textName = (TextView)view.findViewById(R.id.app_name);
ImageView iconview = (ImageView)view.findViewById(R.id.app_icon);
textName.setText(data.loadLabel(packageManager) + " (" + data.packageName + ")");
iconview.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
    };
}


The AndroidManifest.xml look like :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      android:versionCode="1"
      android:versionName="1.0" package="com.samples.applauncher">
    <application android:icon="@drawable/icon" android:label="@string/app_name"
         android:name="AppLauncher" android:description="@string/app_desc">
        <activity android:name=".MainAvtivity"
                  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>
    <uses-sdk android:minSdkVersion="3" />

</manifest> 

Note: Modify the above code as you requirements.