Android – Custom Fonts

Android – Custom Fonts ”; Previous Next In android, you can define your own custom fonts for the strings in your application. You just need to download the required font from the internet, and then place it in assets/fonts folder. After putting fonts in the assets folder under fonts folder, you can access it in your java code through Typeface class. First , get the reference of the text view in the code. Its syntax is given below − TextView tx = (TextView)findViewById(R.id.textview1); The next thing you need to do is to call static method of Typeface class createFromAsset() to get your custom font from assets. Its syntax is given below − Typeface custom_font = Typeface.createFromAsset(getAssets(), “fonts/font name.ttf”); The last thing you need to do is to set this custom font object to your TextView Typeface property. You need to call setTypeface() method to do that. Its syntax is given below − tx.setTypeface(custom_font); Apart from these Methods, there are other methods defined in the Typeface class , that you can use to handle Fonts more effectively. Sr.No Method & description 1 create(String familyName, int style) Create a Typeface object given a family name, and option style information 2 create(Typeface family, int style) Create a Typeface object that best matches the specified existing Typeface and the specified Style 3 createFromFile(String path) Create a new Typeface from the specified font file 4 defaultFromStyle(int style) Returns one of the default Typeface objects, based on the specified style 5 getStyle() Returns the Typeface”s intrinsic style attributes Example Here is an example demonstrating the use of Typeface to handle CustomFont. It creates a basic application that displays a custom font that you specified in the fonts file. To experiment with this example, you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Download a font from internet and put it under assets/fonts folder. 3 Modify src/MainActivity.java file to add necessary code. 4 Modify the res/layout/activity_main to add respective XML components 5 Run the application and choose a running android device and install the application on it and verify the results Before entering to code part add fonts in assests folder from windows explorer. Following is the content of the modified main activity file MainActivity.java. package com.example.sairamkrishna.myapplication; import android.graphics.Typeface; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends ActionBarActivity { TextView tv1,tv2; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv1=(TextView)findViewById(R.id.textView3); tv2=(TextView)findViewById(R.id.textView4); Typeface face= Typeface.createFromAsset(getAssets(), “font/font.ttf”); tv1.setTypeface(face); Typeface face1= Typeface.createFromAsset(getAssets(), “font/font1.ttf”); tv2.setTypeface(face1); } } Following is the modified content of the xml activity_main.xml. <?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” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Typeface” android:id=”@+id/textView” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:textSize=”30dp” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials Point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:textSize=”35dp” android:textColor=”#ff16ff01″ /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials Point” android:id=”@+id/textView3″ android:layout_centerVertical=”true” android:textSize=”45dp” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials Point” android:id=”@+id/textView4″ android:layout_below=”@+id/textView3″ android:layout_alignLeft=”@+id/textView3″ android:layout_alignStart=”@+id/textView3″ android:layout_marginTop=”73dp” android:textSize=”45dp” /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name=”app_name”>My Application</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run our Custom Font application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar.Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − As you can see that the text that appeared on the AVD has not a default android font, rather it has the custom font that you specified in the fonts folder. Note − You need to take care of the size and the character supported by the font , when using custom fonts. Print Page Previous Next Advertisements ”;

Android – Developer Tools

