Thursday 15 September 2016

Android black screen before splash appear | Black screen on app start | How to avoid black screen in android while app is loading?


Hello Friends,
          Have you facing the delay issue on app launch and black/white
screen will be appearingfor few seconds. Here is the solution of this
issue.

1. Inside styles.xml add below style:
     
     <style name="Theme.AppCompat.Light.NoActionBar.FullScreen"
    parent="@android:style/Theme.Black.NoTitleBar">
   <item name="windowNoTitle">true</item>
   <item name="windowActionBar">false</item>
   <item name="android:windowFullscreen">true</item>
   <item name="android:windowContentOverlay">@null</item>
   <item name="android:windowIsTranslucent">true</item>
</style>

2. Inside your AndroidManiest.xml file add above style to your  Splash Activity:
    <activity
    android:configchanges="orientation|
    keyboardHidden|screenSize"
    android:label="@string/app_name"
    android:name=".SplashScreenActivity"
    android:screenorientation="portrait"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">
       <intent-filter>
        <action android:name="android.intent.action.MAIN">
            <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
 </activity>


Hope, this will helps someone.
Enjoy Coding... Cheers.. :)



Wednesday 22 June 2016

App crashed on launch | Android Studio App crashed on launch | App crashed on launch- Android 4.4

Hello friends,

Today I found the strange issue while making an signed/released Apk.

My app getting crashed when app launched on Android 4.4, 4.2 and other devices
and Its working fine with Debug build. After spending lots of time I found that the
issue is with Android studio 2.0 or higher.

The reason of crash is in Android studio 2.0 and higher Google added a new feature
of Instant Run which makes your development/emulation faster.The Instant run is
enabled in latest android studio. We need to make it disable while making a signed
release build.

Steps to Disable:
1. Open the Settings or Preferences dialog: On Windows or Linux, select File > Settings
    from the main menu. On Mac OSX, select Android Studio > Preferences from
    the main menu.
2. Navigate to Build, Execution, Deployment > Instant Run.
3  Unchecked the box next to Enable Instant Run to hoot swap code/resource
    changes on display. 



What is Instant Run??
Instant Run: This feature is supposed to dramatically improve your workflow by letting you quickly see changes running on your device or emulator. It lets you see your changes running “in a near instant,” which means you can continuously code and run your app, hopefully accelerating your edit, build, run cycles. When you click on the Instant Run button, it will analyze the changes you have made and determine how it can deploy your new code in the fastest way. Instant Run works with any Android Device or emulator running API 14 (Ice Cream Sandwich) or higher.


Hope this will help someone.
Enjoy Coding.... :)

Saturday 20 February 2016

Unity | Unity Read SMS Plugin | Unity Pluging : Read all incoming sms


Hello Friends,
              I read a lot that people facing problem in register and un-register the incoming
sms broadcast from Unity. Also reading incoming sms in Unity app .

     

              So, today I am going to share my first blog on Unity. This post helps you
to read all android incoming sms in your unity app.  Also you can easily register
and un-register the broadcast base on need.

In this tutorial I am going provide you a Unity Plugin(i.e:smsreader.jar) which
communicate b/w your unity app and android native callbacks. Below are the
steps to use it in your unity app :


1. Note: The package name which you have to use to access the plugin method is
               com.affle.smsreader

    Permission:  Add below permission inside your unity app manifest.xml file.
         <uses-permission android:name="android.permission.RECEIVE_SMS"/>
         <uses-permission android:name="android.permission.READ_SMS" />



