Starting from scratch: "starting from BaseApplication/Activity (2)", applicationactivity

Source: Internet
Author: User

Starting from scratch: "starting from BaseApplication/Activity (2)", applicationactivity
Reprinted, please indicate the source: the path to the great ox of Wang XiaoYu

It is not easy to take time to write things. People are full of flesh, blood, and thoughts. Learning from and learning is not good. Thanks
Some documents can be found on the Internet.

The same year as the father of beam, Huang Zunxian

Who is the root of the split?
Du Fu then worships the sky and tears, and Jingwei infinite reclamation.

In the previous article, we talked about the benefits of simple encapsulation for us to improve efficiency. This article will continue to be written. If you have not read the first article, you can easily understand it.Link: Zookeeper advanced instances in Android

This time, we use the most basic method in the Activity lifecycle to identify users' Bluetooth and consider the user-level operation understanding during the process, by the way, I would like to add the Bluetooth knowledge of Android phones.

What is Bluetooth?
A wireless technology standard that enables short-distance data exchange between fixed devices, mobile devices, and building personal networks (using 2.4-GHz ISM band UHF radio waves ).
Vernacular: Android has some support for all versions of Bluetooth. Cupcake of Android 1.5 supports Bluetooth headsets. However, since Android 4.3, Google has supported Bluetooth 4.0, further improvement, so the adaptation to 4.3 and later became our work (currently there are not many mobile phones with a general development environment of 5.0, and the workload is not enough)

OK. After a brief introduction, let's start the code today.

Write a tool class named systthmgr and put some Bluetooth-related operations in it.