Android – Developer Tools ”; Previous Next The android developer tools let you create interactive and powerful application for android platform. The tools can be generally categorized into two types. SDK tools Platform tools SDK tools SDK tools are generally platform independent and are required no matter which android platform you are working on. When you install the Android SDK into your system, these tools get automatically installed. The list of SDK tools has been given below − Sr.No Tool & description 1 android This tool lets you manage AVDs, projects, and the installed components of the SDK 2 ddms This tool lets you debug Android applications 3 Draw 9-Patch This tool allows you to easily create a NinePatch graphic using a WYSIWYG editor 4 emulator This tools let you test your applications without using a physical device 5 mksdcard Helps you create a disk image (external sdcard storage) that you can use with the emulator 6 proguard Shrinks, optimizes, and obfuscates your code by removing unused code 7 sqlite3 Lets you access the SQLite data files created and used by Android applications 8 traceview Provides a graphical viewer for execution logs saved by your application 9 Adb Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device. We will discuss three important tools here that are android,ddms and sqlite3. Android Android is a development tool that lets you perform these tasks: Manage Android Virtual Devices (AVD) Create and update Android projects Update your sdk with new platform add-ons and documentation android [global options] action [action options] DDMS DDMS stands for Dalvik debug monitor server, that provide many services on the device. The service could include message formation, call spoofing, capturing screenshot, exploring internal threads and file systems e.t.c Running DDMS From Android studio click on Tools>Android>Android device Monitor. How it works In android, each application runs in its own process and each process run in the virtual machine. Each VM exposes a unique port, that a debugger can attach to. When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between adb and DDMS, which notifies DDMS when a VM on the device is started or terminated. Making SMS Making sms to emulator.we need to call telnet client and server as shown below Now click on send button, and you will see an sms notification in the emulator window. It is shown below − Making Call In the DDMS, select the Emulator Control tab. In the emulator control tab , click on voice and then start typing the incoming number. It is shown in the picture below − Now click on the call button to make a call to your emulator. It is shown below − Now click on hangup in the Android studio window to terminate the call. The fake sms and call can be viewed from the notification by just dragging the notification window to the center using mouse. It is shown below − Capturing ScreenShot You can also capture screenshot of your emulator. For this look for the camera icon on the right side under Devices tab. Just point your mouse over it and select it. As soon as you select it , it will start the screen capturing process and will capture whatever screen of the emulator currently active. It is shown below − The eclipse orientation can be changed using Ctrl + F11 key. Now you can save the image or rotate it and then select done to exit the screen capture dialog. Sqlite3 Sqlite3 is a command line program which is used to manage the SQLite databases created by Android applications. The tool also allow us to execute the SQL statements on the fly. There are two way through which you can use SQlite , either from remote shell or you can use locally. Use Sqlite3 from a remote shell. Enter a remote shell by entering the following command − adb [-d|-e|-s {<serialNumber>}] shell From a remote shell, start the sqlite3 tool by entering the following command − sqlite3 Once you invoke sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, enter exit or press CTRL+D. Using Sqlite3 directly Copy a database file from your device to your host machine. adb pull <database-file-on-device> Start the sqlite3 tool from the /tools directory, specifying the database file − sqlite3 <database-file-on-host> Platform tools The platform tools are customized to support the features of the latest android platform. The platform tools are typically updated every time you install a new SDK platform. Each update of the platform tools is backward compatible with older platforms. Some of the platform tools are listd below − Android Debug bridge (ADB) Android Interface definition language (AIDL) aapt, dexdump , and dex e.t.c Print Page Previous Next Advertisements ”;

Android – SIP Protocol

Android – SIP Protocol ”; Previous Next SIP stands for (Session Initiation Protocol). It is a protocol that let applications easily set up outgoing and incoming voice calls, without having to manage sessions, transport-level communication, or audio record or playback directly. Applications Some of the common applications of SIP are. Video conferencing Instant messaging Requirements Here are the requirements for developing a SIP application − Android OS must be 2.3 or higher You must have a data connection or WIFI You must have an SIP account in order to use this service. SIP Classes Here is a summary of the classes that are included in the Android SIP API: Sr.No Class & description 1 SipAudioCall Handles an Internet audio call over SIP 2 SipErrorCode Defines error codes returned during SIP actions 3 SipManager Provides APIs for SIP tasks, such as initiating SIP connections, and provides access to related SIP services 4 SipProfile Defines a SIP profile, including a SIP account, domain and server information 5 SipSession Represents a SIP session that is associated with a SIP dialog or a standalone transaction not within a dialog Functions of SIP SIP has following major functions. SIP allows for the establishment of user location SIP provides a mechanism for call management SIP provides feature negotiation, so that all the parties in the call can agree to the features supported among them Components of SIP SIP has two major components which are listed below. User Agent Client (UAC) User Agent Server (UAS) UAC UAC or User Agent Client are those end users who generates requests and send those requests to the server.These requests are generated by the client applications running on their systems. UAS UAS or User Agent Server are those systems which get the request generated by UAC. The UAS process those requests and then according to the requests it generates responses accordingly. SipManager SipManager is an android API for SIP tasks, such as initiating SIP connections, and provides access to related SIP services. This class is the starting point for any SIP actions. You can acquire an instance of it with newInstance(). The SipManager has many functions for managing SIP tasks. Some of the functions are listed below. Sr.No Class & description 1 close(String localProfileUri) Closes the specified profile to not make/receive calls 2 getCallId(Intent incomingCallIntent) Gets the call ID from the specified incoming call broadcast intent 3 isOpened(String localProfileUri) Checks if the specified profile is opened in the SIP service for making and/or receiving calls 4 isSipWifiOnly(Context context) Returns true if SIP is only available on WIFI 5 isRegistered(String localProfileUri) Checks if the SIP service has successfully registered the profile to the SIP provider (specified in the profile) for receiving calls 6 isVoipSupported(Context context) Returns true if the system supports SIP-based VOIP API 7 takeAudioCall(Intent incomingCallIntent, SipAudioCall.Listener listener) Creates a SipAudioCall to take an incoming call 8 unregister(SipProfile localProfile, SipRegistrationListener listener) Manually unregisters the profile from the corresponding SIP provider for stop receiving further calls Print Page Previous Next Advertisements ”;