2.  The plugin contains to static method which will be call from unity app :
          A. registerBroadcastReceiver() :  When your unity app launch we first need to
              call this method for registering the broadcast receiver. Below is code snapshot.
              These two methods and class are there in plugin we just need to add that
               plugin as a jar and call it.
            
        /**
  * This method register the Broadcast receiver
  * @param view
  */
 public static void registerBroadcastReceiver() {
    if (broadCastReceiver == null) {
  broadCastReceiver = new IncomingSms();
    }
    UnityPlayer.currentActivity.registerReceiver(broadCastReceiver,
  new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
 }

          B. unregisterBroadcastReceiver() : Whenever you want to stop reading incoming
               sms call this method or when your unity app goes in background.
 /**
  * This method un-register the Broadcast receiver
  * @param view
  */
 public static void unregisterBroadcastReceiver() {

  if (broadCastReceiver != null) {
   UnityPlayer.currentActivity.unregisterReceiver(broadCastReceiver);
   broadCastReceiver = null;
  }
 }

3. IncomingSms.java:
package com.affle.smsreader;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

import com.unity3d.player.UnityPlayer;

public class IncomingSms extends BroadcastReceiver {

 final SmsManager sms = SmsManager.getDefault();

 public void onReceive(Context context, Intent intent) {

  // Retrieves a map of extended data from the intent.
  final Bundle bundle = intent.getExtras();

  try {

   if (bundle != null) {

    final Object[] pdusObj = (Object[]) bundle.get("pdus");

    for (int i = 0; i < pdusObj.length; i++) {

     SmsMessage currentMessage = SmsMessage
       .createFromPdu((byte[]) pdusObj[i]);
     String phoneNumber = currentMessage
       .getDisplayOriginatingAddress();

     String message = currentMessage.getDisplayMessageBody();

     if (UnityPlayer.currentActivity != null) {
      UnityPlayer.UnitySendMessage("TextMessageListner",
        "OnMessageReceived", "" + message);
     }
    } // end for loop
   } // bundle is null

  } catch (Exception e) {
   Log.e("SmsReceiver", "Exception smsReceiver" + e);

  }
 }

}


Download the plugin from here : SmsReader.jar
Hope this will help some one.
Enjoy....
Happy Coding ... :)

Wednesday 17 February 2016

Android 3 Easy Steps to generate SHA1 and MD5 fingerprint| SHA-1 fingerprint of keystore certificate | Using Android Studio generate SHA-1 fingerprint

Hello Friends,
      Today, I am sharing few easy steps to generate SHA1 and MD5 fingerprint using
android studio.No need of terminal command, we can generate it in Android Studio
same as we did in Eclipse-->window---> preferences--->Android---->Build .

Here Are Steps with screen shot:

Easiest way :
  1. Open Android Studio
  2. Open Your Project
  3. Click on Gradle (From Right Side Panel, you will see Gradle Option)
  4. Click on Refresh (Click on Refresh from Gradle, you will see List Gradle scripts of your Project)
  5. Click on Your Project (Your Project Name form List (root))
  6. Click on Tasks
  7. Click on android
  8. Double Click on signingReport (You will get SHA1 and MD5 in Run Bar)

Screen 1.

Screen 2.



Screen 3.



All Done.


Hope this will help some one.
Enjoy Coding.....
Cheers :)

Monday 18 January 2016

Android RecyclerView and CardView tutorial | Android RecyclerView and CardView widgets | Android RecyclerView and CardView with backward compatibility

Hello Friends,
         Today, I am going to share my another post on Android RecyclerView and CardView.
This widgets come in android  latest release i.e Lollipop, Android 5.0 and API Level 21.
We can also add support on lower devices above API Level 7 by adding support library.
For creating complex Listview we need RecyclerView  and CardView.



Android RecyclerView: The advance version of Listview is RecyclerView, It is more
                                        advance and flexible. RecyclerView uses Layout manager for
managing position of item inside the recycler view. Recycler view provides three
built in Layout manager :

1. LinearLayoutManager : shows items in a vertical or horizontal scrolling list.
2. GridLayoutManager: shows items in a grid.
3. StaggeredGridLayoutManager: shows items in a staggered grid.

For more check this Link


CardView Widget:  It help us in showing information inside cards that have a consistent
                                  look across the platform. CardView widgets can have shadows and
                                  rounded corners.
 Note:
       1. To create a card with a shadow, use the card_view:cardElevation attribute. 
       2. To set the corner radius in your layouts, use the card_view:cardCornerRadius
           attribute.
      3. To set the corner radius in your code, use the CardView.setRadius method.
      4. To set the background color of a card, use the card_view:cardBackgroundColor
            attribute.


Here is Sample Code:

1. MainActivity.java

package solutions.developer.android.com.recyclerview;

import android.app.Activity;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Mukesh on 12/20/2015.
 */

public class MainActivity extends Activity {

