Guest User

Untitled

a guest
Jan 3rd, 2013
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.79 KB | None | 0 0
  1. /*
  2. * Copyright (C) 2009 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. using Android.App;
  18. using Android.Bluetooth;
  19. using Android.Content;
  20. using Android.Content.PM;
  21. using Android.OS;
  22. using Android.Util;
  23. using Android.Views;
  24. using Android.Views.InputMethods;
  25. using Android.Widget;
  26. using Java.Lang;
  27.  
  28. namespace BluetoothChat
  29. {
  30.     /// <summary>
  31.     /// This is the main Activity that displays the current chat session.
  32.     /// </summary>
  33.     [Activity(Label = "@string/app_name", MainLauncher = true,
  34.         ConfigurationChanges = ConfigChanges.KeyboardHidden | ConfigChanges.Orientation)]
  35.     public class BluetoothChat : Activity
  36.     {
  37.         // Debugging
  38.         private const string TAG = "BluetoothChat";
  39.         private const bool Debug = true;
  40.  
  41.         // Message types sent from the BluetoothChatService Handler
  42.         // TODO: Make into Enums
  43.         public const int MESSAGE_STATE_CHANGE = 1;
  44.         public const int MESSAGE_READ = 2;
  45.         public const int MESSAGE_WRITE = 3;
  46.         public const int MESSAGE_DEVICE_NAME = 4;
  47.         public const int MESSAGE_TOAST = 5;
  48.  
  49.         // Key names received from the BluetoothChatService Handler
  50.         public const string DEVICE_NAME = "device_name";
  51.         public const string TOAST = "toast";
  52.  
  53.         // Intent request codes
  54.         // TODO: Make into Enums
  55.         private const int REQUEST_CONNECT_DEVICE = 1;
  56.         private const int REQUEST_ENABLE_BT = 2;
  57.         private BluetoothAdapter bluetoothAdapter;
  58.         // Member object for the chat services
  59.         private BluetoothChatService chatService;
  60.  
  61.         // Layout Views
  62.  
  63.         // Name of the connected device
  64.         protected string connectedDeviceName = null;
  65.         // Array adapter for the conversation thread
  66.         protected ArrayAdapter<string> conversationArrayAdapter;
  67.         private ListView conversationView;
  68.         private EditText outEditText;
  69.         // String buffer for outgoing messages
  70.         private StringBuffer outStringBuffer;
  71.         private Button sendButton;
  72.         protected TextView title;
  73.         // Local Bluetooth adapter
  74.  
  75.         protected override void OnCreate(Bundle bundle)
  76.         {
  77.             base.OnCreate(bundle);
  78.  
  79.             if (Debug)
  80.                 Log.Error(TAG, "+++ ON CREATE +++");
  81.  
  82.             // Set up the window layout
  83.             RequestWindowFeature(WindowFeatures.CustomTitle);
  84.             SetContentView(Resource.Layout.main);
  85.             Window.SetFeatureInt(WindowFeatures.CustomTitle, Resource.Layout.custom_title);
  86.  
  87.             // Set up the custom title
  88.             title = FindViewById<TextView>(Resource.Id.title_left_text);
  89.             title.SetText(Resource.String.app_name);
  90.             title = FindViewById<TextView>(Resource.Id.title_right_text);
  91.  
  92.             // Get local Bluetooth adapter
  93.             bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
  94.  
  95.             // If the adapter is null, then Bluetooth is not supported
  96.             if (bluetoothAdapter == null)
  97.             {
  98.                 Toast.MakeText(this, "Bluetooth is not available", ToastLength.Long).Show();
  99.                 Finish();
  100.                 return;
  101.             }
  102.         }
  103.  
  104.         protected override void OnStart()
  105.         {
  106.             base.OnStart();
  107.  
  108.             if (Debug)
  109.                 Log.Error(TAG, "++ ON START ++");
  110.  
  111.             // If BT is not on, request that it be enabled.
  112.             // setupChat() will then be called during onActivityResult
  113.             if (!bluetoothAdapter.IsEnabled)
  114.             {
  115.                 var enableIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
  116.                 StartActivityForResult(enableIntent, REQUEST_ENABLE_BT);
  117.                 // Otherwise, setup the chat session
  118.             }
  119.             else
  120.             {
  121.                 if (chatService == null)
  122.                     SetupChat();
  123.             }
  124.         }
  125.  
  126.         protected override void OnResume()
  127.         {
  128.             base.OnResume();
  129.  
  130.             // Performing this check in onResume() covers the case in which BT was
  131.             // not enabled during onStart(), so we were paused to enable it...
  132.             // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
  133.             if (chatService != null)
  134.             {
  135.                 // Only if the state is STATE_NONE, do we know that we haven't started already
  136.                 if (chatService.GetState() == BluetoothChatService.STATE_NONE)
  137.                 {
  138.                     // Start the Bluetooth chat services
  139.                     chatService.Start();
  140.                 }
  141.             }
  142.         }
  143.  
  144.         private void SetupChat()
  145.         {
  146.             Log.Debug(TAG, "SetupChat()");
  147.  
  148.             // Initialize the array adapter for the conversation thread
  149.             conversationArrayAdapter = new ArrayAdapter<string>(this, Resource.Layout.message);
  150.             conversationView = FindViewById<ListView>(Resource.Id.@in);
  151.             conversationView.Adapter = conversationArrayAdapter;
  152.  
  153.             // Initialize the compose field with a listener for the return key
  154.             outEditText = FindViewById<EditText>(Resource.Id.edit_text_out);
  155.             // The action listener for the EditText widget, to listen for the return key
  156.             outEditText.EditorAction += delegate(object sender, TextView.EditorActionEventArgs e)
  157.                 {
  158.                     // If the action is a key-up event on the return key, send the message
  159.                     if (e.ActionId == ImeAction.ImeNull && e.Event.Action == KeyEventActions.Up)
  160.                     {
  161.                         var message = new String(((TextView) sender).Text);
  162.                         SendMessage(message);
  163.                     }
  164.                 };
  165.  
  166.             // Initialize the send button with a listener that for click events
  167.             sendButton = FindViewById<Button>(Resource.Id.button_send);
  168.             sendButton.Click += delegate
  169.                 {
  170.                     // Send a message using content of the edit text widget
  171.                     var view = FindViewById<TextView>(Resource.Id.edit_text_out);
  172.                     var message = new String(view.Text);
  173.                     SendMessage(message);
  174.                 };
  175.  
  176.             // Initialize the BluetoothChatService to perform bluetooth connections
  177.             chatService = new BluetoothChatService(this, new MyHandler(this));
  178.  
  179.             // Initialize the buffer for outgoing messages
  180.             outStringBuffer = new StringBuffer("");
  181.         }
  182.  
  183.         protected override void OnPause()
  184.         {
  185.             base.OnPause();
  186.  
  187.             if (Debug)
  188.                 Log.Error(TAG, "- ON PAUSE -");
  189.         }
  190.  
  191.         protected override void OnStop()
  192.         {
  193.             base.OnStop();
  194.  
  195.             if (Debug)
  196.                 Log.Error(TAG, "-- ON STOP --");
  197.         }
  198.  
  199.         protected override void OnDestroy()
  200.         {
  201.             base.OnDestroy();
  202.  
  203.             // Stop the Bluetooth chat services
  204.             if (chatService != null)
  205.                 chatService.Stop();
  206.  
  207.             if (Debug)
  208.                 Log.Error(TAG, "--- ON DESTROY ---");
  209.         }
  210.  
  211.         private void EnsureDiscoverable()
  212.         {
  213.             if (Debug)
  214.                 Log.Debug(TAG, "ensure discoverable");
  215.  
  216.             if (bluetoothAdapter.ScanMode != ScanMode.ConnectableDiscoverable)
  217.             {
  218.                 var discoverableIntent = new Intent(BluetoothAdapter.ActionRequestDiscoverable);
  219.                 discoverableIntent.PutExtra(BluetoothAdapter.ExtraDiscoverableDuration, 300);
  220.                 StartActivity(discoverableIntent);
  221.             }
  222.         }
  223.  
  224.         /// <summary>
  225.         /// Sends a message.
  226.         /// </summary>
  227.         /// <param name='message'>
  228.         /// A string of text to send.
  229.         /// </param>
  230.         private void SendMessage(String message)
  231.         {
  232.             // Check that we're actually connected before trying anything
  233.             if (chatService.GetState() != BluetoothChatService.STATE_CONNECTED)
  234.             {
  235.                 Toast.MakeText(this, Resource.String.not_connected, ToastLength.Short).Show();
  236.                 return;
  237.             }
  238.  
  239.             // Check that there's actually something to send
  240.             if (message.Length() > 0)
  241.             {
  242.                 // Get the message bytes and tell the BluetoothChatService to write
  243.                 byte[] send = message.GetBytes();
  244.                 chatService.Write(send);
  245.  
  246.                 // Reset out string buffer to zero and clear the edit text field
  247.                 outStringBuffer.SetLength(0);
  248.                 outEditText.Text = string.Empty;
  249.             }
  250.         }
  251.  
  252.  
  253.         // The Handler that gets information back from the BluetoothChatService
  254.  
  255.         protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
  256.         {
  257.             if (Debug)
  258.                 Log.Debug(TAG, "onActivityResult " + resultCode);
  259.  
  260.             switch (requestCode)
  261.             {
  262.                 case REQUEST_CONNECT_DEVICE:
  263.                     // When DeviceListActivity returns with a device to connect
  264.                     if (resultCode == Result.Ok)
  265.                     {
  266.                         // Get the device MAC address
  267.                         string address = data.Extras.GetString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
  268.                         // Get the BLuetoothDevice object
  269.                         BluetoothDevice device = bluetoothAdapter.GetRemoteDevice(address);
  270.                         // Attempt to connect to the device
  271.                         chatService.Connect(device);
  272.                     }
  273.                     break;
  274.                 case REQUEST_ENABLE_BT:
  275.                     // When the request to enable Bluetooth returns
  276.                     if (resultCode == Result.Ok)
  277.                     {
  278.                         // Bluetooth is now enabled, so set up a chat session
  279.                         SetupChat();
  280.                     }
  281.                     else
  282.                     {
  283.                         // User did not enable Bluetooth or an error occured
  284.                         Log.Debug(TAG, "BT not enabled");
  285.                         Toast.MakeText(this, Resource.String.bt_not_enabled_leaving, ToastLength.Short).Show();
  286.                         Finish();
  287.                     }
  288.                     break;
  289.             }
  290.         }
  291.  
  292.         public override bool OnCreateOptionsMenu(IMenu menu)
  293.         {
  294.             MenuInflater inflater = MenuInflater;
  295.             inflater.Inflate(Resource.Menu.option_menu, menu);
  296.             return true;
  297.         }
  298.  
  299.         public override bool OnOptionsItemSelected(IMenuItem item)
  300.         {
  301.             switch (item.ItemId)
  302.             {
  303.                 case Resource.Id.scan:
  304.                     // Launch the DeviceListActivity to see devices and do scan
  305.                     var serverIntent = new Intent(this, typeof (DeviceListActivity));
  306.                     StartActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
  307.                     return true;
  308.                 case Resource.Id.discoverable:
  309.                     // Ensure this device is discoverable by others
  310.                     EnsureDiscoverable();
  311.                     return true;
  312.             }
  313.             return false;
  314.         }
  315.  
  316.         #region Nested type: MyHandler
  317.  
  318.         private class MyHandler : Handler
  319.         {
  320.             private readonly BluetoothChat bluetoothChat;
  321.  
  322.             public MyHandler(BluetoothChat chat)
  323.             {
  324.                 bluetoothChat = chat;
  325.             }
  326.  
  327.             public override void HandleMessage(Message msg)
  328.             {
  329.                 switch (msg.What)
  330.                 {
  331.                     case MESSAGE_STATE_CHANGE:
  332.                         if (Debug)
  333.                             Log.Info(TAG, "MESSAGE_STATE_CHANGE: " + msg.Arg1);
  334.                         switch (msg.Arg1)
  335.                         {
  336.                             case BluetoothChatService.STATE_CONNECTED:
  337.                                 bluetoothChat.title.SetText(Resource.String.title_connected_to);
  338.                                 bluetoothChat.title.Append(bluetoothChat.connectedDeviceName);
  339.                                 bluetoothChat.conversationArrayAdapter.Clear();
  340.                                 break;
  341.                             case BluetoothChatService.STATE_CONNECTING:
  342.                                 bluetoothChat.title.SetText(Resource.String.title_connecting);
  343.                                 break;
  344.                             case BluetoothChatService.STATE_LISTEN:
  345.                             case BluetoothChatService.STATE_NONE:
  346.                                 bluetoothChat.title.SetText(Resource.String.title_not_connected);
  347.                                 break;
  348.                         }
  349.                         break;
  350.                     case MESSAGE_WRITE:
  351.                         var writeBuf = (byte[]) msg.Obj;
  352.                         // construct a string from the buffer
  353.                         var writeMessage = new String(writeBuf);
  354.                         bluetoothChat.conversationArrayAdapter.Add("Me: " + writeMessage);
  355.                         break;
  356.                     case MESSAGE_READ:
  357.                         var readBuf = (byte[]) msg.Obj;
  358.                         // construct a string from the valid bytes in the buffer
  359.                         var readMessage = new String(readBuf, 0, msg.Arg1);
  360.                         bluetoothChat.conversationArrayAdapter.Add(bluetoothChat.connectedDeviceName + ":  " +
  361.                                                                    readMessage);
  362.                         break;
  363.                     case MESSAGE_DEVICE_NAME:
  364.                         // save the connected device's name
  365.                         bluetoothChat.connectedDeviceName = msg.Data.GetString(DEVICE_NAME);
  366.                         Toast.MakeText(Application.Context, "Connected to " + bluetoothChat.connectedDeviceName,
  367.                                        ToastLength.Short).Show();
  368.                         break;
  369.                     case MESSAGE_TOAST:
  370.                         Toast.MakeText(Application.Context, msg.Data.GetString(TOAST), ToastLength.Short).Show();
  371.                         break;
  372.                 }
  373.             }
  374.         }
  375.  
  376.         #endregion
  377.     }
  378. }
Advertisement
Add Comment
Please, Sign In to add comment