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