Wednesday 31 December 2014

Creating an AppWidget In Android

 A widget is a small gadget or control of your android application placed on the home screen. Widgets can be very handy as they allow you to put your favourite applications on your homescreen in order to quickly access them. You have probably seen some common widgets , such as music widget , weather widget , clock widget e.t.c
Widgets could be of many types such as information widgets, collection widgets, control widgets and hybrid widgets. Android provides us a complete framework to develop our own widgets.

Get Source Code from Here

Tuesday 30 December 2014

Programmatically check google play services exist or not in android device

In this post, we will implement a very basic (but robust) Android application that authenticates a user with Google services.

 1.  Add Google PlayServices library

2. Activity.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:id="@+id/googleplayServies"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

3. String.Xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">GooglePlayServiceUpdate</string>
    <string name="googleplayServiesText">Google Play Services Updated</string>
</resources>

4. AndroidManifest.Xml:

<meta-data android:name="com.google.android.gms.version" 
  android:value="@integer/google_play_services_version" />

5. MainActivity.Java:
package com.example.checkgoogleplayserviceupdate;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {
private TextView googleplayServies;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleplayServies = (TextView) findViewById(R.id.googleplayServies);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this);
if (status != ConnectionResult.SUCCESS) {
updateGoogleplay();
}
 else
googleplayServies.setText(R.string.googleplayServiesText);
}

public void updateGoogleplay() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
// set title
alertDialogBuilder.setTitle("Update Google Play Services");
// set dialog message
alertDialogBuilder
.setMessage("This Application Want To Update You Google Play Services App")
.setCancelable(false)
.setPositiveButton("Update",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
callMarketPlace();
finish();
 }
});
alertDialogBuilder.show();
}
public void callMarketPlace() {
try {
startActivityForResult(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="+ "com.google.android.gms")), 1);
}
 catch (android.content.ActivityNotFoundException anfe) {
startActivityForResult(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id="+ "com.google.android.gms")), 1);
}
}
}

Friday 26 December 2014

Enable, disable and make discovrable bluetooth programmatically

You need to write few lines of code only, to enable or disable the bluetooth.
activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView android:text="" 
        android:id="@+id/out" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"></TextView>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="49dp"
        android:text="TURN_ON" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="27dp"
        android:text="DISCOVERABLE" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="28dp"
        android:text="TURN_OFF" />


</RelativeLayout>

Provide Permission:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

MainActivity.java

public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVERABLE_BT = 0;
 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView out=(TextView)findViewById(R.id.out);
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
 out.append("device not supported");
}
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
    });
button2.setOnClickListener(new View.OnClickListener() {
@Override
 public void onClick(View arg0) {
if (!mBluetoothAdapter.isDiscovering()) {
//  out.append("MAKING YOUR DEVICE DISCOVERABLE");
Context context = getApplicationContext();
CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
int duration = Toast.LENGTH_SHORT;
 Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
 startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
                  
            }
        }
    });
 button3.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View arg0) {   
mBluetoothAdapter.disable();
//  out.append("TURN_OFF BLUETOOTH");
Context context = getApplicationContext();
CharSequence text = "TURNING_OFF BLUETOOTH";
 int duration = Toast.LENGTH_LONG;
 Toast toast = Toast.makeText(context, text, 15);
 toast.show();
            }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
    }

}

Android Bluetooth List Paired Devices Example

Bluetooth is a way to exchange data with other devices wirelessly. Android provides Bluetooth API to perform several tasks such as:
  • scan bluetooth devices
  • connect and transfer data from and to other devices
  • manage multiple connections etc.
Android Bluetooth Api:
The android.bluetooth package provides a lot of interfaces classes to work with bluetooth such as:
  • BluetoothAdapter
  • BluetoothDevice
  • BluetoothSocket
  • BluetoothServerSocket
  • BluetoothClass
  • BluetoothProfile
  • BluetoothProfile.ServiceListener
  • BluetoothHeadset
  • BluetoothA2dp
  • BluetoothHealth
  • BluetoothHealthCallback
  • BluetoothHealthAppConfiguration
List Paired Devices Example:

MainActivity.java:


public class MainActivity extends Activity {
 TextView textview1;
 private static final int REQUEST_ENABLE_BT = 1;
 BluetoothAdapter btAdapter; 
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   textview1 = (TextView) findViewById(R.id.textView1);
   btAdapter = BluetoothAdapter.getDefaultAdapter();
   CheckBluetoothState();
 }
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == REQUEST_ENABLE_BT) {
     CheckBluetoothState();
   }
 }
 
 @Override
 protected void onDestroy() {
   super.onDestroy();
 }
 
 private void CheckBluetoothState() {
   // Checks for the Bluetooth support and then makes sure it is turned on
   // If it isn't turned on, request to turn it on
   // List paired devices
   if(btAdapter==null) { 
     textview1.append("\nBluetooth NOT supported. Aborting.");
     return;
   } else {
     if (btAdapter.isEnabled()) {
       textview1.append("\nBluetooth is enabled...");
        
       // Listing paired devices
       textview1.append("\nPaired Devices are:");
       Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
       for (BluetoothDevice device : devices) {
         textview1.append("\n  Device: " + device.getName() + ", " + device);
       }
     } else {
       //Prompt user to turn on Bluetooth
       Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
       startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
     }
   }
 }
    

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

