Mobile Applications Grzegorz Budzyń Lecture. 3: Android Applications,, part 2 - PDF

Mobile Applications Grzegorz Budzyń Lecture 3: Android Applications,, part 2 Plan Layouts Drawables Wireless Networking with Android WiFi Bluetooth Layouts Layouts An Android layout is a class that handles

Please download to get full document.

View again

of 73
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.

Recruiting & HR

Publish on:

Views: 13 | Pages: 73

Extension: PDF | Download: 0

Mobile Applications Grzegorz Budzyń Lecture 3: Android Applications,, part 2 Plan Layouts Drawables Wireless Networking with Android WiFi Bluetooth Layouts Layouts An Android layout is a class that handles arranging the way its children appear on the screen Anything that is a View (or inherits from View) can be a child of a layout All of the layouts inherit from ViewGroup (which inherits from View) sothelayoutscan be nested Layouts The standard Layouts are: AbsoluteLayout FrameLayout LinearLayout RelativeLayout TableLayout AbsoluteLayout Basedon the simple idea of placing each control at an absolute position The exact x and y coordinates on the screen for each control are specified Not recommended for most UI development: - absolutely positioning ofevery element on the screen makes an inflexible UI that is verydifficult to maintain AbsoluteLayout The standard Layouts are: AbsoluteLayout FrameLayout LinearLayout RelativeLayout TableLayout FrameLayout Designedto display a single item at a time Therecan bemultiple elements within a FrameLayoutbut each element will be positioned based on the top left of the screen Elements that overlap will be displayed overlapping FrameLayout The standard Layouts are: AbsoluteLayout LinearLayout Organizeselements along a single line Thelinecanbe verticalorhorizontal according to android:orientation parameter LinearLayout The standard Layouts are: AbsoluteLayout FrameLayout LinearLayout RelativeLayout TableLayout RelativeLayout Laysout elements based on their relationships with one another, and with the parent container The most complicated layout-several properties have to be configured: android:layout_alignparentbottom Places the bottom of the element on the bottom of the container android:layout_alignparentleft Places the left of the element on the left side of the container android:layout_alignparentright Places the right of the element on the right side of the container android:layout_alignparenttop Places the element at the top of the container android:layout_centerhorizontal Centers the element horizontally within its parent container RelativeLayout The most complicated layout-several properties haveto be configured: android:layout_above Places the element above the specified element android:layout_below Places the element below the specified element android:layout_toleftof Places the element to the left of the specified element android:layout_torightof Places the element to the right of the specified element android:layout_alignbaseline Aligns baseline of the new element with the baseline of the specified element android:layout_alignbottom Aligns the bottom of new element in with the bottom of the specified element android:layout_alignleft Aligns left edge of the new element with the left edge of the specified element RelativeLa The standard Layouts are: AbsoluteLayout FrameLayout LinearLayout RelativeLayout TableLayout TableLayout Organizescontent into rows and columns The rows are defined in the layout XML, and the columns are determined automatically by Android This is done by creating at least one column for each element An element canoccupy more than one column using android:layout_span By default, Android places each element in the first unused column in the row TableLayout The standard Layouts are: AbsoluteLayout FrameLayout LinearLayout RelativeLayout TableLayout Fragments Fragments A Fragmentsis an independent component which can be connected to an activity. A Fragmenttypically defines a part of a user interface but it is possible to define headless Fragments, i.e. without user interface Fragmentscan be dynamically or statically added to a layout. Fragments A Fragmentencapsulate functionality so that it is easier to reuse within activityand layouts A Fragmentcomponent runs in the context of an activitybut it has its own lifecycle and their own user interface Fragments Whento use: Fragmentsmake it easy to re-use components in different layouts, e.g. asingle-pane layouts for handsets (phones) and multi-pane layouts for tablets can be built Fragments Fragments Fragments method1 Twoactivities, onedisplayingtwo Fragments for tablets and thesecondon handsets devices. In this case the Fragments would be switched in the activity whenever necessary. This requires that the fragment is not declared in the layout file as such Fragments cannot be removed during runtime. Fragments method2 (pref.) Separateactivities to host each fragment on a handsetisused. For example, when the tablet UI uses two Fragments in an activity, the same activity for handsetsshouldbe used, but an alternative layout that includes just one fragment should be supplied. When Fragmentsswitchingisnecessary, another activity that hosts the other fragment shouldbe started. Fragments method2 (cont d) To define a new fragment either the or one of its subclasses should be extended Fragments method2 (cont d) Fragment lifecycle: A fragmentis always connected to an activity If an activitystops, its fragmentsare also stopped; if an activityis destroyed its fragmentsare also destroyed The onstart() method is called once the fragment gets visible Fragments method2 (cont d) Communication of application with Fragments To increase reuse of Fragmentsthey should not directly communicate with each other. Every communication of the Fragmentsshould be done via the host activity AFragment should define an interface as an inner type and require that the activitywhich uses it, must implement this interface Fragments method2 (cont d) Modifying Fragments at runtime: Fragmentscan be dynamically modified via transactions To dynamically add Fragmentsto an existing layout thereshouldbe defineda container in the XML layout file in which a Fragmentisadded Drawables Drawableresources A drawableresource is a general concept for a graphic that can be drawn to the screen The simplest case is a graphical file, which would be represented in Android via a BitmapDrawableclass Bitmaps are typically stored in one of the res/drawable folders In addition to graphical files, Android supports XML drawables XML drawablesare used to describe shapes (color, border, gradient), State and Transitions and more Drawableresources There are several different types of drawables: Bitmap -Android supports bitmap files in a three formats:.png(preferred),.jpg (acceptable),.gif (discouraged) Nine-Patch File-A PNG file with stretchable regions to allow image resizing based on content (.9.png). Drawableresources Types of drawables: Layer List-A Drawablethat manages an array of other Drawables State List-An XML file that references different bitmap graphics for different states (for example, to use a different image when a button is pressed) Transition Drawable-An XML file that defines a drawablethat can cross-fade between two drawable resources Shape Drawable-An XML file that defines a geometric shape, including colors and gradients Bitmapsanddrawables Android allows to use the Bitmap class for working with bitmaps All bitmaps which are stored in the drawable folder can be directly used as a Drawable objects Scaledrawable A drawabledefined in XML that changes the size of another drawablebased on its current level Wireless Networking with Android Managingnetworkconnectivity Android broadcasts Intents that describe the changes in network connectivity 3G, WiFi, etc. There are APIs for controlling network settings and connections Android networking is handled by ConnectivityManager(a network connectivity service) Monitor the state of network connections Configure failover settings Control network radios Managingnetworkconnectivity Accessing connectivity manager String service = Context.CONNECTIVITY_SERVICE; ConnectivityManager connectivity = (ConnectivityManager) getsystemservice(service); App needs read/write access permission on network states uses-permission android:name= android.permission.access_network_state / uses-permission android:name= android.permission.change_network_state / Accessingnetworkstatus // Get the active network information. NetworkInfo activenetwork = connectivity.getactivenetworkinfo(); int networktype = networkinfo.gettype(); switch (networktype) { case (ConnectivityManager.TYPE_MOBILE) : break; case (ConnectivityManager.TYPE_WIFI) : break; default: break; } // Get the mobile network information. int network = ConnectivityManager.TYPE_MOBILE; NetworkInfo mobilenetwork = connectivity.getnetworkinfo(network); NetworkInfo.State state = mobilenetwork.getstate(); NetworkInfo.DetailedState detailedstate = mobilenetwork.getdetailedstate(); Preferrednetworks Preferred network configuration: getnetworkpreference() setnetworkpreference() int networkpreference = connectivity.getnetworkpreference(); connectivity.setnetworkpreference(networkpreference.prefer_wifi); If the preferred connection is unavailable, or connectivity on this network is lost, Android will automatically attempt to connect to the secondary network. Control availability of the network types using the setradio() method. WiFi ManagingWiFi WifiManager: represents the Android WiFi connectivity service Configure WiFi network connections Manage current WiFi connection Scan for access points Monitor changes in WiFi connectivities Monitoring WiFiconnectivity Accessing the WiFi Manager String service = Context.WIFI_SERVICE; WifiManager wifi = (WifiManager) getsystemservice(service); uses-permission android:name= android.permission. ACCESS_WIFI_STATE / uses-permission android:name= android.permission. CHANGE_WIFI_STATE / Monitoring and changing Wifi state State: enabling, enabled, disabling, disabled, and unknown if (!wifi.iswifienabled()) if (wifi.getwifistate()!= WifiManager.WIFI_STATE_ENABLING) wifi.setwifienabled(true); Monitoring WiFiconnectivity WifiManagerbroadcasts Intents whenever connectivity status changes WIFI_STATE_CHANGED_ACTION Wifi h/w status has changed: enabling, enabled, disabling, disabled, and unknown SUPPLICANT_CONNECTION_CHANGED_ACTION: Whenever connection state with the active supplicant (access point) changes Fired when a new connis established, or existing connis lost NEWTWORK_STATE_CHANGED_ACTION: Fired whenever wifi connectivity state changes EXTRA_NETWORK_INFO: NetworkInfo obj for current network status EXTRA_BSSID: BSSID of the access point that you re connected to RSSI_CHANGED_ACTION: Monitor the signal strength of the connected WiFi network Monitoring activeconnectiondetails Once thereisaconnectionto an access point, getconnectioninfoof WifiManagershouldbe usedto find info of that connection Returns WifiInfo object WifiInfo info = wifi.getconnectioninfo(); if (info.getbssid()!= null) { int strength = WifiManager.calculateSignalLevel(info.getRssi(), 5); int speed = info.getlinkspeed(); String units = WifiInfo.LINK_SPEED_UNITS; String ssid = info.getssid(); String csummary = String.format( Connected to %s at %s%s. Strength %s/5 , ssid, speed, units, strength); } Scanninghotspots WifiManagershouldbe usedto scan access points using startscan() Android will broadcast scan results with an Intent of SCAN_RESULTS_AVAILABLE_ACTION Scanninghotspots // Register a broadcast receiver that listens for scan results. registerreceiver(new BroadcastReceiver() public void onreceive(context context, Intent intent) { List ScanResult results = wifi.getscanresults(); ScanResult bestsignal = null; for (ScanResult result : results) { if (bestsignal == null WifiManager.compareSignalLevel(bestSignal.level,result.level) 0) bestsignal = result; } String toasttext = String.format( %s networks found. %s is the strongest. , results.size(), bestsignal.ssid); Toast.makeText(getApplicationContext(), toasttext, Toast.LENGTH_LONG); } }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); // Initiate a scan. wifi.startscan(); Creatinga WiFiconfiguration To connect to a WiFinetwork, a WiFiconfiguration must be created and registered Normally a user does this, but app can do this Network configuration is stored as WifiConfiguration object SSID (service set ID, e.g., IPv4_KAIST) BSSID (MAC addrof an AP) networkid(unique ID that the supplicant uses to identify this network configuration entry) priority (priority of this access point) status (current status: ENABLED, DISABLED, CURRENT) Creatinga WiFiconfiguration WifiManager wifi = (WifiManager) getsystemservice(context.wifi_service); WifiConfiguration wc = new WifiConfiguration(); wc.ssid = \ SSIDName\ ; wc.presharedkey = \ password\ ; // it should be in double quote password wc.hiddenssid = true; wc.status = WifiConfiguration.Status.ENABLED; // setting up WPA-PSK wc.allowedgroupciphers.set(wificonfiguration.groupcipher.tkip); wc.allowedgroupciphers.set(wificonfiguration.groupcipher.ccmp); wc.allowedkeymanagement.set(wificonfiguration.keymgmt.wpa_psk); wc.allowedpairwiseciphers.set(wificonfiguration.pairwisecipher.tkip); wc.allowedpairwiseciphers.set(wificonfiguration.pairwisecipher.ccmp); wc.allowedprotocols.set(wificonfiguration.protocol.rsn); int res = wifi.addnetwork(wc); // the ID of the newly created network description Log.d( WifiPreference , add Network returned + res ); boolean b = wifi.enablenetwork(res, true); Log.d( WifiPreference , enablenetwork returned + b ); ManagingWiFiconfigurations WiFiManager shouldbe usedto manage the configured network settings and control which networks to connect to // Get a list of available configurations List WifiConfiguration configurations = wifi.getconfigurednetworks(); // Get the network ID for the first one. if (configurations.size() 0) { int netid = configurations.get(0).networkid; // Enable that network. boolean disableallothers = true; wifi.enablenetwork(netid, disableallotherstrue); } Power Management Android supports its own Power Management (on top of the standard Linux Power Management) To make sure that CPU shouldn't consume power if no applications or services require power Android requires that applications and services request CPU resources with wake locks through the Android application framework and native Linux libraries. If there are no active wake locks, Android will shut down the CPU. Power Management WakeLock Flag value CPU Screen Keyboard PARTIAL_WAKE_LOCK On Off Off SCREEN_DIM_WAKE_LOCK On Dim Off SCREEN_BRIGHT_WAKE_LOCK On BRIGHT Off FULL_WAKE_LOCK On Bright Bright // Acquire handle to the PowerManager service PowerManager pm = (PowerManager)mContext.getSystemService( Context.POWER_SERVICE); // Create a wake lock and specify the power management flags for screen, timeout, etc. PowerManager.WakeLock wl = pm.newwakelock( PowerManager.SCREEN_DIM_WAKE_LOCK PowerManager.ON_AFTER_RELEASE, TAG); // Acquire wake lock wl.acquire(); //... // Release wake lock wl.release(); Wifibackgrounddata transfer Background data transfer: // WifiManager.WifiLock wifilock = null; Wifilock + Wakelock(partial) PowerManager.WakeLock wakelock = null; // acquire if (wifilock == null) { WifiManager wifimanager = (WifiManager) context.getsystemservice(context.wifi_service); wifilock = wifimanager.createwifilock( wifilock ); wifilock.setreferencecounted(true); wifilock.acquire(); PowerManager powermanager = (PowerManager) context.getsystemservice(context.power_service); wakelock = powermanager.newwakelock(powermanager.partial_wake_lock, wakelock ); wakelock.acquire(); } // release if (wifilock!= null) { wifilock.release(); wifilock = null; wakelock.release(); wakelock = null; } Backgrounddata transfer Setting Accounts & sync settings background data setting If this setting is off, an application cannot transfer data only when it is active and in the foreground Services cannot transfer data (by definition) Connectivitymanagershouldbe usedto check this: booleanbackgroundenabled= connectivity.getbackgrounddatasetting(); Backgrounddata transfer App can listen to changes in the background data transfer preference: registerreceiver( new BroadcastReceiver() public void onreceive(context context, Intent intent) // do something.. }, new IntentFilter(ConnectivityManager. ACTION_BACKGROUND_DATA_SERVICE_CHANGED)); Bluetooth BluetoothAdapter: local Bluetooth device BluetoothDevice: Mainclasses representing each remote device with which we want to communicate with BluetoothSocket: call createrfcommsockettoservicerecord() on a remote Bluetooth Device object to create a Bluetooth socket BluetoothServerSocket: creating a Bluetooth server socket by calling listenusingrfcommwithservicerecord() method Bluetoothpermissions To use Bluetooth features, at least one of two Bluetooth permissions must be declared: BLUETOOTH Requesting/accepting a connection, and data transfer BLUETOOTH_ADMIN More powerful than BLUETOOTH; includes device discovery, manipulating Bluetooth settings (on/off), etc. manifest... uses-permission android:name= android.permission.bluetooth / ... /manifest SettingupBluetooth Bluetooth setup: 1. Get the BluetoothAdapter BluetoothAdapter mbluetoothadapter = BluetoothAdapter.getDefaultAdapter(); if (mbluetoothadapter == null) { // Device does not support Bluetooth } 2. Enable Bluetooth if (!mbluetoothadapter.isenabled()) { Intent enablebtintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startactivityforresult(enablebtintent, REQUEST_ENABLE_BT); protected void onactivityresult(int requestcode, int resultcode, Intent data) { if (requestcode == REQUEST_ENABLE_BT) if (resultcode == RESULT_OK ) // if user pressed YES if (resultcode == RESULT_CANCELED) { // if user pressed NO } SettingupBluetooth App can also listen for ACTION_STATE_CHANGED broadcast intent Android will broadcast whenever the Bluetooth state has changed Broadcast contains the extra fields: EXTRA_STATE: current state EXTRA_PREVIOUS_STATE: previous state State values: STATE_TURNING ON STATE_ON STATE_TURNING_OFF STATE_OFF Enabling discoverability will automatically enable Bluetooth Findingdevices Enabling discoverability New intent with ACTION_REQUEST_DISCOVERABLE Intent discoverableintent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableintent.putextra(bluetoothadapter.extra_discoverable_duration, 300); startactivityforresult(discoverableintent, DISCOVERY_REQUEST); This will show a user permission dialog: Activity will receive the response through onactivityresult() Findingdevices The device will be discoverable for the specified duration (default: 2 minutes) App can be notified of mode changes by registering a BroadcastReceiver for the ACTION_SCAN_MODE_CHANGED Intent EXTRA_SCAN_MODE EXTRA_SCAN_MODE_PREVIOUS Values: SCAN_MODE_CONNECTABLE_DISCOVERABLE (inquiry scan + page scan on), SCAN_MODE_CONNECTABLE (page scan on), SCAN_MODE_NONE (none) App does not need to enable device discoverablity if you will be initiating a connection to a remote node Only necessary when other parties discover an app that hosts a server socket for accepting incoming connections Discovering devices Findingdevices Call startdiscovery() asyncmethod (about 12 second inquiry) BluetoothAdapterbt= BluetoothAdapter.getDefaultAdapter();bt.startDiscovery(); App registers a BroadcastReceiverfor the ACTION_FOUND Intent to receive information about each device discovered It carries the extra fields: EXTRA_DEVICE (BluetoothDevice) and EXTRA_CLASS (BluetoothClass) Call canceldiscovery() to cancel discovery (check first with isdiscovering()) Findingdevices // Create a BroadcastReceiver for ACTION_FOUND private final BroadcastReceiver mreceiver = new BroadcastReceiver() { public void onreceive(context context, Intent intent) { String action = intent.getaction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getparcelableextra(bluetoothdevice.extra_device); // Add the name and address to an array adapter to show in a ListView marrayadapter.add(device.getname() + \n + device.getaddress()); } } }; // Register the BroadcastReceiver IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION
Related Search
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks