edu.cmu.mpcs.dashboard.TagViewer.java Source code

Java tutorial

Introduction

Here is the source code for edu.cmu.mpcs.dashboard.TagViewer.java

Source

/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.cmu.mpcs.dashboard;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.media.AudioManager;
import android.net.wifi.WifiManager;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.Util;

import edu.cmu.mpcs.android.nfc.parse.LoginButton;
import edu.cmu.mpcs.android.nfc.parse.NdefMessageParser;
import edu.cmu.mpcs.android.nfc.parse.SessionEvents;
import edu.cmu.mpcs.android.nfc.parse.SessionStore;
import edu.cmu.mpcs.android.nfc.parse.SessionEvents.AuthListener;
import edu.cmu.mpcs.android.nfc.parse.SessionEvents.LogoutListener;
import edu.cmu.mpcs.android.nfc.record.ParsedNdefRecord;
import edu.cmu.mpcs.android.nfc.record.TextRecord;
import edu.cmu.mpcs.android.nfc.record.UriRecord;
import edu.cmu.mpcs.android.nfc.record.WriteToTag;
import edu.cmu.mpcs.dashboard.LoginActivity.FbAPIsAuthListener;
import edu.cmu.mpcs.dashboard.LoginActivity.FbAPIsLogoutListener;
import edu.cmu.mpcs.dashboard.LoginActivity.UserRequestListener;
import edu.cmu.mpcs.facebook.BaseRequestListener;
import edu.cmu.mpcs.facebook.PlacesActivity;

/**
 * An {@link Activity} which handles a broadcast of a new tag that the device
 * just discovered.
 */
public class TagViewer extends Activity {

    // static boolean flag = false;
    final static int RETURN_TO_TAG_VIEW = 2;
    final static int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;

    // public static final String APP_ID = "272708992799068";
    public static final String APP_ID = "371019832916261";

    private static final int CHECKINSUCCESS = 1;

    /** Called when the activity is first created. */
    Facebook facebook = new Facebook(APP_ID);
    String FILENAME = "AndroidSSO_data";
    static SharedPreferences mPrefs;

    String[] permissions = { "offline_access", "publish_stream", "user_photos", "publish_checkins",
            "photo_upload" };

    private LoginButton mLoginButton;

    protected static int HELLO_ID = 1;
    static final String TAG = "ViewTag";

    /**
     * This activity will finish itself in this amount of time if the user
     * doesn't do anything.
     */
    static final int ACTIVITY_TIMEOUT_MS = 1 * 1000;

    // TextView mTitle;

    // LinearLayout mTagContent;

    NfcAdapter mNfcAdapter;
    PendingIntent mNfcPendingIntent;
    IntentFilter[] mWriteTagFilters;
    IntentFilter[] mNdefExchangeFilters;
    private boolean mWriteMode;
    Button b;
    String writeContent;
    static AlertDialog.Builder builder;

    private static AlertDialog dialog;
    Intent loginIntent;
    private boolean InitializeLogin = false;

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

        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

        Intent intent = this.getIntent();
        writeContent = intent.getStringExtra("writeContent");

        mLoginButton = new LoginButton(getApplicationContext());

        // if(flag == true)

        Log.d("TAG_VIEWER", "writeConent:" + writeContent);
        // setContentView(R.layout.tag_viewer);
        mNfcPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        // mTagContent = (LinearLayout) findViewById(R.id.list);
        // mTitle = (TextView) findViewById(R.id.title);

        Log.d("TAG_VIEWER", "Utility.mFacebook is " + Utility.mFacebook);
        if (Utility.mFacebook == null) {
            InitializeLogin = true;

        }
        // Create the Facebook Object using the app id.
        edu.cmu.mpcs.dashboard.Utility.mFacebook = new Facebook(APP_ID);
        // Instantiate the asynrunner object for asynchronous api calls.
        edu.cmu.mpcs.dashboard.Utility.mAsyncRunner = new AsyncFacebookRunner(
                edu.cmu.mpcs.dashboard.Utility.mFacebook);

        Log.d("TAG_VIEWER", "in oncreate in TagViewer is session valid?:" + Utility.mFacebook.isSessionValid());

        mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);

        if (APP_ID == null) {
            Util.showAlert(this, "Warning",
                    "Facebook Applicaton ID must be " + "specified before running this example: see FbAPIs.java");
            return;
        }

        SessionStore.restore(Utility.mFacebook, this);
        SessionEvents.addAuthListener(new FbAPIsAuthListener());
        SessionEvents.addLogoutListener(new FbAPIsLogoutListener());
        // SessionEvents.r

        if (Utility.mFacebook.isSessionValid()) {
            requestUserData();

        }

        // TODO do something about - dont call resolve intent by
        // default.
        if (writeContent == null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Log.d("TAG_VIEWER", "in OnCreate Before reading");
            loginIntent = intent;

            if (InitializeLogin) { /*
                                   * This is if we come to tag viewer without
                                   * having started dashboard activity
                                   */
                mLoginButton.initializeFbLogin();
            } else { /* This is we if read the tag while in dashboard! */
                resolveIntent(intent);

            }
            // mLoginButton.performLogout();

        } else {
            Log.d("TAG_VIEWER", "Before creating alert dialog");
            builder = new AlertDialog.Builder(TagViewer.this);
            dialog = builder.create();
            builder.setTitle("Touch tag to write").setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    Log.d("TAG_VIEWER", "On cancel called");
                    disableTagWriteMode();

                }
            }).create();
            dialog.setTitle("touch tag to write");
            dialog.show();
            dialog.setOnDismissListener(new OnDismissListener() {

                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    Log.d("TAG_VIEWER", "On dismiss called");
                    disableTagWriteMode();

                }
            });
            // builder.setCancelable(true);
            // builder.setOnCancelListener(new
            // DialogInterface.OnCancelListener() {
            // public void onCancel(DialogInterface dialog) {
            // Log.d("TAG_VIEWER","On cancel called");
            // disableTagWriteMode();
            //
            // }
            // }).create().show();
        }

        // Tag writing mode
        if (writeContent != null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Log.d("TAG_VIEWER", "in Oncreate Before writing");

            Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            try {
                WriteToTag.write(detectedTag, writeContent);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("TAG_VIEWER", "in on create, writing to tag");
        }
        Log.d("TAG_VIEWER", "in create");

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("TAG_VIEWER", "in on activity result, result code is: " + Integer.toString(resultCode));

        Log.d("TAG_VIEWER", "in on activity result, result code is: " + Integer.toString(resultCode));

        /*
         * if (resultCode == ACTIVITY_LOGOUT) { Log.d("TAG_VIEWER",
         * "logging out the user"); mLoginButton.performLogout(); return; }
         */

        switch (requestCode) {
        /*
         * if this is the activity result from authorization flow, do a call
         * back to authorizeCallback Source Tag: login_tag
         */
        case AUTHORIZE_ACTIVITY_RESULT_CODE: {
            Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
            break;
        }

        }

        if (resultCode == CHECKINSUCCESS) {
            InitializeLogin = false;
            mLoginButton.performLogout();
        }

        /*
         * if (resultCode == RETURN_TO_TAG_VIEW) { Log.d("TAG_VIEWER",
         * "on acvitiy for result"); resolveIntent(loginIntent); }
         */

    }

    private OnClickListener onClickListener() {
        // TODO Auto-generated method stub
        return null;
    }

    void resolveIntent(Intent intent) {
        // Parse the intent
        String action = intent.getAction();
        Log.d("TAG_VIEWER", "in resolve intent");
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            // When a tag is discovered we send it to the service to
            // be save. We
            // include a PendingIntent for the service to call back
            // onto. This
            // will cause this activity to be restarted with
            // onNewIntent(). At
            // that time we read it from the database and view it.
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                // Unknown tag type
                byte[] empty = new byte[] {};
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
                NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };
            }
            // Setup the views
            setTitle(R.string.title_scanned_tag);
            buildTagViews(msgs);
        } else {
            Log.e(TAG, "Unknown intent " + intent);
            // finish();
            return;
        }
    }

    void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) {
            return;
        }
        LayoutInflater inflater = LayoutInflater.from(this);
        // LinearLayout content = mTagContent;
        // Clear out any old views in the content area, for example if
        // you scan
        // two tags in a row.
        // content.removeAllViews();
        // Parse the first message in the list
        // Build views for all of the sub records
        Log.i("TEST", "test");
        List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
        NdefRecord[] ndefRecords = msgs[0].getRecords();
        short tnf = ndefRecords[0].getTnf();

        Log.d("RECORD", "tnf is : " + Short.toString(tnf));

        byte[] type = ndefRecords[0].getType();
        byte[] standard = NdefRecord.RTD_TEXT;

        System.out.println("printing what we got in the message");
        for (byte theByte : type) {
            System.out.println(Integer.toHexString(theByte));
            Log.d("RECORD", Integer.toHexString(theByte));
        }

        System.out.println("printing what the actual val is ");
        for (byte theByte : standard) {
            System.out.println(Integer.toHexString(theByte));
            Log.d("RECORD", Integer.toHexString(theByte));
        }
        if (ndefRecords[0].getType().equals(standard))
            Log.d("RECORD", " type is : RTD_TXT");
        else if (ndefRecords[0].getType().equals(NdefRecord.RTD_URI))
            Log.d("RECORD", " type is : RTD_URI");
        else
            Log.d("RECORD", " type is : none of the 2");
        final int size = records.size();
        for (int i = 0; i < size; i++) {
            ParsedNdefRecord record = records.get(i);
            Log.i("RECORD", record.toString());
            String text;
            if (record instanceof TextRecord) {
                TextRecord t = (TextRecord) record;
                text = t.getText();
            } else {
                UriRecord t = (UriRecord) record;
                text = t.getUri().toString();
            }
            Log.d("WIFI", text);

            /*
             * At this point we have obtained the name of the profile . We
             * should not append .txt and see if the file exists in the
             * /mnt/Profile folder.
             * 
             * If it does exist, then we read the file, and apply various
             * settings
             * 
             * If it does note exists, then we show an error message indicating
             * that the user does not have a profile corresponding to this TAG.
             * Alternatively: We can take him to the create TAG activity where
             * he can create a new TAG with this name.
             */

            String contents[] = text.split("#");
            String filename = null;
            if (contents.length > 1) {

                String readHash = contents[0];
                filename = contents[1];

                Log.d("TAG_VIEWER", "readHash: " + readHash);
                Log.d("TAG_VIEWER", "filename: " + filename);

                if (readHash.equals(Utility.hashOfId)) {
                    Log.d("TAG_VIEWER", "Hash Valid");

                    File root = Environment.getExternalStorageDirectory();
                    String path = root + "/Profiles/" + Utility.userUID + "/";
                    String filePath = path + filename + ".txt";
                    String settingString = "";
                    boolean exists = (new File(path).exists());

                    if (exists) {
                        Log.d("TAG_VIEWER", "Found file:" + filePath);
                        /*
                         * Parse the contents of the file, and apply settings
                         */
                        try {

                            FileReader logReader = new FileReader(filePath);
                            BufferedReader in = new BufferedReader(logReader);
                            try {
                                settingString = in.readLine();

                                Log.d("TAG_VIEWER", "In " + filePath + " settingString: " + settingString);
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                Log.d("TAG_VIEWER", " read(buf) exception");
                                e.printStackTrace();
                            }
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            Log.d("TAG_VIEWER", "FileReader exception");
                            e.printStackTrace();
                        }

                        /*
                         * One call for each setting that we support
                         */
                        StringBuilder returnVal = new StringBuilder();

                        returnVal.append(wifiSetting(settingString));

                        returnVal.append(bluetoothSetting(settingString));

                        returnVal.append(ringerSetting(settingString));

                        launchmusicSetting(settingString);

                        returnVal.append(alarmSetting(settingString));

                        fbSetting(settingString);

                        Log.d("TAG_VIEWER", "the toast should be : " + returnVal.toString());

                        Context context = getApplicationContext();
                        CharSequence toastMessage = returnVal;
                        int duration = Toast.LENGTH_LONG;
                        Toast toast = Toast.makeText(context, toastMessage, duration);
                        toast.show();

                    } else {
                        /*
                         * Give the user the option of creating a new tag or
                         * ignoring this tag
                         */
                    }

                } else {
                    Log.d("TAG_VIEWER", "Hash InValid");
                    int duration = Toast.LENGTH_LONG;
                    CharSequence msg = "Authentication failure.This tag does not belong to you";
                    Toast toast = Toast.makeText(TagViewer.this, msg, duration);
                    toast.show();
                    finish();
                    // return;
                }

            } else {
                // public tag
                Log.d("PUBLIC_TAG", "PUBLIC_TAG");
            }

            // For Vibrate mode
            //

            /** Sending an SMS to a particular number **/

            // Intent intent = new
            // Intent(Intent.ACTION_VIEW,
            // Uri.parse("sms:" + "5189515772"));
            // intent.putExtra("sms_body",
            // "Hi This is a test message");
            // startActivity(intent);

            /** Toggle Airplane mode **/

            // Context context = getApplicationContext();
            // boolean isEnabled =
            // Settings.System.getInt(this.getApplicationContext().getContentResolver(),
            // Settings.System.AIRPLANE_MODE_ON, 0) == 1;
            // Settings.System.putInt(context.getContentResolver(),Settings.System.AIRPLANE_MODE_ON,isEnabled
            // ? 0 : 1);
            // Intent intent = new
            // Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            // intent.putExtra("state", !isEnabled);
            // sendBroadcast(intent);

            /** Launching the browser **/

            // String url = "http://www.google.com";
            // Intent intent = new
            // Intent(Intent.ACTION_VIEW);
            // intent.setData(Uri.parse(url));
            // startActivity(intent);

            /** Check into Facebook **/

            // Bundle params = new Bundle();
            //
            // //String access_token =
            // AndroidDashboardActivity.mPrefs.getString("access_token",
            // null);
            // //params.putString("access_token", access_token);
            // params.putString("place", "203682879660695"); // YOUR PLACE
            // ID
            // params.putString("Message","I m here in this place");
            // JSONObject coordinates = new JSONObject();
            // try
            // {
            // coordinates.put("latitude", 40.756);
            // coordinates.put("longitude", -73.987);
            // }
            // catch (JSONException e)
            // {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            //
            // params.putString("coordinates",coordinates.toString());
            // JSONArray frnd_data=new JSONArray();
            // params.putString("tags", "waves.mpcs@gmail.com");//where xx
            // indicates the User Id
            // String response;
            // try
            // {
            // response = facebook.request("me/checkins", params, "POST");
            // Log.d("Response",response);
            // }
            // catch (FileNotFoundException e)
            // {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // catch (MalformedURLException e)
            // {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // catch (IOException e)
            // {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // //Log.d("Response",response);

            /*
             * TODO: Hashing TODO: Facebook Auth TODO: File Storage (Profile
             * Storage) TODO: Sample Profiles TODO: Social Network Check in
             * TODO: Alarms TODO: Airplane Mode (Enabling NFC while switching to
             * Airplane mode) TODO: NFC Launcher List (Market App) TODO: UI
             */

            // content.addView(record.getView(this, inflater, content, i));
            // inflater.inflate(R.layout.tag_divider, content, true);
        }

    }

    private String alarmSetting(String settingString) {
        if (settingString.contains("set alarm")) {
            /** Set Alarm **/

            String hour = settingString.substring(settingString.indexOf("#") + 1, settingString.indexOf("*"));
            String minute = settingString.substring(settingString.indexOf("*") + 1, settingString.indexOf("|"));

            Log.d("timePicker", hour + ":" + minute);

            int hr = Integer.parseInt(hour);
            int min = Integer.parseInt(minute);

            Log.d("Alarm", "hr:" + hr + "min:" + min);

            Calendar cal = Calendar.getInstance();
            // add minutes to the calendar object
            //
            cal.set(Calendar.HOUR_OF_DAY, hr);
            cal.set(Calendar.MINUTE, min);
            cal.set(Calendar.SECOND, 0);
            // cal.add(Calendar.MINUTE, 1);
            Intent alarmintent = new Intent(getApplicationContext(), AlarmReceiver.class);
            alarmintent.putExtra("title", "Alarm for " + hour + ":" + minute);
            alarmintent.putExtra("note", "Touch to turn off Alarm");
            // HELLO_ID is a static variable that must be
            // initialised at the BEGINNING OF CLASS with 1;

            PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID, alarmintent,
                    PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
            // VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT...
            // this will send correct extra's informations
            // to
            // AlarmReceiver Class
            // Get the AlarmManager service

            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

            am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
            Log.i("Alarm", "AlarmSet" + cal.toString());

            // /** Auto-sync **/
            //
            // if (!ContentResolver.getMasterSyncAutomatically())
            // ContentResolver.setMasterSyncAutomatically(true);
            // else {
            // ContentResolver.setMasterSyncAutomatically(false);
            // }

            return ("AlarmSet for : " + hour + ":" + min + "\n");

        }
        return ("");

    }

    private void launchmusicSetting(String settingString) {

        if (settingString.contains("launch music")) {

            AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

            if (!mAudioManager.isMusicActive()) {
                Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.google.android.music");
                startActivity(LaunchIntent);
            }

            if (settingString.contains("launch music:On")) {
                /** Launching the Music App **/
                Intent commandIntent = new Intent("com.android.music.musicservicecommand");
                commandIntent.putExtra("command", "play");
                sendBroadcast(commandIntent);

            } else {
                Intent commandIntent = new Intent("com.android.music.musicservicecommand");
                commandIntent.putExtra("command", "pause");
                sendBroadcast(commandIntent);

            }
        }

    }

    private String ringerSetting(String settingString) {
        /*****
         * Setting the phone on Silent, Vibrate and Normal modes
         *****/

        if (settingString.contains("ringer")) {
            AudioManager audMangr;
            audMangr = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

            // For Normal mode
            // audMangr.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            // For Silent mode
            // audMangr.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            // For vibrate
            // audMangr.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

            if (settingString.contains("ringer:Loud")) {
                audMangr.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                return ("Phone Ringer:Loud\n");

            } else {
                audMangr.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                return ("Phone Ringer:Vibrate\n");

            }

            /* Adjusting volume */
            // if (audMangr.getRingerMode() == AudioManager.RINGER_MODE_NORMAL)
            // {
            // Log.d("RINGER", "setting ringer to silent");
            // audMangr.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            // audMangr.adjustVolume(AudioManager.ADJUST_LOWER, 0);
            //
            // } else {
            // Log.d("RINGER", "setting ringer to normal");
            //
            //
            // }
        }

        return ("");

    }

    private String bluetoothSetting(String settingString) {
        /*
         * Enable/Disable bluetooth
         */
        if (settingString.contains("bluetooth")) {
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (settingString.contains("bluetooth:On")) {
                mBluetoothAdapter.enable();
                return ("Bluetooth turned On\n");

            } else {
                mBluetoothAdapter.disable();
                return ("Bluetooth turned Off\n");

            }

        }
        return ("");

    }

    private String wifiSetting(String settingString) {
        /*
         * Enable/Disable wifi
         */
        if (settingString.contains("wifi")) {
            WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
            if (settingString.contains("wifi:On")) {
                wifiManager.setWifiEnabled(true);
                return ("Wifi turned On\n");
            } else {
                wifiManager.setWifiEnabled(false);
                return ("Wifi turned Off\n");
            }
        }
        return ("");

    }

    private void fbSetting(String settingString) {

        Log.d("TAG_VIEWER", "In fbsetting!!");

        if (settingString.contains("facebook")) {
            String access_token = Utility.mFacebook.getAccessToken();
            System.out.println("access token us : " + access_token);
            final Intent myIntent = new Intent(getApplicationContext(), PlacesActivity.class);
            myIntent.putExtra("LOCATION", "current");
            startActivityForResult(myIntent, 0);

            /*
             * new AlertDialog.Builder(TagViewer.this)
             * .setTitle(R.string.get_location)
             * .setMessage(R.string.get_default_or_new_location)
             * .setPositiveButton(R.string.current_location_button, new
             * DialogInterface.OnClickListener() {
             * 
             * public void onClick(DialogInterface dialog, int which) {
             * myIntent.putExtra("LOCATION", "current");
             * startActivity(myIntent); } }) .setNegativeButton("TimeSquare",
             * new DialogInterface.OnClickListener() {
             * 
             * public void onClick(DialogInterface dialog, int which) {
             * myIntent.putExtra("LOCATION", "times_square");
             * startActivity(myIntent); }
             * 
             * }).show();
             */

        } else {
            /* Performing logout when there is no fb checkin. */
            InitializeLogin = false;
            mLoginButton.performLogout();
        }
    }

    private View.OnClickListener mTagWriter = new View.OnClickListener() {
        public void onClick(View arg0) {
            // Write to a tag for as long as the dialog is shown.
            Log.d("TAG_VIEWER", "in on click");
            enableTagWriteMode();

        }
    };

    @Override
    public void onResume() {
        super.onResume();
        Log.d("TAG_VIEWER", "in onResume");

        if (Utility.mFacebook != null) {
            if (!Utility.mFacebook.isSessionValid()) {
                Log.d("TAG_VIEWER", "you are logged out!");
                /*
                 * mText.setText("You are logged out! ");
                 * mUserPic.setImageBitmap(null);
                 */
            } else {
                Log.d("TAG_VIEWER", "in on resume");
                Utility.mFacebook.extendAccessTokenIfNeeded(this, null);
            }
        }

        if (writeContent != null) {
            Log.d("TAG_VIEWER", "in onResume, writeContent is not null");
            enableTagWriteMode();
        } else {
            Log.d("TAG_VIEWER", "in onResume, writeContent is null");
        }

    }

    @Override
    public void onNewIntent(Intent intent) {
        setIntent(intent);
        Log.d("TAG_VIEWER", "on new intent actually fired ");
        if (!mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {

            resolveIntent(intent);
        }

        // Tag writing mode
        if (writeContent != null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Log.d("TAG_VIEWER", "in Oncreate Before writing");

            // new AlertDialog.Builder(TagViewer.this)
            // .setTitle("Touch tag to write")
            // .setOnCancelListener(
            // new DialogInterface.OnCancelListener() {
            // public void onCancel(DialogInterface dialog) {
            // disableTagWriteMode();
            //
            // }
            // }).create().show();

            Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            try {
                WriteToTag.write(detectedTag, writeContent);
                Context context = getApplicationContext();
                CharSequence text = "Tag sucessfully written!!";
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();

                Log.d("TAG_VIEWER", "Before calling dialog.cancel");
                dialog.dismiss();
                finish();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("TAG_VIEWER", "in on create, writing to tag");
        }
        //
        // // Tag writing mode
        // if (mWriteMode
        // &&
        // NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()))
        // {
        // Tag detectedTag =
        // intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        // try {
        // WriteToTag.write(detectedTag);
        // } catch (IOException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // } catch (FormatException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // Log.d("TAG_VIEWER", "in on new intent, writing to tag");
        // }
    }

    @Override
    public void setTitle(CharSequence title) {
        // mTitle.setText(title);
    }

    private void enableTagWriteMode() {
        Log.d("TAG_VIEWER", "in enable tag write");
        mWriteMode = true;
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        // tagDetected.addDataScheme("http");
        // IntentFilter techFilter = new
        // IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        try {
            tagDetected.addDataType("text/plain");
            // tagDetected.addDataScheme("http");
            // techFilter.addDataType("text/plain");
        } catch (MalformedMimeTypeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        IntentFilter httpDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        httpDetected.addDataScheme("http");

        mWriteTagFilters = new IntentFilter[] { tagDetected, httpDetected };
        mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null);
    }

    private void disableTagWriteMode() {
        Log.d("TAG_VIEWER", "in disable tag write");
        // mNfcAdapter.disableForegroundDispatch(this);
    }

    /*
     * Callback for fetching current user's name, picture, uid.
     */
    public class UserRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(response);

                final String picURL = jsonObject.getString("picture");
                final String name = jsonObject.getString("name");
                Utility.userUID = jsonObject.getString("id");

                Utility.hashOfId = Utility.SHAsum(Utility.userUID.getBytes());
                Log.d("TAG_VIEWER", Utility.hashOfId);

                Log.d("TAG_VIEWER", "name is :" + name);
                Log.d("TAG_VIEWER", "id is :" + Utility.userUID);
                Log.d("TAG_VIEWER", "here!!!!");

                /*
                 * mHandler.post(new Runnable() {
                 * 
                 * @Override public void run() { mText.setText("Welcome " + name
                 * + "!"); mUserPic.setImageBitmap(Utility.getBitmap(picURL)); }
                 * });
                 */

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    /*
     * Request user name, and picture to show on the main screen.
     */
    public void requestUserData() {
        // mText.setText("Fetching user name, profile pic...");
        Bundle params = new Bundle();
        params.putString("fields", "name, picture");
        Utility.mAsyncRunner.request("me", params, new UserRequestListener());
    }

    /*
     * The Callback for notifying the application when authorization succeeds or
     * fails.
     */

    public class FbAPIsAuthListener implements AuthListener {

        public void onAuthSucceed() {
            // Log.d("TAG_VIEWER",
            // "value of login object on authentication success is:" +
            // LoginActivity.this);
            // Log.d("TAG_VIEWER",
            // "value of FbAPIs object on authentication success is:" + this);
            Log.d("TAG_VIEWER", "Login success! congrats :D");

            requestUserData();

            resolveIntent(loginIntent);

            // TagViewer.flag = true;

        }

        public void onAuthFail(String error) {
            // mText.setText("Login Failed: " + error);
            Log.d("TAG_VIEWER", "login failed");
        }
    }

    /*
     * The Callback for notifying the application when log out starts and
     * finishes.
     */
    public class FbAPIsLogoutListener implements LogoutListener {

        public void onLogoutBegin() {
            Log.d("TAG_VIEWER", "Logging out...");
            // mText.setText("Logging out...");
        }

        public void onLogoutFinish() {
            Log.d("TAG_VIEWER", "You have logged out!!");
            finish();
            android.os.Process.killProcess(android.os.Process.myPid());

            /*
             * mText.setText("You have logged out! ");
             * mUserPic.setImageBitmap(null);
             */
        }
    }

}