Android – UI Patterns

Android – UI Patterns ”; Previous Next In this chapter we will look at the different UI Patterns which are available by android to design apps that behave in a consistent and foreseeable way. UI Patterns components A good android application should follow following UI patterns − Action Bar Confirming and Acknowledging Settings Help Selection Now we will discuss the above mentioned UI Patterns in detail. Action Bar The action bar is a dedicated bar at the top of each screen that is generally persistent throughout the app. It provides you several key function which are as following − Makes important actions prominent and accessible Supports consistent navigation and view switching within apps Reduces clutter by providing an action overflow for rarely used actions Provides a dedicated space for giving your app an identity Action Bar Components Action Bar has four major components which can be seen in the following image. These components name and functionality is discussed below − Sr.No Action Bar Components 1 App Icon The app icon establishes your app”s identity. It can be replaced with a different logo or branding if you wish. 2 View control If your app displays data in different views, this segment of the action bar allows users to switch views. 3 Action buttons Show the most important actions of your app in the actions section. 4 Action overflow Move less often used actions to the action overflow. Confirming and Acknowledging When a user invokes a action on your app”s UI, it is a good practice to confirm or acknowledge that action through a toast or a dialog box. There is a difference between Confirming and Acknowledging. Confirming When we ask the user to verify that they truly want to proceed with a action that they just invoked, it is called confirming. As you can see in the following image − Acknowledging When we display a toast to let the user know that the action they just invoked has been completed, this is called acknowledging, As you can see in the following image − Settings The place in your app where users can indicate their preferences for how your app should behave is called as Settings. The use of settings can benefit your app”s users in the following ways − Settings help user to predetermine that what will happen in certain situations Use of settings in your app help users to feel in control Placement of Settings It is preferred by the android developers to always make “settings” option part of action overflow which is mentioned above. As users did not frequently use this option so the common practice is to place it below all other items except “Help”. As you can see in the following picture − Help Some of your app users may run into some difficulty while using your app and they will be looking for some answers, and they want them within the app. So always make “help” part of your app. Placement of Help Like “Settings” the standard design of placing “Help” option is in action overflow. Always make it very last item in the menu and always label it “Help”. Even if your app screen has no other action overflow items, “Help” should appear there. As you can see this in the following picture − Selection Android 3.0 version changed the long press gesture to the global gesture to select data. The long press gesture is now used to select data, combining contextual actions and selection management functions for selected data into a new element called the contextual action bar (CAB). Using Contextual Action Bar (CAB) The selection CAB is a temporary action bar that overlays your app”s current action bar while data is selected. It appears after the user long presses on a selectable data item. As you can see in the following picture − From the CAB bar user can perform following actions − Select additional data items by touching them Trigger an action from the CAB that applies to all highlighted data items Dismiss the CAB via the navigation bar”s Back button or the CAB”s checkmark button Print Page Previous Next Advertisements ”;

Android – NFC Guide