    /**
     * Cursor used to access the results from querying for images
     * on the SD card.
     */
    private Cursor cursor;
    /*
     * Column index for the Thumbnails Image IDs.
     */
    private int columnIndex;
    private static final String TAG = "RecyclerViewExample";

    private List mediaList = new ArrayList();

    private RecyclerView mRecyclerView;

    private MediaRVAdapter adapter;

    String type = "";

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

        /* Initialize recyclerview */
        mRecyclerView = (RecyclerView) findViewById(R.id.list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        type = "audio";
        new MediaAsyncTask().execute(type);

    }

    private void parseAllAudio(String type) {
        try {
          String TAG = "Audio";
          Cursor cur = getContentResolver().query(
                 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                  null);

          if (cur == null) {
              // Query failed...
              Log.e(TAG, "Failed to retrieve music: cursor is null :-(");
          } else if (!cur.moveToFirst()) {
             // Nothing to query. There is no music on the device. How boring.
              Log.e(TAG, "Failed to move cursor to first row (no query results).");
          } else {
              Log.i(TAG, "Listing...");
              // retrieve the indices of the columns where the ID,
              //title, etc. of the song are
              // add each song to mItems
             do {
                 int artistColumn = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                 int titleColumn = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
                 int albumColumn = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM);
                 int durationColumn = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
                 int idColumn = cur.getColumnIndex(MediaStore.Audio.Media._ID);
              int filePathIndex = cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                 Log.i(TAG, "Title column index: " + String.valueOf(titleColumn));
                 Log.i(TAG, "ID column index: " + String.valueOf(titleColumn));

                 Log.i("Final ", "ID: " + cur.getString(idColumn) + " Title: "
                 + cur.getString(titleColumn) + "Path: " +
                   cur.getString(filePathIndex));
                 MediaFileInfo audio = new MediaFileInfo();
                 audio.setFileName(cur.getString(titleColumn));
                 audio.setFilePath(cur.getString(filePathIndex));
                 audio.setFileType(type);
                 mediaList.add(audio);

              } while (cur.moveToNext());
          }

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

  public class MediaAsyncTask extends AsyncTask {

      @Overrid
      protected void onPreExecute() {
        //setProgressBarIndeterminateVisibility(true);
      }

     @Override
     protected Integer doInBackground(String... params) {
         Integer result = 0;
         String type = params[0];
         try {
             mediaList = new ArrayList();
              if (type.equalsIgnoreCase("audio")) {
                   parseAllAudio(type);
                   result = 1;
              }
        } catch (Exception e) {
              e.printStackTrace();
              result = 0;
        }
       return result; //"Failed to fetch data!";
   }
    @Override
    protected void onPostExecute(Integer result) {

      // setProgressBarIndeterminateVisibility(false);
      /* Download complete. Lets update UI */
      if (result == 1) {
          adapter = new MediaRVAdapter(MainActivity.this, mediaList);
          mRecyclerView.setAdapter(adapter);
      } else {
          Log.e(TAG, "Failed to fetch data!");
      }
   }
 }
} 

2. MediaRVAdapter.java

package solutions.developer.android.com.recyclerview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.util.List;

/**
 * Created by Mukesh on 12/20/2015.
 */
public class MediaRVAdapter extends RecyclerView.Adapter {


    private List itemList;

    private Context mContext;

    public MediaRVAdapter(Context context, List itemList) {
        this.itemList = itemList;
        this.mContext = context;
    }

    @Override
    public MediaListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, null);
        MediaListRowHolder mh = new MediaListRowHolder(v);

