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".
  • An Overview of Android Intents - Techotopia
    application containing activities named ActivityA and ActivityB xml version 1 0 encoding utf 8 manifest xmlns android http schemas android com apk res android package com ebookfrenzy Intent1 android versionCode 1 android versionName 1 0 uses sdk android minSdkVersion 10 application android icon drawable ic launcher android label string app name activity android label string app name android name ActivityA 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 ActivityB activity application manifest Returning Data from an Activity As the example in the previous section stands whilst data is transferred to ActivityB there is no way for data to be returned to the first activity which we will call ActivityA This can however be achieved by launching ActivityB as a sub activity of ActivityA An activity is started as a sub activity by starting the intent with a call to the startActivityForResult method instead of using startActivity In addition to the intent object this method is also passed a request code value which can be used to identify the return data when the sub activity returns For example startActivityForResult i REQUEST CODE In order to return data to the parent activity the sub activity must implement the finish method the purpose of which is to create a new intent object containing the data to be returned and then calling the setResult method of the enclosing activity passing through a result code and the intent containing the return data The result code is typically RESULT OK or RESULT CANCELED but may also be a custom value subject to the requirements of the developer In the event that a sub activity crashes the parent activity will receive a RESULT CANCELED result code The following code for example illustrates the code for a typical sub activity finish method public void finish Intent data new Intent data putExtra returnString1 Message to parent activity setResult RESULT OK data super finish In order to obtain and extract the returned data the parent activity must implement the onActivityResult method for example protected void onActivityResult int requestCode int resultCode Intent data String returnString if resultCode RESULT OK requestCode REQUEST CODE if data hasExtra returnString1 returnString data getExtras getString returnString1 Note that the above method checks the returned request code value to make sure that it matches that passed through to the startActivityForResult method When starting multiple sub activities it is especially important to use the request code to track which activity is currently returning results since all will call the same onActivityResult method on exit Implicit Intents Unlike explicit intents which reference the Java class name of the activity to be launched implicit intents identify the activity to be launched by specifying the action to be performed and the type of data to be handled by the receiving activity For example an action type of ACTION VIEW accompanied by the URL of a web page in the form of a URI object

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


  • Android Explicit Intents – A Worked Example - Techotopia
    android layout height wrap content android layout below id editText1 android layout centerHorizontal true android layout marginTop 86dp android onClick onClick android text string answer text TextView 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 112dp 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 160dp android ems 10 android inputType text requestFocus EditText RelativeLayout The completed layout should resemble that illustrated in Figure 26 2 Figure 26 2 Save the file and add the onCreate method to the ActivityB java file to ensure that the layout is loaded at runtime package com example explicitintent import android app Activity import android os Bundle public class ActivityB extends Activity public void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity b Adding ActivityB to the Application Manifest File In order for ActivityA to be able to launch ActivityB using an intent it is necessary to add an entry for ActivityB to the AndroidManifest xml file Locate this file within the Package Explorer panel and double click on it to load it into the Manifest Editor Within the Manifest Editor click on the AndroidManifest xml tab located at the bottom of the editor panel and edit the XML to add the ActivityB entry xml version 1 0 encoding utf 8 manifest xmlns android http schemas android com apk res android package com example explicitintent android versionCode 1 android versionName 1 0 uses sdk android minSdkVersion 19 android targetSdkVersion 19 application android allowBackup true android icon drawable ic launcher android label string app name android theme style AppTheme activity android name com example explicitintent 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 ActivityB activity application manifest With the second activity created and added to the manifest file it is now time to write some code in the ActivityA class to issue the intent 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 example explicitintent import android app Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android view View import android view

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

  • Android Implicit Intents – A Worked Example - Techotopia
    the new MyWebView project is going to consist of an instance of the Android WebView view Within the Package Explorer panel locate the activity my web view xml file containing the user interface description for the activity and double click on it to load it into the Graphical Layout tool Click on the activity my web view xml tab located on the bottom edge of the layout tool panel to display the XML view of the layout Edit the XML so that it 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 Graphical Layout view and drag and drop a WebView object from the Composite section of the palette onto the existing RelativeLayout view By default the new WebView object should automatically fill the entire display area as illustrated in Figure 30 2 Figure 30 2 Be sure to save the user interface design before proceeding 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 an 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 which since we did not provide a specific name will have a default ID of webView1 To implement this functionality modify the onCreate method in MyWebViewActivity java so that it reads as follows package com example mywebview import android app Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android view View import android view ViewGroup import android os Build import java net URL import android net Uri import android content Intent import android webkit WebView public class MyWebViewActivity extends Activity 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 Override public boolean onCreateOptionsMenu Menu menu getMenuInflater inflate R menu activity my web view menu return true 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

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

  • Android Broadcast Intents and Broadcast Receivers - Techotopia
    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 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 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 anytime 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 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 device when the broadcast is detected Finally the broadcast receiver will be modified to detect the system notification of external power being disconnected from the device Creating the Example Application The first step in this exercise is to create an application the purpose of which is to send a custom broadcast intent Within the Eclipse environment create a new Android Application project Name the project SendBroadcast with the appropriate package name and SDK selections Request the creation of a blank activity and the use of the default launcher icons On the New Blank Activity screen of the New Android Application wizard set the Activity Name to SendBroadcastActivity and the Layout and Fragment to activity send broadcast and fragment send broadcast respectively Click Finish to create the new project Once the new project has been created locate and load the fragment send broadcast xml layout file and either in the Graphical Layout tool or XML editor replace the TextView object with a Button view Move the button to the center of the display and change the text so that it reads Send Broadcast Right click on the button in the Graphical Layout tool and select the Other Properties All by Name onClick menu option and enter the method name broadcastIntent into the resulting dialog 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 example sendbroadcast import android app Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android view View import android view ViewGroup import android os Build import android content Intent public class SendBroadcastActivity extends Activity public void broadcastIntent View view Intent intent new Intent intent setAction com example SendBroadcast intent addFlags Intent FLAG INCLUDE STOPPED PACKAGES sendBroadcast intent Note that in this instance the action string for the intent is com example 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 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 named BroadcastReceiver with an appropriate package name this time switching off the Create Activity option in the Configure Project screen Add a new class to the project by right clicking on the BroadcastReceiver project name in the Package Explorer panel and selecting the New Class menu option In the Package field name the package com example broadcastreceiver Name the class MyReceiver and enter or select android content BroadcastReceiver as the superclass and click on Finish to create the new class Navigate to the new MyReceiver java file and double click on it to load it into an editing panel where it should read as follows package com example broadcastreceiver import android content BroadcastReceiver import android content Context import android content Intent public class MyReceiver extends BroadcastReceiver Override public void onReceive Context arg0 Intent arg1 TODO Auto generated method stub As can be seen in the code Eclipse has already auto generated for us the onReceive method which will be called when a matching broadcast intent is detected This needs to be modified to display a message to the user using the Toast class The

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

  • A Basic Overview of Android Threads and Thread handlers - Techotopia
    Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android view View import android view ViewGroup import android os Build public class ThreadExample extends Activity 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 29 2 report the application as being unresponsive Figure 29 2 Clearly anything that is going to take time to complete within the buttonClick method needs to be performed within a separate 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 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 Implementing a Thread Handler Thread handlers are implemented in the main thread of an application and are primarily used to make updates to the user interface in response to messages sent by another thread running within the application s process Handlers

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

  • An Overview of 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 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 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_Started_and_Bound_Services (2016-02-13)
    Open archived version from archive

  • Implementing an Android Started Service – A Worked Example - Techotopia
    LogCat panel displayed click on the green located to the right of the Save Filters title to display the filter settings dialog Name the filter ServiceExample and in the by Log Tag field enter the Tag value declared in MyIntentService java in the above code example this was com example ServiceExample Select the newly created filter from the list and then run the application Once the application is running the Service started message should appear within the LogCat panel 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 ServiceExample project in the Package Explorer panel and select the New Class menu option Create a new class named MyService subclassed from android app Service and allocated to the appropriate application package Within the Package Explorer window navigate to and load the new MyService java file which should read as follows package com example serviceexample import android app Service import android content Intent import android os IBinder public class MyService extends Service Override public IBinder onBind Intent arg0 TODO Auto generated method stub return null As the source file currently stands only a stub callback method has been implemented by Eclipse Since this is not a bound service the stub correctly returns a null value 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 For the purposes of this example this 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 package com example serviceexample import android app Service import android content Intent import android os IBinder import android util Log public class MyService extends Service private static final String TAG com

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

  • Android Local Bound Services – A Worked Example - Techotopia
    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 example localbound import java text SimpleDateFormat import java util Date import java util Locale import android app Service import android content Intent import android os Binder import android os IBinder public class BoundService extends Service private final IBinder myBinder new MyLocalBinder Override public IBinder onBind Intent arg0 TODO Auto generated method stub 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 LocalService project in the Package Explorer panel and once loaded into the Manifest Editor click on the file name tab at the bottom of the editor panel to display the XML Within the application element add 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 example localbound android versionCode 1 android versionName 1 0 uses sdk android minSdkVersion 19 android targetSdkVersion 19 application android allowBackup true android icon drawable ic launcher android label string app name android theme style AppTheme activity android name com example localbound LocalBound 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 application manifest 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 receive the IBinder object returned by the service s onBind method it is necessary to create a ServiceConnection subclass and implement onServiceConnected and onServiceDisconnected callback methods With these requirements in mind edit the LocalBoundActivity java file and modify it as follows 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 package com example localbound import android app Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android

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



  •