archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Android 6 Implicit Intents – A Worked Example - Techotopia
    file containing the user interface description for the activity and double click on it to load it into the Designer tool With the Designer tool in Design mode select the default TextView widget and remove it from the layout using the keyboard delete key Switch Designer to Text mode and edit the XML to remove the padding properties and TextView element so that the file reads as follows xml version 1 0 encoding utf 8 RelativeLayout xmlns android http schemas android com apk res android xmlns tools http schemas android com tools android layout width match parent android layout height match parent tools context MyWebViewActivity RelativeLayout Return the Designer tool to Design mode and drag and drop a WebView object from the Widgets section of the palette onto the existing RelativeLayout view Set the layout height and width properties to match parent using either the Designer toolbar buttons or the Properties panel so that the WebView fills the entire display area as illustrated in Figure 39 2 Figure 39 2 Double click on the WebView instance and change the ID to webView1 Obtaining the Intent URL When the implicit intent object is created to display a web browser window the URL of the web page to be displayed will be bundled into the intent object within a Uri object The task of the onCreate method within the MyWebViewActivity class is to extract this Uri from the intent object convert it into a URL string and assign it to the WebView object To implement this functionality modify the onCreate method in MyWebViewActivity java so that it reads as follows package com ebookfrenzy mywebview import android support v7 app AppCompatActivity import android os Bundle import java net URL import android net Uri import android content Intent import android webkit WebView public class MyWebViewActivity extends AppCompatActivity Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity my web view Intent intent getIntent Uri data intent getData URL url null try url new URL data getScheme data getHost data getPath catch Exception e e printStackTrace WebView webView WebView findViewById R id webView1 webView loadUrl url toString The new code added to the onCreate method performs the following tasks Obtains a reference to the intent which caused this activity to be launched Extracts the Uri data from the intent object Converts the Uri data to a URL object Obtains a reference to the WebView object in the user interface Loads the URL into the web view converting the URL to a String in the process The coding part of the MyWebView project is now complete All that remains is to modify the manifest file Modifying the MyWebView Project Manifest File There are a number of changes that must be made to the MyWebView manifest file before it can be tested In the first instance the activity will need to seek permission to access the internet since it will be required to load a web page This is achieved by adding the appropriate

    Original URL path: http://www.techotopia.com/index.php/Android_6_Implicit_Intents_%E2%80%93_A_Worked_Example (2016-02-13)
    Open archived version from archive


  • Android 6 Broadcast Intents and Broadcast Receivers - Techotopia
    sendBroadcast method there is no way for the initiating activity to receive results from any broadcast receivers that pick up the broadcast In the event that return results are required it is necessary to use the sendOrderedBroadcast method instead When a broadcast intent is sent using this method it is delivered in sequential order to each broadcast receiver with a registered interest The sendOrderedBroadcast method is called with a number of arguments including a reference to another broadcast receiver known as the result receiver which is to be notified when all other broadcast receivers have handled the intent together with a set of data references into which those receivers can place result data When all broadcast receivers have been given the opportunity to handle the broadcast the onReceive method of the result receiver is called and passed the result data Sticky Broadcast Intents By default broadcast intents disappear once they have been sent and handled by any interested broadcast receivers A broadcast intent can however be defined as being sticky A sticky intent and the data contained therein remains present in the system after it has completed The data stored within a sticky broadcast intent can be obtained via the return value of a call to the registerReceiver method using the usual arguments references to the broadcast receiver and intent filter object Many of the Android system broadcasts are sticky a prime example being those broadcasts relating to battery level status A sticky broadcast may be removed at any time via a call to the removeStickyBroadcast method passing through as an argument a reference to the broadcast intent to be removed The Broadcast Intent Example The remainder of this chapter will work through the creation of an Android Studio based example of broadcast intents in action In the first instance a simple application will be created for the purpose of issuing a custom broadcast intent A corresponding broadcast receiver will then be created that will display a message on the display of the Android device when the broadcast is detected Finally the broadcast receiver will be modified to detect notification by the system that external power has been disconnected from the device Creating the Example Application Launch Android Studio and create a new project entering SendBroadcast into the Application name field and ebookfrenzy com as the Company Domain setting before clicking on the Next button On the form factors screen enable the Phone and Tablet option and set the minimum SDK setting to API 8 Android 2 2 Froyo Continue to proceed through the screens requesting the creation of an empty activity named SendBroadcastActivity with a corresponding layout resource file named activity send broadcast Once the new project has been created locate and load the activity send broadcast xml layout file located in the Project tool window under app res layout and with the Designer tool in Design mode replace the TextView object with a Button view Move the button to the center of the display double click on it and set the text property so that it reads Send Broadcast Once the text value has been set use the light bulb menu icon to extract the string to a resource named button text With the button still selected in the layout locate the onClick property in the Properties panel and configure it to call a method named broadcastIntent A useful shortcut for finding properties is to click on the toolbar of the Properties panel and start typing the first few characters of the property name This will trigger the search system and begin selecting the best matches for the property name Creating and Sending the Broadcast Intent Having created the framework for the SendBroadcast application it is now time to implement the code to send the broadcast intent This involves implementing the broadcastIntent method specified previously as the onClick target of the Button view in the user interface Locate and double click on the SendBroadcastActivity java file and modify it to add the code to create and send the broadcast intent Once modified the source code for this class should read as follows package com ebookfrenzy sendbroadcast import android support v7 app AppCompatActivity import android os Bundle import android content Intent import android view View public class SendBroadcastActivity extends AppCompatActivity Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity send broadcast public void broadcastIntent View view Intent intent new Intent intent setAction com ebookfrenzy sendbroadcast intent addFlags Intent FLAG INCLUDE STOPPED PACKAGES sendBroadcast intent Note that in this instance the action string for the intent is com ebookfrenzy sendbroadcast When the broadcast receiver class is created in later sections of this chapter it is essential that the intent filter declaration match this action string eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters This concludes the creation of the application to send the broadcast intent All that remains is to build a matching broadcast receiver Creating the Broadcast Receiver In order to create the broadcast receiver a new class needs to be created which subclasses the BroadcastReceiver superclass Create a new project with the application name set to BroadcastReceiver and the company domain name set to com ebookfrenzy this time selecting the Add No Activity option before clicking on Finish Within the Project tool window navigate to app java and right click on the package name From the resulting menu select the New Other Broadcast Receiver menu option name the class MyReceiver and make sure the Exported and Enabled options are selected These settings allow the Android system to launch the receiver when needed and ensure that the class can receive messages sent by other applications on the device With the class configured click on Finish Once created Android Studio will automatically load the new MyReceiver java class file into the editor

    Original URL path: http://www.techotopia.com/index.php/Android_6_Broadcast_Intents_and_Broadcast_Receivers (2016-02-13)
    Open archived version from archive

  • A Basic Overview of Java Threads and Thread Handlers on Android - Techotopia
    the goal here is to demonstrate the problem of performing lengthy tasks on the main thread the code will simply pause for 20 seconds before displaying different text on the TextView object package com ebookfrenzy threadexample import android support v7 app AppCompatActivity import android os Bundle import android view View import android widget TextView public class ThreadExampleActivity extends AppCompatActivity Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity thread example public void buttonClick View view long endTime System currentTimeMillis 20 1000 while System currentTimeMillis endTime synchronized this try wait endTime System currentTimeMillis catch Exception e TextView myTextView TextView findViewById R id myTextView myTextView setText Button Pressed With the code changes complete run the application on either a physical device or an emulator Once the application is running touch the Button at which point the application will appear to freeze It will for example not be possible to touch the button a second time and in some situations the operating system will as demonstrated in Figure 41 2 report the application as being unresponsive Figure 41 2 Clearly anything that is going to take time to complete within the buttonClick method needs to be performed within a separate thread Creating a New Thread In order to create a new thread the code to be executed in that thread needs to be placed within the Run method of a Runnable instance A new Thread object then needs to be created passing through a reference to the Runnable instance to the constructor Finally the start method of the thread object needs to be called to start the thread running To perform the task within the buttonClick method therefore the following changes need to be made public void buttonClick View view Runnable runnable new Runnable public void run long endTime System currentTimeMillis 20 1000 while System currentTimeMillis endTime synchronized this try wait endTime System currentTimeMillis catch Exception e Thread mythread new Thread runnable mythread start When the application is now run touching the button causes the delay to be performed in a new thread leaving the main thread to continue handling the user interface including responding to additional button presses In fact each time the button is touched a new thread will be created allowing the task to be performed multiple times concurrently A close inspection of the updated code for the buttonClick method will reveal that the code to update the TextView has been removed As previously stated updating a user interface element from within a thread other than the main thread violates a key rule of Android development In order to update the user interface therefore it will be necessary to implement a Handler for the thread eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Implementing a Thread Handler Thread handlers are implemented in

    Original URL path: http://www.techotopia.com/index.php/A_Basic_Overview_of_Java_Threads_and_Thread_Handlers_on_Android (2016-02-13)
    Open archived version from archive

  • An Overview of Android 6 Started and Bound Services - Techotopia
    unbinds from a service the service will be terminated by the Android runtime system It is important to keep in mind that a bound service may also be started via call to startService Once started components may then bind to it via bindService calls When a bound service is launched via a call to startService it will continue to run even after the last client unbinds from it A bound service must include an implementation of the onBind method which is called both when the service is initially created and when other clients subsequently bind to the running service The purpose of this method is to return to binding clients an object of type IBinder containing the information needed by the client to communicate with the service In terms of implementing the communication between a client and a bound service the recommended technique depends on whether the client and service reside in the same or different processes and whether or not the service is private to the client Local communication can be achieved by extending the Binder class and returning an instance from the onBind method Interprocess communication on the other hand requires Messenger and Handler implementation Details of both of these approaches will be covered in later chapters eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters The Anatomy of a Service A service must as has already been mentioned be created as a subclass of the Android Service class more specifically android app Service or a sub class thereof such as android app IntentService As part of the subclassing procedure one or more of the following superclass callback methods must be overridden depending on the exact nature of the service being created onStartCommand This is the method that is called when the service is started by another component via a call to the startService method This method does not need to be implemented for bound services onBind Called when a component binds to the service via a call to the bindService method When implementing a bound service this method must return an IBinder object facilitating communication with the client In the case of started services this method must be implemented to return a NULL value onCreate Intended as a location to perform initialization tasks this method is called immediately before the call to either onStartCommand or the first call to the onBind method onDestroy Called when the service is being destroyed onHandleIntent Applies only to IntentService subclasses This method is called to handle the processing for the service It is executed in a separate thread from the main application Note that the IntentService class includes its own implementations of the onStartCommand and onBind callback methods so these do not need to be implemented in subclasses Controlling Destroyed Service Restart Options The onStartCommand callback method is

    Original URL path: http://www.techotopia.com/index.php/An_Overview_of_Android_6_Started_and_Bound_Services (2016-02-13)
    Open archived version from archive

  • Implementing an Android 6 Started Service – A Worked Example - Techotopia
    the filter ServiceExample and in the by Log Tag field enter the TAG value declared in ServiceExampleActivity java in the above code example this was ServiceExample When the changes are complete click on the OK button to create the filter and dismiss the dialog The newly created filter should now be selected in the Android tool window With the filter configured run the application on a physical device or AVD emulator session and note that the Intent Service Started message appears in the LogCat panel note that it may be necessary to change the filter menu setting back to ServiceExample after the application has launched 11 04 13 02 51 714 18811 18830 I ServiceExample Intent Service started Had the service been tasked with a long term activity the service would have continued to run in the background in a separate thread until the task was completed allowing the application to continue functioning and responding to the user Since all our service did was log a message it will have simply stopped upon completion Using the Service Class While the IntentService class allows a service to be implemented with minimal coding there are situations where the flexibility and synchronous nature of the Service class will be required As will become evident in this section this involves some additional programming work to implement In order to avoid introducing too many concepts at once and as a demonstration of the risks inherent in performing time consuming service tasks in the same thread as the calling application the example service created here will not run the service task within a new thread instead relying on the main thread of the application Creation and management of a new thread within a service will be covered in the next phase of the tutorial Creating the New Service For the purposes of this example a new class will be added to the project that will subclass from the Service class Right click therefore on the package name listed under app java in the Project tool window and select the New Service Service menu option Create a new class named MyService with both the Exported and Enabled options selected eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters The minimal requirement in order to create an operational service is to implement the onStartCommand callback method which will be called when the service is starting up In addition the onBind method must return a null value to indicate to the Android system that this is not a bound service For the purposes of this example the onStartCommand method will loop three times performing a 10 second wait on each loop For the sake of completeness stub versions of the onCreate and onDestroy methods will also be implemented in the new MyService java file as follows

    Original URL path: http://www.techotopia.com/index.php/Implementing_an_Android_6_Started_Service_%E2%80%93_A_Worked_Example (2016-02-13)
    Open archived version from archive

  • Android 6 Local Bound Services – A Worked Example - Techotopia
    the service throw new UnsupportedOperationException Not yet implemented public class MyLocalBinder extends Binder BoundService getService return BoundService this eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Having made the changes to the class it is worth taking a moment to recap the steps performed here First a new subclass of Binder named MyLocalBinder is declared This class contains a single method for the sole purpose of returning a reference to the current instance of the BoundService class A new instance of the MyLocalBinder class is created and assigned to the myBinder IBinder reference since Binder is a subclass of IBinder there is no type mismatch in this assignment Next the onBind method needs to be modified to return a reference to the myBinder object and a new public method implemented to return the current time when called by any clients that bind to the service package com ebookfrenzy localbound import java text SimpleDateFormat import java util Date import java util Locale import android app Service import android content Intent import android os IBinder import android os Binder public class BoundService extends Service private final IBinder myBinder new MyLocalBinder public BoundService Override public IBinder onBind Intent intent return myBinder public String getCurrentTime SimpleDateFormat dateformat new SimpleDateFormat HH mm ss MM dd yyyy Locale US return dateformat format new Date public class MyLocalBinder extends Binder BoundService getService return BoundService this At this point the bound service is complete and is ready to be added to the project manifest file Locate and double click on the AndroidManifest xml file for the LocalBound project in the Project tool window and once loaded into the Manifest Editor verify that Android Studio has already added a service entry for the service as follows xml version 1 0 encoding utf 8 manifest xmlns android http schemas android com apk res android package com ebookfrenzy localbound localbound application android allowBackup true android icon mipmap ic launcher android label string app name android theme style AppTheme activity android name LocalBoundActivity android label string app name intent filter action android name android intent action MAIN category android name android intent category LAUNCHER intent filter activity service android name BoundService android enabled true android exported true service application manifest eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters The next phase is to implement the necessary code within the activity to bind to the service and call the getCurrentTime method Binding the Client to the Service For the purposes of this tutorial the client is the LocalBoundActivity instance of the running application As previously noted in order to successfully bind to a service and

    Original URL path: http://www.techotopia.com/index.php/Android_6_Local_Bound_Services_%E2%80%93_A_Worked_Example (2016-02-13)
    Open archived version from archive

  • Android 6 Remote Bound Services – A Worked Example - Techotopia
    project by right clicking on the package name located under app java within the Project tool window and select the New Service Service menu option Specify RemoteService as the class name and make sure that both the Exported and Enabled options are selected before clicking on Finish to create the class The next step is to implement the handler class for the new service This is achieved by extending the Handler class and implementing the handleMessage method This method will be called when a message is received from the client It will be passed as an argument a Message object containing any data that the client needs to pass to the service In this instance this will be a Bundle object containing a string to be displayed to the user The modified class in the RemoteService java file should read as follows once this has been implemented package com ebookfrenzy remotebound import android app Service import android content Intent import android os IBinder import android os Bundle import android os Handler import android os Message import android widget Toast import android os Messenger public class RemoteService extends Service public RemoteService class IncomingHandler extends Handler Override public void handleMessage Message msg Bundle data msg getData String dataString data getString MyString Toast makeText getApplicationContext dataString Toast LENGTH SHORT show Override public IBinder onBind Intent intent TODO Return the communication channel to the service throw new UnsupportedOperationException Not yet implemented With the handler implemented the only remaining task in terms of the service code is to modify the onBind method such that it returns an IBinder object containing a Messenger object which in turn contains a reference to the handler final Messenger myMessenger new Messenger new IncomingHandler Override public IBinder onBind Intent intent return myMessenger getBinder The first line of the above code fragment creates a new instance of our handler class and passes it through to the constructor of a new Messenger object Within the onBind method the getBinder method of the messenger object is called to return the messenger s IBinder object eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Configuring a Remote Service in the Manifest File In order to portray the communication between a client and remote service accurately it will be necessary to configure the service to run in a separate process from the rest of the application This is achieved by adding an android process property within the service tag for the service in the manifest file In order to launch a remote service it is also necessary to provide an intent filter for the service To implement these changes modify the AndroidManifest xml file to add the required entries xml version 1 0 encoding utf 8 manifest xmlns android http schemas android com apk res android package com ebookfrenzy remotebound application android

    Original URL path: http://www.techotopia.com/index.php/Android_6_Remote_Bound_Services_%E2%80%93_A_Worked_Example (2016-02-13)
    Open archived version from archive

  • An Overview of Android 6 SQLite Databases - Techotopia
    in the SQLite library The developers of SQLite have placed the technology into the public domain with the result that it is now a widely deployed database solution SQLite is written in the C programming language and as such the Android SDK provides a Java based wrapper around the underlying database interface This essentially consists of a set of classes that may be utilized within the Java code of an application to create and manage SQLite based databases For additional information about SQLite refer to http www sqlite org Structured Query Language SQL Data is accessed in SQLite databases using a high level language known as Structured Query Language This is usually abbreviated to SQL and pronounced sequel SQL is a standard language used by most relational database management systems SQLite conforms mostly to the SQL 92 standard SQL is essentially a very simple and easy to use language designed specifically to enable the reading and writing of database data Because SQL contains a small set of keywords it can be learned quickly In addition SQL syntax is more or less identical between most DBMS implementations so having learned SQL for one system it is likely that your skills will transfer to other database management systems While some basic SQL statements will be used within this chapter a detailed overview of SQL is beyond the scope of this book There are however many other resources that provide a far better overview of SQL than we could ever hope to provide in a single chapter here Trying SQLite on an Android Virtual Device AVD For readers unfamiliar with databases in general and SQLite in particular diving right into creating an Android application that uses SQLite may seem a little intimidating Fortunately Android is shipped with SQLite pre installed including an interactive environment for issuing SQL commands from within an adb shell session connected to a running Android AVD emulator instance This is both a useful way to learn about SQLite and SQL and also an invaluable tool for identifying problems with databases created by applications running in an emulator To launch an interactive SQLite session begin by running an AVD session This can be achieved from within Android Studio by launching the Android Virtual Device Manager Tools Android AVD Manager selecting a previously configured AVD and clicking on Start Once the AVD is up and running open a Terminal or Command Prompt window and connect to the emulator using the adb command line tool as follows note that the e flag directs the tool to look for an emulator with which to connect rather than a physical device adb e shell Once connected the shell environment will provide a command prompt at which commands may be entered root android Data stored in SQLite databases are actually stored in database files on the file system of the Android device on which the application is running By default the file system path for these database files is as follows data data package name databases database filename db eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters For example if an application with the package name com example MyDBApp creates a database named mydatabase db the path to the file on the device would read as follows data data com example MyDBApp databases mydatabase db For the purposes of this exercise therefore change directory to data data within the adb shell and create a sub directory hierarchy suitable for some SQLite experimentation cd data data mkdir com example dbexample cd com example dbexample mkdir databases cd databases With a suitable location created for the database file launch the interactive SQLite tool as follows root android data data databases sqlite3 mydatabase db sqlite3 mydatabase db SQLite version 3 7 4 Enter help for instructions Enter SQL statements terminated with a sqlite At the sqlite prompt commands may be entered to perform tasks such as creating tables and inserting and retrieving data For example to create a new table in our database with fields to hold ID name address and phone number fields the following statement is required create table contacts id integer primary key autoincrement name text address text phone text Note that each row in a table must have a primary key that is unique to that row In the above example we have designated the ID field as the primary key declared it as being of type integer and asked SQLite to increment automatically the number each time a row is added This is a common way to make sure that each row has a unique primary key On most other platforms the choice of name for the primary key is arbitrary In the case of Android however it is essential that the key be named id in order for the database to be fully accessible using all of the Android database related classes The remaining fields are each declared as being of type text To list the tables in the currently selected database use the tables statement sqlite tables contacts To insert records into the table sqlite insert into contacts name address phone values Bill Smith 123 Main Street California 123 555 2323 sqlite insert into contacts name address phone values Mike Parks 10 Upping Street Idaho 444 444 1212 To retrieve all rows from a table sqlite select from contacts 1 Bill Smith 123 Main Street California 123 555 2323 2 Mike Parks 10 Upping Street Idaho 444 444 1212 To extract a row that meets specific criteria sqlite select from contacts where name Mike Parks 2 Mike Parks 10 Upping Street Idaho 444 444 1212 To exit from the sqlite3 interactive environment sqlite exit eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38

    Original URL path: http://www.techotopia.com/index.php/An_Overview_of_Android_6_SQLite_Databases (2016-02-13)
    Open archived version from archive



  •