Android – NFC Guide ”; Previous Next NFC stands for Near Field Communication, and as the name implies it provides a wireless communication mechanism between two compatible devices. NFC is a short range wireless technology having a range of 4cm or less for two devices to share data. How It Works Like Bluetooth and WiFi, and all manner of other wireless signals, NFC works on the principle of sending information over radio waves. Through NFC data is send through electromagnetic induction between two devices. NFC works on the bases of tags , it allows you to share some amount of data between an NFC tag and an android powered device or between two android powered devices. Tags have various set of complexities. The Data stored in the tag can be written in a variety of formats, but android APIs are based around a NFC standard called as NFC Data Exchange Format(NDEF).. The transmission frequency for data across NFC is 13.56 megahertz, and data can be sent at either 106, 212 or 424 kilobits per second, which is quick enough for a range of data transfers from contact details to swapping pictures, songs and videos. Android powered devices with NFC supports following three main modes of operations − Three Modes of Operation Reader/Writer Mode − It allows the NFC device to read or write passive NFC tags. P2P mode − This mode allows NFC device to exchange data with other NFC peers. Card emulation mode − It allows the NFC device itself to act as an NFC card, so it can be accessed by an external NFC reader. How it works with Android To get the permission to access NFC Hardware, add the following permission in your Android.Manifest file. <uses-sdk android:minSdkVersion=”10″/> First thing to note is that not all android powered devices provide NFC technology. So to make sure that your application shows up in google play for only those devices that have NFC Hardware, add the following line in your Android.Manifest file. <uses-feature android:name=”android.hardware.nfc” android:required=”true”/> Android provides a android.nfc package for communicating with another device. This package contains following classes − Sr.No Classes & Description 1 NdefMessage It represents an immutable NDEF Message. 2 NdefRecord It represents an immutable NDEF Record. 3 NfcAdapter It represents the local NFC adapter. 4 NfcEvent It wraps information associated with any NFC event. 5 NfcManager It is a high level manager used to obtain an instance of an NfcAdapter. 6 Tag It represents an NFC tag that has been discovered. NFC tags system works in android with the help of some intent filters that are listed below: Sr.No Filters & Features 1 ACTION_NDEF_DISCOVERED This intent is used to start an Activity when a tag contains an NDEF payload. 2 ACTION_TECH_DISCOVERED This intent is used to start an activity if the tag does not contain NDEF data, but is of known technology. 3 ACTION_TAG_DISCOVERED This intent is started if no activities handle the ACTION_NDEF_DISCOVERED or ACTION_TECH_DISCOVERED intents. To code an application that uses NFC technology is complex so don”t use it in your app unless necessary. The use of NFC is not common in devices but it is getting popular. Let”s see what is the future of this technology − Future Applications With this technology growing day by day and due to introduction of contact less payment systems this technology is getting a boom. A service known as Google Wallet is already introduced in the US which purpose is to make our smartphones a viable alternative to credit and transport cards. Print Page Previous Next Advertisements ”;

Android – Data Backup

