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 Explicit Intents – An Android Studio Example - Techotopia
    android id id textView1 android layout width wrap content android layout height wrap content android layout alignParentTop true android layout centerHorizontal true android layout marginTop 35dp android text Large Text android textAppearance android attr textAppearanceLarge EditText android id id editText1 android layout width 300dp android layout height wrap content android layout below id textView1 android layout centerHorizontal true android layout marginTop 66dp android ems 10 android inputType text RelativeLayout If designing the layout using the Designer tool in Design mode note that the onClick property on the button view has been configured to call a method named onClick the width of the EditText view has been set to 300dp and the views have been assigned IDs button1 TextView1 and editText1 The completed layout should resemble that illustrated in Figure 32 2 Figure 32 3 Reviewing the Application Manifest File In order for ActivityA to be able to launch ActivityB using an intent it is necessary that an entry for ActivityB be present in the AndroidManifest xml file Locate this file within the Project tool window app manifests double click on it to load it into the editor and verify that Android Studio has automatically added an entry for the activity xml version 1 0 encoding utf 8 manifest xmlns android http schemas android com apk res android package com ebookfrenzy explicitintent application android allowBackup true android icon drawable ic launcher android label string app name android theme style AppTheme activity android name ActivityA android label string app name intent filter action android name android intent action MAIN category android name android intent category LAUNCHER intent filter activity activity android name ActivityB android label string title activity activity b activity application manifest With the second activity created and listed in the manifest file it is now time to write some code in the ActivityA class to issue the intent eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 Creating the Intent The objective for ActivityA is to create and start an intent when the user touches the Ask Question button As part of the intent creation process the question string entered by the user into the EditText view will be added to the intent object as a key value pair When the user interface layout was created for ActivityA the button object was configured to call a method named onClick when clicked by the user This method now needs to be added to the ActivityA class ActivityA java source file as follows package com ebookfrenzy explicitintent import android support v7 app ActionBarActivity import android os Bundle import android view Menu import android view MenuItem import android content Intent import android view View import android widget EditText import android widget TextView public class ActivityA extends ActionBarActivity Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity

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


  • Android Implicit Intents – An Android Studio Example - Techotopia
    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 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 to 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 33 2 Figure 33 2 Double click on the WebView instance and change the ID to id webView1 eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 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 ActionBarActivity import android os Bundle import android view Menu import android view MenuItem import java net URL import android net Uri import android content Intent import android webkit WebView public class MyWebViewActivity extends ActionBarActivity 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

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

  • Broadcast Intents and Broadcast Receivers in Android Studio - Techotopia
    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 a blank activity named SendBroadcastActivity with corresponding layout and menu resource files named activity send broadcast and menu send broadcast respectively 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 ActionBarActivity import android os Bundle import android view Menu import android view MenuItem import android content Intent import android view View public class SendBroadcastActivity extends ActionBarActivity 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 This concludes the creation of the application to send the broadcast intent All that remains is to build a matching broadcast receiver eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 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 Once created Android Studio will automatically load the new MyReceiver java class file into the editor where it should read as follows package com ebookfrenzy broadcastreceiver import android content BroadcastReceiver import android content Context import android content Intent public class MyReceiver extends BroadcastReceiver public MyReceiver Override public void onReceive

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

  • Android Threads and Thread Handlers - An Android Studio Tutorial - Techotopia
    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 ActionBarActivity import android os Bundle import android view Menu import android view MenuItem import android view View import android widget TextView public class ThreadExampleActivity extends ActionBarActivity 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 35 2 report the application as being unresponsive Figure 35 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 fully updated Android 6 Edition of this Android Studio Development Essentials publication 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

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

  • Understanding Android 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 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 required to return an integer value to define what should happen with regard to the service in the event that it is destroyed by the Android runtime system Possible return values for these methods are as follows START NOT STICKY Indicates to

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

  • Implementing an Android Started Service in Android Studio - Techotopia
    have changed this to reflect your company s URL When the changes are complete click on the OK button to create the filter and dismiss the dialog Instead of listing No Filters 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 05 20 09 38 50 953 10961 10996 com ebookfrenzy serviceexample I com example 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 Whilst 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 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 package com ebookfrenzy serviceexample import android app Service import android content Intent import android os IBinder import android util Log public class MyService extends Service public MyService private static final String TAG com ebookfrenzy serviceexample Override public void onCreate Log i TAG Service onCreate Override public int onStartCommand Intent

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

  • Implementing Local Bound Services in Android Studio - Techotopia
    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 TODO Return the communication channel to the service throw new UnsupportedOperationException Not yet implemented public class MyLocalBinder extends Binder BoundService getService return BoundService this Having made the changes to the class it is worth taking a moment to recap the steps performed here Firstly 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 drawable 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 The next phase is to implement the necessary code within the activity to bind to the service and call the getCurrentTime method eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 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 receive the IBinder object returned by the

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

  • Android Remote Bound Services – An Android Studio Tutorial - Techotopia
    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 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 allowBackup true android icon drawable ic launcher android label string app name android theme style AppTheme activity android name RemoteBoundActivity 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

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



  •