Starting from the beginning of the Baseapplication/activity (ii)

Source: Internet
Author: User

Reprint please indicate the source: Wang 亟亟 's way of Daniel

willing to spend time writing things is not easy, people ah, are flesh and blood have thought, learn from is learning, pure copy is not good, thank you
Some of the information is available online.

《赠梁任父同年》黄遵宪

inch inch mountains and rivers inch gold, Kua from splitting power who ren?
Cuckoo Again Worship sorrow day tears, Jingwei infinite fill the sea heart.

In the previous article we talked about the benefits of simple encapsulation to our efficiency, this one continues to write, if the first hope can be seen, easy to understand. link : 亟亟 on Android Advanced instance

This time we use the most basic activity life cycle method to identify the user's Bluetooth, and in the process to consider the user level of operational understanding, by the way, add the Bluetooth knowledge of the Android phone.

What is Bluetooth?
a wireless technology standard that enables short-range data exchange between fixed devices, mobile devices, and building personal domain networks (UHF radio waves using 2.4-2.485ghz's ISM band).
Vernacular: Android has a certain support for each version of Bluetooth, The Bluetooth headset is supported from the 1.5 cupcake, but since the Android 4.3 version, Google's support for Bluetooth 4.0 has been further improved, so the adaptation to 4.3 has become our work (now it is already common to 5.0 for the development of the low version of the mobile phone is not much, the workload is not very large)

OK, Simple introduction, start today's code

Write a tool class Bluetoothmgr, put the Bluetooth some related operation, put in the inside

/** * Created by Ezreal on 2015/9/14. * * Public  class bluetoothmgr {    Private StaticBluetoothmgr oneinstance =NULL; Public StaticBluetoothadapter Mbluetoothadapter =NULL; Public BooleanAvailable =false;Private StaticList<bluetoothdevice> devlist =NewArraylist<bluetoothdevice> ();Private Bluetoothmgr() { }@TargetApi(Build.version_codes. JELLY_BEAN_MR2)Private Bluetoothmgr(Context context) {intSdkint = Build.VERSION.SDK_INT;if(Sdkint <= build.version_codes.        JELLY_BEAN_MR1) {mbluetoothadapter = Bluetoothadapter.getdefaultadapter (); }Else{Bluetoothmanager manager = (Bluetoothmanager) context.getsystemservice (Context.bluetooth_service);        Mbluetoothadapter = Manager.getadapter (); } available = (NULL! = Mbluetoothadapter); }//Determine if Bluetoothmgr is available     Public Boolean available() {returnAvailable }//Get examples     Public StaticBluetoothmgrgetinstance(Context context) {if(NULL= = oneinstance) {oneinstance =NewBluetoothmgr (context); }returnOneinstance; }//Search Equipment     Public Static Boolean StartDiscovery(){if(NULL= = Mbluetoothadapter) {return false; }if(!mbluetoothadapter.isenabled ()) {mbluetoothadapter.enable (); while(!mbluetoothadapter.isenabled ()) {Try{Thread.Sleep ( +); }Catch(Interruptedexception e)                {E.printstacktrace (); }            }        }if(Mbluetoothadapter.isdiscovering ()) {return true; }returnMbluetoothadapter.startdiscovery (); }//Cancel Search     Public Static Boolean Canceldiscovery() {if(Mbluetoothadapter = =NULL) {return false; }if(Mbluetoothadapter.isdiscovering ()) {returnMbluetoothadapter.canceldiscovery (); }return false; }//Add Device     Public Static void AddOne(Bluetoothdevice device) {if(NULL= = Device) {return; }if(Devlist.contains (device)) {return;    } devlist.add (device); }//Remove device     Public Static void Deleteone(String mac) {if(NULL= = Mac | | Mac.length () = =0) {return; } for(inti =0; I < devlist.size (); ++i) {Bluetoothdevice device = Devlist.get (i);if(Device.getaddress (). Equalsignorecase (MAC)) {Devlist.remove (i); Break; }        }    }//Empty collection     Public Static void clearalldevices() {devlist.clear (); } Public StaticBluetoothdeviceFindOne(intPOS) {if(Pos <0|| POS >= devlist.size ()) {return NULL; }returnDevlist.get (POS); } Public StaticList<bluetoothdevice>getdevlist() {returnDevlist; } Public Static Boolean Isdevlistempty() {return(NULL= = Devlist | |    Devlist.isempty ()); }//Get status     Public Static int getState(){if(mbluetoothadapter!=NULL) {LOGUTILS.D ("Bluetoothmgr","Mbluetoothadapter.getstate ()"+mbluetoothadapter.getstate ());returnMbluetoothadapter.getstate (); }Else{return-1; }    }}

Analysis: Some basic methods of Bluetooth encapsulation, as well as version of the judgment, this side in the example of the Bluetooth related to some specific code content
(This part of the online information is also available, you can look for)

To use Bluetooth on Android, first authorize

    <uses-permission android:name="android.permission.BLUETOOTH" />    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Otherwise, you run the project as an exception.

To use Bluetooth, you must declare aBluetoothAdapter

prior to 4.3
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();Gets the system default Bluetooth.

after 4.3
BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = manager.getAdapter();

list some common methods

Disable () Turn off Bluetooth

Enable () Turn on Bluetooth (users will not receive a prompt)

Here's another way to turn on Bluetooth, but you'll be alerted to manually open

Intent enabler=new Intent (bluetoothadapter.action_request_enable);
Startactivityforresult (Enabler,recode);//With startactivity (enabler);

Canceldiscovery () Cancel Search device

StartDiscovery () Start searching for devices

GetAddress () get local Bluetooth address

GetName () Get the local Bluetooth name

Getremotedevice (stringaddress) Get a remote Bluetooth device based on the Bluetooth address

GetState () Get the current status of the local Bluetooth adapter

Isdiscovering () to determine whether the device is currently being looked up, is true

IsEnabled () Determines whether Bluetooth is turned on, turned on returns True, otherwise, returns false

and then list the status values of Bluetooth
Bluetoothadapter State Value

          int STATE_OFF        蓝牙已经关闭          int STATE_ON        蓝牙已经打开          int STATE_TURNING_OFF      蓝牙处于关闭过程中 ,关闭ing          int STATE_TURNING_ON        蓝牙处于打开过程中 ,打开ing

Bluetoothadapter scan_mod Status value = Scan status

Can scan other devices, of course, it can also be scanned by other Bluetooth device code.

     int  SCAN_MODE_CONNECTABLE         表明该蓝牙可以扫描其他蓝牙设备     int  SCAN_MODE_CONNECTABLE_DISCOVERABLE     可以扫描其他蓝牙设备,并且可以被其他蓝牙设备扫描到。     int  SCAN_MODE_NONE : 该蓝牙不能扫描以及被扫描。

For more information, refer to bluetoothadapter[Bluetooth]

The bedding was done almost as we started today's code.

Requirements: I have an activity, I need to enter his time to let the user turn on the phone Bluetooth, and then to our other Bluetooth hardware to operate, if the user is not willing to open, then stay in the original interface, if the user to open Bluetooth and successful then go to the next operation, If it is not successful, then continue to prompt.

Package Structure:

The base class of the code continues to be added in our previous demo, and more continuity.

Direct Sticker Mainactivity

 Public  class mainactivity extends baseactivity implements View. Onclicklistener {Button button;PrivateMypromptdlg Btnotopendlg =NULL; Bluetoothmgr Blemgr;@Override    protected void FindByID() {button= (button) Findviewbyid (R.id.button); Blemgr=bluetoothmgr.getinstance ( This); }@Override    protected void Setlistener() {Button.setonclicklistener ( This); }@Override    protected void Logic() {    }@Override    protected int GetLayout() {returnR.layout.activity_main; }@Override     Public void OnClick(View v) {if(V.getid () ==r.id.button) {Toast.maketext (mainactivity). This,"is NFC available??" "+nfcisavailable (), Toast.length_short). Show ();        Openbluetoothsetting (); }    }@Override    protected void Onresume() {Super. Onresume (); LOGUTILS.D ("------>onresume");if(Blemgr.isenabled ()) {Toast.maketext (mainactivity). This,"Bluetooth is turned on", Toast.length_short). Show (); }Else{Openbluetooth (); }    }//Turn on Bluetooth    Private void Openbluetooth(){//Determine the status of the activity        if( This. Isfinishing ()) {return; }if(NULL= = Btnotopendlg) {Mypromptdlg.builder Builder =NewMypromptdlg.builder ( This); Builder.settitle (res.getstring (R.string.prompt_dlg_title)). SetText (Res.getstring (r.string.bt_check_mes SAGE). Setpositivebutton (Res.getstring (R.STRING.COMMON_OK),NewDialoginterface.onclicklistener () {@Override                                 Public void OnClick(Dialoginterface Dialog,intwhich) {Dialog.dismiss ();                                Openbluetoothsetting (); }}). Setnegativebutton (Res.getstring (R.string.common_cancel),NewDialoginterface.onclicklistener () {@Override                                 Public void OnClick(Dialoginterface Dialog,intwhich) {Dialog.dismiss ();//finish ();}                            });            Btnotopendlg = Builder.create (); Btnotopendlg.setcancelable (false); Btnotopendlg.setcanceledontouchoutside (false); }if(!btnotopendlg.isshowing ())        {btnotopendlg.show (); }    }//Open the System Bluetooth settings menu    Private void openbluetoothsetting() {Intent Intent =NewIntent (settings.action_bluetooth_settings);        Intent.setflags (Intent.flag_activity_new_task);    StartActivity (Intent); }}

Analysis:
First we initialize a bluetoothmgr in our OnCreate method and let it get the instance of the system Bluetooth (the Bluetoothmgr in the package is a demo version, more common methods are encapsulated in the jar package)

The user enters the app and calls Oncreate–onstart–onresume–activity into the running state in turn.
We did not judge the user's Bluetooth status at OnCreate, but judged it in the Onresume method, which is why? See

Because Onresume will be called multiple times, and OnCreate never be recycled or onstop, we need every time the user focus in our app to determine the status of Bluetooth, that is why we do this.

In order to improve the friendliness of our app, when judging the user does not turn on Bluetooth, we pop up a dialog prompt users to open Bluetooth,

If the user clicks Cancel we will return to the interface, but will not call the Onresume method, otherwise our users have been there to choose Ah, not logical.
Click Yes, call the Openbluetoothsetting () method to manually open, of course, if you feel you need to be strong some can use the Enable () method, directly open, but remember to do a short wait, because the Bluetooth will have a certain asynchronous operation.
Because your code calls to turn on Bluetooth so the user back to the interface will not be able to determine the time to turn on Bluetooth, but also in line with our business needs.

When the user clicks OK, we turn on the Bluetooth Settings menu interface (System)

Came back and then called the Onresume and popped up our toast

OK our business is finished, there are other ways to achieve it? Yes!!

Can use the service, open a ready-made to judge also can achieve results but is not the most ideal way to achieve

There is broadcastreceiver to monitor the changes in Bluetooth mobile phone, the realization of the following

Broadcastreceiver bluetoothstate =NewBroadcastreceiver () { Public void OnReceive(context context, Intent Intent) {String Stateextra = bluetoothadapter.extra_state;intState = Intent.getintextra (Stateextra,-1);Switch(state) { CaseBLUETOOTHADAPTER.STATE_TURNING_ON: Break; CaseBLUETOOTHADAPTER.STATE_ON: Break; CaseBluetoothadapter.state_turning_off: Break; CaseBluetoothadapter.state_off: Break; }}}registerreceiver (Bluetoothstate,NewIntentfilter (bluetoothadapter.action_state_changed));

Remember to sign out Oh!!

Lunch Break!! Source Address: http://yunpan.cn/cmCaaRkzc2UV6 access password 4894

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Starting from the beginning of the Baseapplication/activity (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.