Android – Data Backup ”; Previous Next Android allows you to backup your application data to remote “cloud” storage, in order to provide a restore point for the application data and settings. You can only backup your application data. In order to access the other applications data, you need to root your phone. In order to make a data backup application, you need to register your application with google backup service. This has been explained in the example. After registering , you have to specify its key in the AndroidManifest.XML <application android:allowBackup=”true” android:backupAgent=”MyBackupPlace”> <meta-data android:name=”com.google.android.backup.api_key” android:value=”AEdPqrEAAAAIErlxFByGgNz2ywBeQb6TsmLpp5Ksh1PW-ZSexg” /> </application> Android provides BackUpAgentHelper class to handle all the operations of data backup. In order to use this class , you have to extend your class with it. Its syntax is given below − public class MyBackUpPlace extends BackupAgentHelper { } The persistent data that you want to backup is in either of the two forms. Either it could be SharedPrefrences or it could be File. Android supports both types of backup in the respective classes of SharedPreferencesBackupHelper and FileBackupHelper. In order to use SharedPerefernceBackupHelper, you need to instantiate its object with the name of your sharedPerefernces File. Its syntax is given below − static final String File_Name_Of_Prefrences = “myPrefrences”; SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, File_Name_Of_Prefrences); The last thing you need to do is to call addHelper method by specifying the backup key string , and the helper object. Its syntax is given below − addHelper(PREFS_BACKUP_KEY, helper); The addHelper method will automatically add a helper to a given data subset to the agent”s configuration. Apart from these methods, there are other methods defined in the BackupAgentHelper class. They are defined below − Sr.No Method & description 1 onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) Run the backup process on each of the configured handlers 2 onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) Run the restore process on each of the configured handlers The methods of the SharedPreferencesBackUpHelper class are listed below. Sr.No Method & description 1 performBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) Backs up the configured SharedPreferences groups 2 restoreEntity(BackupDataInputStream data) Restores one entity from the restore data stream to its proper shared preferences file store Example The following example demonstrates the use of BackupAgentHelper class to create backup of your application data. To experiment with this example, you need to run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application and name it as Backup under a package com.example.backup. 2 Register your application with Google backup service. 3 Modify the AndroidManifest to add respective necessary key and other components 4 Create backup agent class with the name you specify at AndroidManifest.XML 5 Run the application and verify the results Register you android application with google backup service. In order to do that , visit this link. You must agree to the terms of service, and then enter the application package name. It is shown below − Then click on Register with android backup service. It would give you your key, along with your AndroidManifest code to copy. Just copy the key. It is shown below − Once you copy the key , you need to write it in your AndroidManifest.XML file. Its code is given below − <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.backup” > <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:backupAgent=”MyBackUpPlace” android:theme=”@style/AppTheme” > <activity android:name=”com.example.backup.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> <meta-data android:name=”com.google.android.backup.api_key” android:value=”AEdPqrEAAAAIErlxFByGgNz2ywBeQb6TsmLpp5Ksh1PW-ZSexg” /> </application> </manifest> Here is the code of BackUpAgentHelper class. The name of the class should be the same as you specified in the backupAgent tag under application in AndroidManifest.XML package com.example.backup; import android.app.backup.BackupAgentHelper; import android.app.backup.SharedPreferencesBackupHelper; public class MyBackUpPlace extends BackupAgentHelper { static final String File_Name_Of_Prefrences = “myPrefrences”; static final String PREFS_BACKUP_KEY = “backup”; @Override public void onCreate() { SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, File_Name_Of_Prefrences); addHelper(PREFS_BACKUP_KEY, helper); } } Test your BackupAgent Once you”ve implemented your backup agent, you can test the backup and restore functionality with the following procedure, using bmgr. Install your application on a suitable Android system image. If using the emulator, create and use an AVD with Android 2.2 (API Level 8). If using a device, the device must be running Android 2.2 or greater and have Google Play built in. Ensure data backup is enabled If using the emulator, you can enable backup with the following command from your SDK tools/ path − adb shell bmgr enable true If using a device, open the system Settings, select Privacy, then enable Back up my data and Automatic restore. Performing backup For testing purposes, you can also make a request with the following bmgr command − adb shell bmgr backup your.package.name Initiate a backup operation by typing the following command. adb shell bmgr run This forces the Backup Manager to perform all backup requests that are in its queue. Uninstall and reinstall your application Uninstall the application with the following command − adb uninstall your.package.name Then reinstall the application and verify the results. Print Page Previous Next Advertisements ”;

Android – Facebook Integration

