scmu.nutweet.bluetooth.BluetoothChat.java Source code

Java tutorial

Introduction

Here is the source code for scmu.nutweet.bluetooth.BluetoothChat.java

Source

/*
 * Copyright (C) 2009 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 scmu.nutweet.bluetooth;

import android.app.*;
import android.app.ActionBar.Tab;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import scmu.nutweet.R;
import scmu.nutweet.consts.Const;
import scmu.nutweet.fragments.ChatFragment;
import scmu.nutweet.fragments.FriendListFragment;
import scmu.nutweet.fragments.NewTweetFragment;

/**
 * This is the main Activity that displays the current chat session.
 */
public class BluetoothChat extends FragmentActivity implements ActionBar.TabListener {
    // Debugging
    private static final String TAG = "BluetoothChat";
    private static final boolean D = true;

    public static final int FRIENDS_POSITION = 0;
    public static final int CHAT_POSITION = 1;

    // Message types sent from the BluetoothIntentService Handler
    public static final byte MESSAGE_STATE_CHANGE = 1;
    public static final byte MESSAGE_READ = 2;
    public static final byte MESSAGE_WRITE = 3;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE = "device";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (D)
            Log.e(TAG, "+++ ON CREATE +++");

        // Set up the window layout
        setContentView(R.layout.activity_chat);

        // Set up the action bar to show tabs.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayHomeAsUpEnabled(true);

        // For each of the sections in the app, add a tab to the action bar.
        actionBar.addTab(actionBar.newTab().setIcon(R.drawable.friends_black).setTabListener(this));
        actionBar.addTab(actionBar.newTab().setIcon(R.drawable.chatmsg_black).setTabListener(this));

        //stateChange(Const.mService.getState());
    }

    @Override
    public void onStart() {
        super.onStart();
        if (D)
            Log.e(TAG, "++ ON START ++");

        if (mHandler == null)
            mHandler = new MyHandler(this);
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if (D)
            Log.e(TAG, "+ ON RESUME +");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (D)
            Log.e(TAG, "--- ON DESTROY ---");
    }

    private void ensureDiscoverable() {
        if (D)
            Log.d(TAG, "ensure discoverable");
        if (Const.mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    private final void setStatus(int resId) {
        final ActionBar actionBar = getActionBar();
        actionBar.setSubtitle(resId);
    }

    private final void setStatus(CharSequence subTitle) {
        final ActionBar actionBar = getActionBar();
        actionBar.setSubtitle(subTitle);
    }

    public static Handler mHandler;

    private static class MyHandler extends Handler {
        private final BluetoothChat bc;

        public MyHandler(BluetoothChat bluetoothChat) {
            this.bc = bluetoothChat;
        }

        @Override
        public void handleMessage(Message msg) {
            String line;
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                bc.stateChange(msg.arg1);
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
                line = "Me:  " + writeMessage;
                Const.currentConversationAdapter.add(line);
                Const.currentConversationView.invalidate();
                if (Const.currentFriend != null)
                    Const.friendsList.get(Const.currentFriend).getChatHistory().add(line);
                break;
            case MESSAGE_READ:
                BluetoothDevice device = msg.getData().getParcelable(BluetoothChat.DEVICE);

                Log.d("DEBUG", "Received message read!");
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg2);
                String username = Const.macToUsername.get(device.getAddress());

                line = username + ":  " + readMessage;

                if (Const.currentFriend.equals(username) && Const.currentConversationAdapter != null
                        && Const.currentConversationView != null) {
                    Const.currentConversationAdapter.add(line);
                    Const.currentConversationView.invalidate();
                }

                Const.friendsList.get(username).getChatHistory().add(line);
                break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (D)
            Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE_SECURE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, true);
            }
            break;
        case REQUEST_CONNECT_DEVICE_INSECURE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, false);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
            } else {
                // User did not enable Bluetooth or an error occurred
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    public void stateChange(int state) {
        //      if (D)
        //         Log.i(TAG, "MESSAGE_STATE_CHANGE: " + state);
        //      switch (state) {
        //      case BluetoothService.STATE_CONNECTED:
        //         setStatus(getString(R.string.title_connected_to, Const.connectedDeviceName));
        //         if (mConversationArrayAdapter != null)
        //            mConversationArrayAdapter.clear();
        //         break;
        //      case BluetoothService.STATE_CONNECTING:
        //         setStatus(R.string.title_connecting);
        //         break;
        //      case BluetoothService.STATE_LISTEN:
        //      case BluetoothService.STATE_NONE:
        //         setStatus(R.string.title_not_connected);
        //         break;
        //      }
    }

    public static void connectDevice(Intent data, boolean secure) {
        // Get the device MAC address
        String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BluetoothDevice object
        BluetoothDevice device = Const.mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        Const.mService.connect(device, secure);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_chat, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent serverIntent;
        switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        case R.id.secure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
            return true;
        case R.id.insecure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
            return true;
        case R.id.discoverable:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        case R.id.newtweet:
            FragmentManager fm = getFragmentManager();
            DialogFragment dialog = NewTweetFragment.newInstance();
            dialog.show(fm, "dialog");
            return true;
        }
        return false;
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // When the given tab is selected, show the tab contents in the
        // container view.
        Fragment fragment;

        switch (tab.getPosition()) {
        case CHAT_POSITION:
            fragment = new ChatFragment(this, mHandler);
            getFragmentManager().beginTransaction().replace(R.id.containerChat, fragment).commit();
            break;
        case FRIENDS_POSITION:
            fragment = new FriendListFragment(this);
            getFragmentManager().beginTransaction().replace(R.id.containerChat, fragment).commit();
            break;
        default:
            break;
        }
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {

    }

}