activity_main. xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="61dp"
        android:text="Showing Paired Devices:" />

</RelativeLayout>

Add Permission In Manifest File:


 <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Saturday 16 August 2014

Android Multiscreen support Layout folders

Being an Android developer one should know the different layout folders.
Layouts play an important role in UI concept of Android. 

Here are the few layouts folders which are used to support different screen sizes like

  1. Small Screen phones
  2. Medium Screen phones
  3. Large Screen Phones
  4. 7" Tablets
  5. 10 " Tablets


·         res/layout/ 

for Phones 



·         res/layout-port

for Phones only portrait screen



·         res/layout-land

for Phones only Landscape screen



·         res/layout-sw600dp/

for 7" Tablets



·         res/layout-sw600dp-port/

for 7" Tablets only portrait



·         res/layout-sw600dp-land/

for 7" Tablets only landscape



·         res/layout-sw720dp/

for 10" Tablets



·         res/layout-sw720dp-port/

for 10" Tablets only portrait



·         res/layout-sw720dp-land/

for 10" Tablets only landscape



·         res/layout-xlarge/

for pre 3.2" Tablets 




·         res/layout-xlarge-port/

for pre 3.2" Tablets to support portrait only




·         res/layout-xlarge-land/

for pre 3.2" Tablets to support landscapre only




·         res/layout-small/

for small screens 




·         res/layout-small-port/

for small screens to support portrait screens only 




·         res/layout-small-land/

for small screens to support landscape screens only 




·         res/layout-large/

for large screens 



·         res/layout-large-port/

for large screens to support portrait screens only 



·         res/layout-large-land/
for large screens to support landscape screens only 


How to support multiple screen in Android   

Multi Screen Pdf

Friday 7 February 2014

Android Preferences

Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs: private/public, small/large datasets.

Your data storage options are the following:

Shared Preferences: Store private primitive data in key-value pairs.
Internal Storage: Store private data on the device memory.
External Storage: Store public data on the shared external storage.
SQLite Databases: Store structured data in a private database.
Network Connection: Store data on the web with your own network server.
Content Provider: Shared repository globally shared by all apps.

Preferences is an Android lightweight mechanism to store and retrieve <key-value> pairs of primitive data types (also called Maps, and Associative Arrays.  PREFERENCES are typically used to keep state information and shared data among several activities of an application.  In each entry of the form <key-value> the key is a stringand the value must be a primitive data type. Preferences are similar to Bundles however they are persistent while Bundles are not.

Using Preferences API calls:

 You have three API choices to pick a Preference:

1.getPreferences() from within your Activity, to access activity specific preferences

2.getSharedPreferences() from within your Activity to access application-level preferences

3.getDefaultSharedPreferences(), on PreferencesManager, to get the shared preferences that work in concert with Android's overall preference framework

Download Sample code:   Here


Wednesday 8 January 2014

Android 2D Graphics Example

Android comes along with powerful open-source API libraries which support custom 2D and 3D graphics as well animations. In this tutorial let’s concentrate only on 2D graphics.
               Android framework API provides 2D drawing APIs for simple animation that does not require major dynamic changes. There are two ways of implementation using these API.
  •    Drawing to a View
  •  Drawing on a Canvas
    

Code: 

DragDrop.java:


package com.android.Graphics ;

import android.app.Activity;

import android.content.Intent;

import android.graphics.Color;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.Window;

import android.view.WindowManager;

import android.widget.Toast;

public class DragDrop extends Activity {

DrawView drawView;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Set full screen view

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN);

requestWindowFeature(Window.FEATURE_NO_TITLE);

Toast.makeText(getApplicationContext(), "Draw Text on screen", Toast.LENGTH_LONG).show();

getWindow().getDecorView().setBackgroundColor(Color.WHITE);

drawView = new DrawView(this);

setContentView(drawView);

drawView.requestFocus();

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

public boolean onOptionsItemSelected(MenuItem item)

{

switch (item.getItemId())

{

case R.id.Refresh:

Intent intent = getIntent();

intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

finish();

startActivity(intent);

return true;

default:

return super.onOptionsItemSelected(item);

}

}

}

DrawView.Java:

package com.android.Graphics ;

import java.util.ArrayList;

import java.util.List;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.util.Log;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnTouchListener;

public class DrawView extends View implements OnTouchListener {

private static final String TAG = "DrawView";

List<Point> points = new ArrayList<Point>();

Paint paint = new Paint();

public DrawView(Context context) {

super(context);

setFocusable(true);

      setFocusableInTouchMode(true);

this.setOnTouchListener(this);

paint.setColor(Color.RED);

paint.setAntiAlias(true);

}

@Override

public void onDraw(Canvas canvas) {

for (Point point : points) {

canvas.drawCircle(point.x, point.y, 5, paint);

// Log.d(TAG, "Painting: "+point);

}

}

public boolean onTouch(View view, MotionEvent event) {

// if(event.getAction() != MotionEvent.ACTION_DOWN)

// return super.onTouchEvent(event);

Point point = new Point();

point.x = event.getX();

point.y = event.getY();

points.add(point);

invalidate();

Log.d(TAG, "point: " + point);

return true;

class Point
{

float x, y;

@Override

public String toString()

{
return x + ", " + y;

}

}


Menu.Xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item

android:id="@+id/Refresh"

android:orderInCategory="100"

android:showAsAction="never"

android:title="Refresh"/>

</menu>