Android – Facebook Integration ”; Previous Next Android allows your application to connect to facebook and share data or any kind of updates on facebook. This chapter is about integrating facebook into your application. There are two ways through which you can integrate facebook and share something from your application. These ways are listed below − Facebook SDK Intent Share Integrating Facebook SDK This is the first way of connecting with facebook. You have to register your application and then receive some Application Id , and then you have to download the facebook SDK and add it to your project. The steps are listed below: Generating application signature You have to generate a key signature, but before you generate it, make sure you have SSL installed, otherwise you have to download SSl. It can be downloaded here. Now open command prompt and redirect to your java jre folder. Once you reach there, type this command exactly. You have to replace the path in the inverted commas with your keystore path which you can found in eclipse by selecting the window tab and selecting the preferences tab and then selecting the build option under android from left side. keytool -exportcert -alias androiddebugkey -keystore “your path” | openssl sha1 -binary | openssl base64 Once you enter it, you will be prompt for password. Give android as the password and then copy the key that is given to you. It is shown in the image below − Registering your application Now create a new facebook application at developers.facebook.com/apps and fill all the information. It is shown below − Now move to the native android app section and fill in your project and class name and paste the hash that you copied in step 1. It is shown below − If everything works fine, you will receive an application ID with the secret. Just copy the application id and save it somewhere. It is shown in the image below − Downloading SDK and integrating it Download facebook sdk here. Import this into eclipse. Once imported, right click on your facebook project and click on properties.Click on android, click on add button and select facebook sdk as the project.Click ok. Creating facebook login application Once everything is complete , you can run the samples, that comes with SDK or create your own application. In order to login, you need to call openActiveSession method and implements its callback. Its syntax is given below − // start Facebook Login Session.openActiveSession(this, true, new Session.StatusCallback() { // callback when session changes state public void call(Session session, SessionState state, Exception exception) { if (session.isOpened()) { // make request to;2 the /me API Request.executeMeRequestAsync(session, new Request.GraphUserCallback() { // callback after Graph API response with user object @Override public void onCompleted(GraphUser user, Response response) { if (user != null) { TextView welcome = (TextView) findViewById(R.id.welcome); welcome.setText(“Hello ” + user.getName() + “!”); } } }); } } } Intent share Intent share is used to share data between applications. In this strategy, we will not handle the SDK stuff, but let the facebook application handles it. We will simply call the facebook application and pass the data to share. This way, we can share something on facebook. Android provides intent library to share data between activities and applications. In order to use it as share intent , we have to specify the type of the share intent to ACTION_SEND. Its syntax is given below − Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); Next thing you need to is to define the type of data to pass , and then pass the data. Its syntax is given below − shareIntent.setType(“text/plain”); shareIntent.putExtra(Intent.EXTRA_TEXT, “Hello, from tutorialspoint”); startActivity(Intent.createChooser(shareIntent, “Share your thoughts”)); Apart from the these methods, there are other methods available that allows intent handling. They are listed below − Sr.No Method & description 1 addCategory(String category) This method add a new category to the intent. 2 createChooser(Intent target, CharSequence title) Convenience function for creating a ACTION_CHOOSER Intent 3 getAction() This method retrieve the general action to be performed, such as ACTION_VIEW 4 getCategories() This method return the set of all categories in the intent and the current scaling event 5 putExtra(String name, int value) This method add extended data to the intent. 6 toString() This method returns a string containing a concise, human-readable description of this object Example Here is an example demonstrating the use of IntentShare to share data on facebook. It creates a basic application that allows you to share some text on facebook. To experiment with this example, you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components. 4 Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified main activity file MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.FileNotFoundException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { private ImageView img; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img=(ImageView)findViewById(R.id.imageView); Button b1=(Button)findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); Uri screenshotUri = Uri.parse(“android. resource://comexample.sairamkrishna.myapplication/*”); try { InputStream stream = getContentResolver().openInputStream(screenshotUri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } sharingIntent.setType(“image/jpeg”); sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri); startActivity(Intent.createChooser(sharingIntent, “Share image using”)); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. In the below code abc indicates the logo of tutorialspoint.com <?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” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textView” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:textSize=”30dp” android:text=”Facebook share ” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials Point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:textSize=”35dp” android:textColor=”#ff16ff01″ /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:layout_below=”@+id/textView2″ android:layout_centerHorizontal=”true” android:src=”@drawable/abc”/> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Share” android:id=”@+id/button” android:layout_marginTop=”61dp” android:layout_below=”@+id/imageView” android:layout_centerHorizontal=”true” /> </RelativeLayout> Following is the content of AndroidManifest.xml file.

Android – Discussion

Discuss Android ”; Previous Next Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. This tutorial will teach you basic Android programming and will also take you through some advance concepts related to Android application development. Print Page Previous Next Advertisements ”;

Android – Network Connection