        return mh;
    }

    @Override
    public void onBindViewHolder(MediaListRowHolder mediaListRowHolder, int i) {
        try {
            MediaFileInfo item = itemList.get(i);
            mediaListRowHolder.title.setText(item.getFileName());
            Uri uri = Uri.fromFile(new File(item.getFilePath()));
            if (item.getFileType().equalsIgnoreCase("audio")) {
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(item.getFilePath());
                try {
                    if (mmr != null) {
                        byte[] art = mmr.getEmbeddedPicture();
                        if (art != null && art.length > 0) {
                            Bitmap bmp = BitmapFactory.decodeByteArray(art, 0, art.length);
                            if (bmp != null) {
                                bmp = ThumbnailUtils.extractThumbnail(bmp, 80, 50);
                                mediaListRowHolder.thumbnail.setImageBitmap(bmp);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return (null != itemList ? itemList.size() : 0);
    }

    public class MediaListRowHolder extends RecyclerView.ViewHolder {
        protected ImageView thumbnail;
        protected TextView title;

        public MediaListRowHolder(View view) {
            super(view);
            this.thumbnail = (ImageView) view.findViewById(R.id.image);
            this.title = (TextView) view.findViewById(R.id.name);
        }
    }
} 


Download Complete Code from here

Hope this will help some one.....
Enjoy coding.......
Cheers  :)

Sunday 27 December 2015

Android media store tutorial | List all sdcard audio |List all sdcard video | List all sdcard images

Hello Friends,
       Today, I am going to share my another post on Android Media Store. In this post
I am going to show you how to query media file like audio,images and video using
Android Media Store and Android Content Resolver .









For Listing all Images:
private void parseAllImages() {
        try {
            String[] projection = {MediaStore.Images.Media.DATA};
            cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    projection, // Which columns to return
                    null,       // Return all rows
                    null,
                    null);

          
            int size = cursor.getCount();

            /*******  If size is 0, there are no images on the SD Card. *****/

            if (size == 0) {

            } else {

                int thumbID = 0;
                while (cursor.moveToNext()) {

                    int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                    /**************** Captured image details ************/

                    /*****  Used to show image on view in LoadImagesFromSDCard class ******/
                    String path = cursor.getString(file_ColumnIndex);

                    String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());

                    MediaFileInfo mediaFileInfo = new MediaFileInfo();
                    mediaFileInfo.setFilePath(path);
                    mediaFileInfo.setFileName(fileName);
                    mediaFileInfo.setFileType(type);
                    mediaList.add(mediaFileInfo);
                }
            }


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


For Listing all Video(.mp4)


private void parseAllVideo() {
        try {
            String name = null;
            String[] thumbColumns = {MediaStore.Video.Thumbnails.DATA,
                    MediaStore.Video.Thumbnails.VIDEO_ID};

            int video_column_index;
            String[] proj = {MediaStore.Video.Media._ID,
                    MediaStore.Video.Media.DATA,
                    MediaStore.Video.Media.DISPLAY_NAME,
                    MediaStore.Video.Media.SIZE};
            Cursor videocursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    proj, null, null, null);
            int count = videocursor.getCount();
            Log.d("No of video", "" + count);
            for (int i = 0; i < count; i++) {
                MediaFileInfo mediaFileInfo = new MediaFileInfo();
                video_column_index = videocursor
                        .getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
                videocursor.moveToPosition(i);
                name = videocursor.getString(video_column_index);

                mediaFileInfo.setFileName(name);

                int column_index = videocursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                videocursor.moveToPosition(i);
                String filepath = videocursor.getString(column_index);

                mediaFileInfo.setFilePath(filepath);
                mediaFileInfo.setFileType(type);
                mediaList.add(mediaFileInfo);
                // id += " Size(KB):" +
                // videocursor.getString(video_column_index);


            }
            videocursor.close();

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



For Listing All Audio


private void parseAllAudio() {
        try {
            String TAG = "Audio";
            Cursor cur = getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    null);

            if (cur == null) {
                // Query failed...
                Log.e(TAG, "Failed to retrieve music: cursor is null :-(");

            }
            else if (!cur.moveToFirst()) {
                // Nothing to query. There is no music on the device. How boring.
                Log.e(TAG, "Failed to move cursor to first row (no query results).");

            }else {
                Log.i(TAG, "Listing...");
                // retrieve the indices of the columns where the ID, title, etc. of the song are

                // add each song to mItems
                do {
                    int artistColumn = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                    int titleColumn = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
                    int albumColumn = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM);
                    int durationColumn = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
                    int idColumn = cur.getColumnIndex(MediaStore.Audio.Media._ID);
                    int filePathIndex = cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    Log.i(TAG, "Title column index: " + String.valueOf(titleColumn));
                    Log.i(TAG, "ID column index: " + String.valueOf(titleColumn));

                    Log.i("Final ", "ID: " + cur.getString(idColumn) + " Title: " + cur.getString(titleColumn) + "Path: " + cur.getString(filePathIndex));
                    MediaFileInfo audio = new MediaFileInfo();
                    audio.setFileName(cur.getString(titleColumn));
                    audio.setFilePath(cur.getString(filePathIndex));
                    audio.setFileType(type);
                    mediaList.add(audio);

                } while (cur.moveToNext());
            }

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




Downalod Complete Code: MediaListing


Hope this will help some one.
Enjoy coding..................  ;)

Saturday 19 December 2015

Android Turn on Bluetooth Tethering | Android enable tethering

Hello Friends ,
          Today, I am sharing my another blog on Bluetooth Tethering.  In this tutorial
we can programmatically turn on and off  Bluetooth Tethering.

 





















Here the code:

1. BluetoothTethering.java


package com.solutions.developer.android.com.bluetoothtethering;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Switch;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;


public class BluetoothTethering extends AppCompatActivity {

    BluetoothAdapter mBluetoothAdapter = null;
    Class classBluetoothPan = null;
    Constructor BTPanCtor = null;
    Object BTSrvInstance = null;
    Class noparams[] = {};
    Method mIsBTTetheringOn;
    public static Switch toggle ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_tethering);

        toggle = (Switch) findViewById(R.id.wifi_switch);
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                try {
                    mBluetoothAdapter = getBTAdapter();
                    mBluetoothAdapter.enable();
                    Thread.sleep(100);
                    toggleTethering();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void toggleTethering() {
        Context MyContext = getApplicationContext();
        mBluetoothAdapter = getBTAdapter();
        String sClassName = "android.bluetooth.BluetoothPan";
        try {
            classBluetoothPan = Class.forName("android.bluetooth.BluetoothPan");
            mIsBTTetheringOn = classBluetoothPan.getDeclaredMethod("isTetheringOn", noparams);
            BTPanCtor = classBluetoothPan.getDeclaredConstructor(Context.class, BluetoothProfile.ServiceListener.class);
            BTPanCtor.setAccessible(true);

            BTSrvInstance = BTPanCtor.newInstance(MyContext, new BTPanServiceListener(MyContext));
            Thread.sleep(250);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("NewApi")
    private BluetoothAdapter getBTAdapter() {
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
            return BluetoothAdapter.getDefaultAdapter();
        else {
            BluetoothManager bm = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
            return bm.getAdapter();
        }
    }

    public  static void changeToggleState(boolean state) {
        try{
            if(state){
                toggle.setChecked(BTPanServiceListener.state);
            }else {
                toggle.setChecked(BTPanServiceListener.state);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
 

2. BTPanServiceListener.java




package com.solutions.developer.android.com.bluetoothtethering;

import java.lang.reflect.InvocationTargetException;

import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class BTPanServiceListener implements BluetoothProfile.ServiceListener {
    private final Context context;
    public static boolean state = false;

    public BTPanServiceListener(final Context context) {
        this.context = context;
    }

    @Override
    public void onServiceConnected(final int profile,
                                   final BluetoothProfile proxy) {
        //Some code must be here or the compiler will optimize away this callback.
        Log.i("MyApp", "BTPan proxy connected");
        try {
            boolean nowVal = ((Boolean) proxy.getClass().getMethod("isTetheringOn", new Class[0]).invoke(proxy, new Object[0])).booleanValue();
            if (nowVal) {
                proxy.getClass().getMethod("setBluetoothTethering", new Class[]{Boolean.TYPE}).invoke(proxy, new Object[]{Boolean.valueOf(false)});
                Toast.makeText(context, "Turning bluetooth tethering off", Toast.LENGTH_SHORT).show();
                state = false;
            } else {
                proxy.getClass().getMethod("setBluetoothTethering", new Class[]{Boolean.TYPE}).invoke(proxy, new Object[]{Boolean.valueOf(true)});
                Toast.makeText(context, "Turning bluetooth tethering on", Toast.LENGTH_SHORT).show();
                state = true;
            }
            BluetoothTethering.changeToggleState(state);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(final int profile) {
    }
} 



Download Complete Code : BluetoothTethering

Hope this will help some one.
Enjoy coding....... :)

 

Copyright @ 2013 Android Developers Blog.