/*** Created by Ezreal on 2015/9/14. */public class implements thmgr {private static implements thmgr oneInstance = null; public static implements thadapter mBluetoothAdapter = null; public boolean available = false; private static List <shortthdevice> devList = new ArrayList <shortthdevice> (); private shortthmgr () {}@ TargetApi (Build. VERSION_CODES.JELLY_BEAN_MR2) private incluthmgr (Context context ){ Int sdkInt = Build. VERSION. SDK_INT; if (sdkInt <= Build. VERSION_CODES.JELLY_BEAN_MR1) {mblustmthadapter = descrithadapter. getdefaadapter adapter ();} else {descrithmanager manager = (descrithmanager) context. getSystemService (Context. BLUETOOTH_SERVICE); mbluw.thadapter = manager. getAdapter ();} available = (null! = Mblustmthadapter);} // determines whether javasthmgr is available public boolean available () {return available;} // gets the instance public static descrithmgr getInstance (Context context) {if (null = oneInstance) {oneInstance = new incluthmgr (context) ;}return oneInstance ;}// search for the public static boolean startDiscovery () {if (null = mbluw.thadapter) Device) {return false;} if (! Mblustmthadapter. isEnabled () {mblustmthadapter. enable (); while (! Mblustmthadapter. isEnabled () {try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace () ;}} if (mblustmthadapter. isDiscovering () {return true;} return mbluw.thadapter. startDiscovery () ;}// cancel searching for public static boolean cancelDiscovery () {if (mbluw.thadapter = null) {return false;} if (mbluw.thadapter. isDiscovering () {return mbluw.thadapter. cancelDiscovery ();} Return false;} // Add the public static void addOne (effecthdevice device) {if (null = device) {return;} if (devList. contains (device) {return;} devList. add (device) ;}// Delete the public static void deleteOne (String mac) {if (null = mac | mac. length () = 0) {return;} for (int I = 0; I <devList. size (); ++ I) {descrithdevice device = devList. get (I); if (device. getAddress (). equalsIgnoreCase (Mac) {devList. remove (I); break ;}}// clear the public static void clearAllDevices () {devList. clear ();} public static effecthdevice findOne (int pos) {if (pos <0 | pos> = devList. size () {return null;} return devList. get (pos);} public static List <javasthdevice> getDevList () {return devList;} public static boolean isDevListEmpty () {return (null = devList | devList. isEmpty ();} // obtain the result State public static int getState () {if (mbluw.thadapter! = Null) {LogUtils. d ("effecthmgr", "mblustmthadapter. getState () "+ mbluw.thadapter. getState (); return mbluw.thadapter. getState () ;}else {return-1 ;}}}

Analysis: some basic Bluetooth methods are encapsulated and the version is determined. Here we will illustrate some specific code content related to Bluetooth.
(This part of online information is still available. You can also find it)

To use Bluetooth in Android, you must first authorize

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

Otherwise, an exception occurs when your project is run.

To use Bluetooth, you must declareBluetoothAdapter

Before 4.3
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();Obtain the default Bluetooth of the system.

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

List common methods

Disable () disable Bluetooth

Enable () enable Bluetooth (the user will not receive a prompt)

The following is another way to enable Bluetooth, but the user will be reminded to manually enable it.

Intent enabler = new Intent (effecthadapter. ACTION_REQUEST_ENABLE );
StartActivityForResult (enabler, reCode); // same as startActivity (enabler );

CancelDiscovery () cancels searching for devices

StartDiscovery () start searching Devices

GetAddress () Get the local Bluetooth address

GetName () Get the local Bluetooth name

GetRemoteDevice (Stringaddress) obtains the remote Bluetooth device based on the Bluetooth address.

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

IsDiscovering () determines whether the device is currently being searched. true is returned.

IsEnabled () determines whether the Bluetooth is enabled. If enabled, true is returned. Otherwise, false is returned.

Next, list the Bluetooth Status values.
BluetoothAdapter STATE value

Int STATE_OFF Bluetooth has been disabled int STATE_ON Bluetooth has been turned on int STATE_TURNING_OFF Bluetooth is being turned off, turn off ing int STATE_TURNING_ON Bluetooth is being turned on, turn on ing

Descrithadapter SCAN_MOD status value = scan status

It can scan other devices. Of course, it can also be scanned by other Bluetooth devices.

Int SCAN_MODE_CONNECTABLE indicates that this bluetooth device can scan other Bluetooth devices. int SCAN_MODE_CONNECTABLE_DISCOVERABLE can scan other Bluetooth devices and be scanned by other Bluetooth devices. Int SCAN_MODE_NONE: the Bluetooth cannot be scanned or scanned.

For more information, refer to thadapter [Bluetooth].

We started today's code.

Requirements:I have an Activity. When I need to enter the Activity, ask the user to enable the mobile phone Bluetooth and then operate another Bluetooth hardware. If the user does not want to open the Activity, then stay on the original interface. If the user starts Bluetooth and succeeds, go to the next step. If not, continue with the prompt.

Package Structure:

The base classes of the Code are added in our previous Demo, which is more continuous.

Directly paste MainActivity

Public class MainActivity extends BaseActivity implements View. onClickListener {Button button; private MyPromptDlg btNotOpenDlg = null; descrithmgr bleMgr; @ Override protected void findById () {button = (Button) findViewById (R. id. button); bleMgr = descrithmgr. getInstance (this) ;}@ Override protected void setListener () {button. setOnClickListener (this) ;}@ Override protected void logic () {}@ Override Protected int getLayout () {return R. 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 (); openjavasthsetting () ;}@ Override protected void onResume () {super. onResume (); LogUtils. d ("------> onResume"); if (bleMgr. isEnabled () {Toast. makeText (MainActivity. this, "Bluetooth enabled", Toast. LENGTH_SHORT ). show () ;}else {OpenBlueTooth () ;}// enable the Bluetooth private void OpenBlueTooth () {// judge the Activity status if (this. isFinishing () {return;} if (null = btNotOpenDlg ){ MyPromptDlg. builder builder = new MyPromptDlg. builder (this); builder. setTitle (res. getString (R. string. prompt_dlg_title )). setText (res. getString (R. string. bt_check_message )). setPositiveButton (res. getString (R. string. common_ OK), new DialogInterface. onClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {dialog. dismiss (); opendomainthsetting ();}}). setNegativeButton (r Es. getString (R. string. common_cancel), new DialogInterface. onClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {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 opendeskthsetting () {Intent intent = new Intent (Settings. action_effecth_settings); intent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); startActivity (intent );}}

Analysis:
First, we initialize a systthmgr instance in our onCreate method and obtain the system Bluetooth instance (the systthmgr 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 in turn to enter the running status.
We did not judge the user's bluetooth status during onCreate, but in the onResume method. Why? View

Because onResume will be called multiple times, And onCreate will always be called once without being recycled or onStop, we need to judge the Bluetooth status every time the user focus is in our App, that is why we want to do so.

To improve the friendliness of our App, when we determine that the user has not enabled Bluetooth, a Dialog prompt is displayed, prompting the user not to enable Bluetooth,

If you click Cancel, we will return to the interface, but will not call the onResume method. Otherwise, our users will always choose it, which is not in line with the logic.
Click Yes to call the openjavasthsetting () method to manually enable it. Of course, if you think you need to be strong, you can use the enable () method to enable it directly, but remember to wait for a while, some asynchronous operations may occur when Bluetooth is enabled.
Because your code calls to enable Bluetooth, the user will not enable Bluetooth again after returning to the interface, which also meets our business needs.

When the user clicks "OK", the Bluetooth settings menu interface (system) is enabled)

OnResume was called again, and our toast popped up.

OK, our business is complete. Is there any other implementation method? Yes !!

You can use the Service to create a ready-to-use solution where you can determine whether it can achieve the desired results, but it is not the best implementation method.

In addition, BroadcastReceiver monitors the changes of mobile phone Bluetooth. The implementation is as follows:

BroadcastReceiver bluetoothState = new BroadcastReceiver() {    public void onReceive(Context context, Intent intent) {    String stateExtra = BluetoothAdapter.EXTRA_STATE;       int state = intent.getIntExtra(stateExtra, -1);       switch(state) {    case BluetoothAdapter.STATE_TURNING_ON:        break;    case BluetoothAdapter.STATE_ON:        break;    case BluetoothAdapter.STATE_TURNING_OFF:        break;    case BluetoothAdapter.STATE_OFF:        break;    }    }}registerReceiver(bluetoothState,new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

Remember to log out !!

Lunch break !! Source Code address: http://yunpan.cn/cmCaaRkzc2UV6 access password 4894

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.