Android – Network Connection ”; Previous Next Android lets your application connect to the internet or any other local network and allows you to perform network operations. A device can have various types of network connections. This chapter focuses on using either a Wi-Fi or a mobile network connection. Checking Network Connection Before you perform any network operations, you must first check that are you connected to that network or internet e.t.c. For this android provides ConnectivityManager class. You need to instantiate an object of this class by calling getSystemService() method. Its syntax is given below − ConnectivityManager check = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE); Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo method to get the information of all the networks. This method returns an array of NetworkInfo. So you have to receive it like this. NetworkInfo[] info = check.getAllNetworkInfo(); The last thing you need to do is to check Connected State of the network. Its syntax is given below − for (int i = 0; i<info.length; i++){ if (info[i].getState() == NetworkInfo.State.CONNECTED){ Toast.makeText(context, “Internet is connected Toast.LENGTH_SHORT).show(); } } Apart from this connected states, there are other states a network can achieve. They are listed below − Sr.No State 1 Connecting 2 Disconnected 3 Disconnecting 4 Suspended 5 Unknown Performing Network Operations After checking that you are connected to the internet, you can perform any network operation. Here we are fetching the html of a website from a url. Android provides HttpURLConnection and URL class to handle these operations. You need to instantiate an object of URL class by providing the link of website. Its syntax is as follows − String link = “http://www.google.com”; URL url = new URL(link); After that you need to call openConnection method of url class and receive it in a HttpURLConnection object. After that you need to call the connect method of HttpURLConnection class. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); And the last thing you need to do is to fetch the HTML from the website. For this you will use InputStream and BufferedReader class. Its syntax is given below − InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, “UTF-8”)); String webPage = “”,data=””; while ((data = reader.readLine()) != null){ webPage += data + “n”; } Apart from this connect method, there are other methods available in HttpURLConnection class. They are listed below − Sr.No Method & description 1 disconnect() This method releases this connection so that its resources may be either reused or closed 2 getRequestMethod() This method returns the request method which will be used to make the request to the remote HTTP server 3 getResponseCode() This method returns response code returned by the remote HTTP server 4 setRequestMethod(String method) This method Sets the request command which will be sent to the remote HTTP server 5 usingProxy() This method returns whether this connection uses a proxy server or not Example The below example demonstrates the use of HttpURLConnection class. It creates a basic application that allows you to download HTML from a given web page. To experiment with this example, you need to run this on an actual device on which wifi internet is connected . Steps Description 1 You will use Android studio IDE to create an Android application under a package com.tutorialspoint.myapplication. 2 Modify src/MainActivity.java file to add Activity code. 4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 6 Modify AndroidManifest.xml to add necessary permissions. 7 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of src/MainActivity.java. package com.tutorialspoint.myapplication; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class MainActivity extends ActionBarActivity { private ProgressDialog progressDialog; private Bitmap bitmap = null; Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkInternetConenction(); downloadImage(“https://www.tutorialspoint.com/green/images/logo.png”); } }); } private void downloadImage(String urlStr) { progressDialog = ProgressDialog.show(this, “”, “Downloading Image from ” + urlStr); final String url = urlStr; new Thread() { public void run() { InputStream in = null; Message msg = Message.obtain(); msg.what = 1; try { in = openHttpConnection(url); bitmap = BitmapFactory.decodeStream(in); Bundle b = new Bundle(); b.putParcelable(“bitmap”, bitmap); msg.setData(b); in.close(); }catch (IOException e1) { e1.printStackTrace(); } messageHandler.sendMessage(msg); } }.start(); } private InputStream openHttpConnection(String urlStr) { InputStream in = null; int resCode = -1; try { URL url = new URL(urlStr); URLConnection urlConn = url.openConnection(); if (!(urlConn instanceof HttpURLConnection)) { throw new IOException(“URL is not an Http URL”); } HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod(“GET”); httpConn.connect(); resCode = httpConn.getResponseCode(); if (resCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } }catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } return in; } private Handler messageHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); ImageView img = (ImageView) findViewById(R.id.imageView); img.setImageBitmap((Bitmap) (msg.getData().getParcelable(“bitmap”))); progressDialog.dismiss(); } }; private boolean checkInternetConenction() { // get Connectivity Manager object to check connection ConnectivityManager connec =(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE); // Check for network connections if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED || connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING || connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING || connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) { Toast.makeText(this, ” Connected “, Toast.LENGTH_LONG).show(); return true; }else if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED ) { Toast.makeText(this, ” Not Connected “, Toast.LENGTH_LONG).show(); return false; } return false; } } Here is the content of activity_main.xml. <?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” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”UI Animator Viewer” android:id=”@+id/textView” android:textSize=”25sp” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:textColor=”#ff36ff15″ android:textIsSelectable=”false” android:textSize=”35dp” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:layout_below=”@+id/textView2″ android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Button” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_centerHorizontal=”true” android:layout_marginTop=”76dp” /> </RelativeLayout> Here is the content of Strings.xml. <resources> <string name=”app_name”>My Application</string> </resources> Here is the content of AndroidManifest.xml <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.tutorialspoint.myapplication” > <uses-permission android:name=”android.permission.INTERNET”></uses-permission> <uses-permission

Android – Clipboard

Android – Clipboard ”; Previous Next Android provides the clipboard framework for copying and pasting different types of data. The data could be text, images, binary stream data or other complex data types. Android provides the library of ClipboardManager and ClipData and ClipData.item to use the copying and pasting framework.In order to use clipboard framework, you need to put data into clip object, and then put that object into system wide clipboard. In order to use clipboard , you need to instantiate an object of ClipboardManager by calling the getSystemService() method. Its syntax is given below − ClipboardManager myClipboard; myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE); Copying data The next thing you need to do is to instantiate the ClipData object by calling the respective type of data method of the ClipData class. In case of text data , the newPlainText method will be called. After that you have to set that data as the clip of the Clipboard Manager object.Its syntax is given below − ClipData myClip; String text = “hello world”; myClip = ClipData.newPlainText(“text”, text); myClipboard.setPrimaryClip(myClip); The ClipData object can take these three form and following functions are used to create those forms. Sr.No ClipData Form & Method 1 Text newPlainText(label, text) Returns a ClipData object whose single ClipData.Item object contains a text string. 2 URI newUri(resolver, label, URI) Returns a ClipData object whose single ClipData.Item object contains a URI. 3 Intent newIntent(label, intent) Returns a ClipData object whose single ClipData.Item object contains an Intent. Pasting data In order to paste the data, we will first get the clip by calling the getPrimaryClip() method. And from that click we will get the item in ClipData.Item object. And from the object we will get the data. Its syntax is given below − ClipData abc = myClipboard.getPrimaryClip(); ClipData.Item item = abc.getItemAt(0); String text = item.getText().toString(); Apart from the these methods , there are other methods provided by the ClipboardManager class for managing clipboard framework. These methods are listed below − Sr.No Method & description 1 getPrimaryClip() This method just returns the current primary clip on the clipboard 2 getPrimaryClipDescription() This method returns a description of the current primary clip on the clipboard but not a copy of its data. 3 hasPrimaryClip() This method returns true if there is currently a primary clip on the clipboard 4 setPrimaryClip(ClipData clip) This method sets the current primary clip on the clipboard 5 setText(CharSequence text) This method can be directly used to copy text into the clipboard 6 getText() This method can be directly used to get the copied text from the clipboard Example Here is an example demonstrating the use of ClipboardManager class. It creates a basic copy paste application that allows you to copy the text and then paste it via clipboard. To experiment with this example , you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio IDE to create an Android application and under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.ClipData; import android.content.ClipboardManager; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends ActionBarActivity { EditText ed1, ed2; Button b1, b2; private ClipboardManager myClipboard; private ClipData myClip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1 = (EditText) findViewById(R.id.editText); ed2 = (EditText) findViewById(R.id.editText2); b1 = (Button) findViewById(R.id.button); b2 = (Button) findViewById(R.id.button2); myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text; text = ed1.getText().toString(); myClip = ClipData.newPlainText(“text”, text); myClipboard.setPrimaryClip(myClip); Toast.makeText(getApplicationContext(), “Text Copied”, Toast.LENGTH_SHORT).show(); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ClipData abc = myClipboard.getPrimaryClip(); ClipData.Item item = abc.getItemAt(0); String text = item.getText().toString(); ed2.setText(text); Toast.makeText(getApplicationContext(), “Text Pasted”, Toast.LENGTH_SHORT).show(); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. <?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” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:text=”Example” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:hint=”Copy text” android:layout_below=”@+id/imageView” android:layout_alignLeft=”@+id/imageView” android:layout_alignStart=”@+id/imageView” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText2″ android:layout_alignLeft=”@+id/editText” android:layout_alignStart=”@+id/editText” android:hint=”paste text” android:layout_below=”@+id/editText” android:layout_alignRight=”@+id/editText” android:layout_alignEnd=”@+id/editText” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Copy text” android:id=”@+id/button” android:layout_below=”@+id/editText2″ android:layout_alignLeft=”@+id/editText2″ android:layout_alignStart=”@+id/editText2″ /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Paste text” android:id=”@+id/button2″ android:layout_below=”@+id/editText2″ android:layout_alignRight=”@+id/editText2″ android:layout_alignEnd=”@+id/editText2″ /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name=”app_name”>My Application</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”com.example.sairamkrishna.myapplication.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run our an application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the tool bar. Android studio installer will display following images − Now just enter any text in the Text to copy field and then select the copy text button. The following notification will be displayed which is shown below − Now just press the paste button, and you will see the text which is copied is now pasted in the field of Copied Text. It is shown below − Print Page Previous Next Advertisements ”;