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 – Spelling Checker

Android – Spelling Checker ”; Previous Next The Android platform offers a spelling checker framework that lets you implement and access spell checking in your application. In order to use spelling checker , you need to implement SpellCheckerSessionListener interface and override its methods. Its syntax is given below − public class HelloSpellCheckerActivity extends Activity implements SpellCheckerSessionListener { @Override public void onGetSuggestions(final SuggestionsInfo[] arg0) { // TODO Auto-generated method stub } @Override public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) { // TODO Auto-generated method stub } } Next thing you need to do is to create an object of SpellCheckerSession class. This object can be instantiated by calling newSpellCheckerSession method of TextServicesManager class. This class handles interaction between application and text services. You need to request system service to instantiate it. Its syntax is given below − private SpellCheckerSession mScs; final TextServicesManager tsm = (TextServicesManager) getSystemService( Context.TEXT_SERVICES_MANAGER_SERVICE); mScs = tsm.newSpellCheckerSession(null, null, this, true); The last thing you need to do is to call getSuggestions method to get suggestion for any text, you want. The suggestions will be passed onto the onGetSuggestions method from where you can do whatever you want. mScs.getSuggestions(new TextInfo(editText1.getText().toString()), 3); This method takes two parameters. First parameter is the string in the form of Text Info object, and second parameter is the cookie number used to distinguish suggestions. Apart from the the methods , there are other methods provided by the SpellCheckerSession class for better handling suggestions. These methods are listed below − Sr.No Method & description 1 cancel() Cancel pending and running spell check tasks 2 close() Finish this session and allow TextServicesManagerService to disconnect the bound spell checker 3 getSentenceSuggestions(TextInfo[] textInfos, int suggestionsLimit) Get suggestions from the specified sentences 4 getSpellChecker() Get the spell checker service info this spell checker session has. 5 isSessionDisconnected() True if the connection to a text service of this session is disconnected and not alive. Example Here is an example demonstrating the use of Spell Checker. It creates a basic spell checking application that allows you to write text and get suggestions. 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/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.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.textservice.TextInfo; import android.view.textservice.TextServicesManager; import android.widget.Button; import android.widget.EditText; import android.view.textservice.SentenceSuggestionsInfo; import android.view.textservice.SpellCheckerSession; import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener; import android.view.textservice.SuggestionsInfo; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements SpellCheckerSessionListener { Button b1; TextView tv1; EditText ed1; private SpellCheckerSession mScs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); tv1=(TextView)findViewById(R.id.textView3); ed1=(EditText)findViewById(R.id.editText); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), ed1.getText().toString(),Toast.LENGTH_SHORT).show(); mScs.getSuggestions(new TextInfo(ed1.getText().toString()), 3); } }); } public void onResume() { super.onResume(); final TextServicesManager tsm = (TextServicesManager) getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE); mScs = tsm.newSpellCheckerSession(null, null, this, true); } public void onPause() { super.onPause(); if (mScs != null) { mScs.close(); } } public void onGetSuggestions(final SuggestionsInfo[] arg0) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < arg0.length; ++i) { // Returned suggestions are contained in SuggestionsInfo final int len = arg0[i].getSuggestionsCount(); sb.append(”n”); for (int j = 0; j < len; ++j) { sb.append(“,” + arg0[i].getSuggestionAt(j)); } sb.append(” (” + len + “)”); } runOnUiThread(new Runnable() { public void run() { tv1.append(sb.toString()); } }); } @Override public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) { // TODO Auto-generated method stub } } Following is the modified content of the xml res/layout/main.xml. In the following 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:text=”Spell checker ” 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” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Suggestions” android:id=”@+id/button” android:layout_alignParentBottom=”true” android:layout_centerHorizontal=”true” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:hint=”Enter Text” android:layout_above=”@+id/button” android:layout_marginBottom=”56dp” android:focusable=”true” android:textColorHighlight=”#ff7eff15″ android:textColorHint=”#ffff25e6″ android:layout_alignRight=”@+id/textview” android:layout_alignEnd=”@+id/textview” android:layout_alignLeft=”@+id/textview” android:layout_alignStart=”@+id/textview” /> <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” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Suggestions” android:id=”@+id/textView3″ android:textSize=”25sp” android:layout_below=”@+id/imageView” /> </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 ourr 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 − Now what you need to do is to enter any text in the field. For example, i have entered some text. Press the suggestions button. The following notification would appear in you AVD along with suggestions − Now change the text and press the button again, like i did. And this is what comes on screen. Print Page Previous Next Advertisements ”;

Android – Broadcast Receivers

Android – Broadcast Receivers ”; Previous Next Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action. There are following two important steps to make BroadcastReceiver works for the system broadcasted intents − Creating the Broadcast Receiver. Registering Broadcast Receiver There is one additional steps in case you are going to implement your custom intents then you will have to create and broadcast those intents. Creating the Broadcast Receiver A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter. public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, “Intent Detected.”, Toast.LENGTH_LONG).show(); } } Registering Broadcast Receiver An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process. Broadcast-Receiver <application android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <receiver android:name=”MyReceiver”> <intent-filter> <action android:name=”android.intent.action.BOOT_COMPLETED”> </action> </intent-filter> </receiver> </application> Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be executed. There are several system generated events defined as final static fields in the Intent class. The following table lists a few important system events. Sr.No Event Constant & Description 1 android.intent.action.BATTERY_CHANGED Sticky broadcast containing the charging state, level, and other information about the battery. 2 android.intent.action.BATTERY_LOW Indicates low battery condition on the device. 3 android.intent.action.BATTERY_OKAY Indicates the battery is now okay after being low. 4 android.intent.action.BOOT_COMPLETED This is broadcast once, after the system has finished booting. 5 android.intent.action.BUG_REPORT Show activity for reporting a bug. 6 android.intent.action.CALL Perform a call to someone specified by the data. 7 android.intent.action.CALL_BUTTON The user pressed the “call” button to go to the dialer or other appropriate UI for placing a call. 8 android.intent.action.DATE_CHANGED The date has changed. 9 android.intent.action.REBOOT Have the device reboot. Broadcasting Custom Intents If you want your application itself should generate and send custom intents then you will have to create and send those intents by using the sendBroadcast() method inside your activity class. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete. public void broadcastIntent(View view) { Intent intent = new Intent(); intent.setAction(“com.tutorialspoint.CUSTOM_INTENT”); sendBroadcast(intent); } This intent com.tutorialspoint.CUSTOM_INTENT can also be registered in similar way as we have regsitered system generated intent. <application android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <receiver android:name=”MyReceiver”> <intent-filter> <action android:name=”com.tutorialspoint.CUSTOM_INTENT”> </action> </intent-filter> </receiver> </application> Example This example will explain you how to create BroadcastReceiver to intercept custom intent. Once you are familiar with custom intent, then you can program your application to intercept system generated intents. So let”s follow the following steps to modify the Android application we created in Hello World Example chapter − Step Description 1 You will use Android studio to create an Android application and name it as My Application under a package com.example.tutorialspoint7.myapplication as explained in the Hello World Example chapter. 2 Modify main activity file MainActivity.java to add broadcastIntent() method. 3 Create a new java file called MyReceiver.java under the package com.example.tutorialspoint7.myapplication to define a BroadcastReceiver. 4 An application can handle one or more custom and system intents without any restrictions. Every intent you want to intercept must be registered in your AndroidManifest.xml file using <receiver…/> tag 5 Modify the default content of res/layout/activity_main.xml file to include a button to broadcast intent. 6 No need to modify the string file, Android studio take care of string.xml file. 7 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity file MainActivity.java. This file can include each of the fundamental life cycle methods. We have added broadcastIntent() method to broadcast a custom intent. package com.example.tutorialspoint7.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // broadcast a custom intent. public void broadcastIntent(View view){ Intent intent = new Intent(); intent.setAction(“com.tutorialspoint.CUSTOM_INTENT”); sendBroadcast(intent); } } Following is the content of MyReceiver.java: package com.example.tutorialspoint7.myapplication; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * Created by TutorialsPoint7 on 8/23/2016. */ public class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, “Intent Detected.”, Toast.LENGTH_LONG).show(); } } Following will the modified content of AndroidManifest.xml file. Here we have added <receiver…/> tag to include our service: <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.tutorialspoint7.myapplication”> <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:supportsRtl=”true” android:theme=”@style/AppTheme”> <activity android:name=”.MainActivity”> <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> <receiver android:name=”MyReceiver”> <intent-filter> <action android:name=”com.tutorialspoint.CUSTOM_INTENT”> </action> </intent-filter> </receiver> </application> </manifest> Following will be the content of res/layout/activity_main.xml file to include a button to broadcast our custom intent − <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:id=”@+id/textView1″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Example of Broadcast” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:textSize=”30dp” /> <TextView android:id=”@+id/textView2″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point ” android:textColor=”#ff87ff09″ android:textSize=”30dp” android:layout_above=”@+id/imageButton” android:layout_centerHorizontal=”true” android:layout_marginBottom=”40dp” /> <ImageButton android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageButton” android:src=”@drawable/abc” android:layout_centerVertical=”true” android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/button2″ android:text=”Broadcast Intent” android:onClick=”broadcastIntent” android:layout_below=”@+id/imageButton” android:layout_centerHorizontal=”true” /> </RelativeLayout> Let”s try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment set-up. 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 installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window − Now to broadcast our

Android – Internal Storage

Android – Internal Storage ”; Previous Next Android provides many kinds of storage for applications to store their data. These storage places are shared preferences, internal and external storage, SQLite storage, and storage via network connection. In this chapter we are going to look at the internal storage. Internal storage is the storage of the private data on the device memory. By default these files are private and are accessed by only your application and get deleted , when user delete your application. Writing file In order to use internal storage to write some data in the file, call the openFileOutput() method with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is given below − FileOutputStream fOut = openFileOutput(“file name here”,MODE_WORLD_READABLE); The method openFileOutput() returns an instance of FileOutputStream. So you receive it in the object of FileInputStream. After that you can call write method to write data on the file. Its syntax is given below − String str = “data”; fOut.write(str.getBytes()); fOut.close(); Reading file In order to read from the file you just created , call the openFileInput() method with the name of the file. It returns an instance of FileInputStream. Its syntax is given below − FileInputStream fin = openFileInput(file); After that, you can call read method to read one character at a time from the file and then you can print it. Its syntax is given below − int c; String temp=””; while( (c = fin.read()) != -1){ temp = temp + Character.toString((char)c); } //string temp contains all the data of the file. fin.close(); Apart from the the methods of write and close, there are other methods provided by the FileOutputStream class for better writing files. These methods are listed below − Sr.No Method & description 1 FileOutputStream(File file, boolean append) This method constructs a new FileOutputStream that writes to file. 2 getChannel() This method returns a write-only FileChannel that shares its position with this stream 3 getFD() This method returns the underlying file descriptor 4 write(byte[] buffer, int byteOffset, int byteCount) This method Writes count bytes from the byte array buffer starting at position offset to this stream Apart from the the methods of read and close, there are other methods provided by the FileInputStream class for better reading files. These methods are listed below − Sr.No Method & description 1 available() This method returns an estimated number of bytes that can be read or skipped without blocking for more input 2 getChannel() This method returns a read-only FileChannel that shares its position with this stream 3 getFD() This method returns the underlying file descriptor 4 read(byte[] buffer, int byteOffset, int byteCount) This method reads at most length bytes from this stream and stores them in the byte array b starting at offset Example Here is an example demonstrating the use of internal storage to store and read files. It creates a basic storage application that allows you to read and write from internal storage. 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 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.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.FileInputStream; import java.io.FileOutputStream; public class MainActivity extends Activity { Button b1,b2; TextView tv; EditText ed1; String data; private String file = “mydata”; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); b2=(Button)findViewById(R.id.button2); ed1=(EditText)findViewById(R.id.editText); tv=(TextView)findViewById(R.id.textView2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { data=ed1.getText().toString(); try { FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE); fOut.write(data.getBytes()); fOut.close(); Toast.makeText(getBaseContext(),”file saved”,Toast.LENGTH_SHORT).show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { FileInputStream fin = openFileInput(file); int c; String temp=””; while( (c = fin.read()) != -1){ temp = temp + Character.toString((char)c); } tv.setText(temp); Toast.makeText(getBaseContext(),”file read”,Toast.LENGTH_SHORT).show(); } catch(Exception e){ } } }); } } Following is the modified content of the xml res/layout/activity_main.xml. In the following 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:text=”Internal storage” 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” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Save” android:id=”@+id/button” android:layout_alignParentBottom=”true” android:layout_alignLeft=”@+id/textView” android:layout_alignStart=”@+id/textView” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:hint=”Enter Text” android:focusable=”true” android:textColorHighlight=”#ff7eff15″ android:textColorHint=”#ffff25e6″ android:layout_below=”@+id/imageView” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:layout_marginTop=”42dp” android:layout_alignLeft=”@+id/imageView” android:layout_alignStart=”@+id/imageView” /> <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” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”load” android:id=”@+id/button2″ android:layout_alignTop=”@+id/button” android:layout_alignRight=”@+id/editText” android:layout_alignEnd=”@+id/editText” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Read” android:id=”@+id/textView2″ android:layout_below=”@+id/editText” android:layout_toLeftOf=”@+id/button2″ android:layout_toStartOf=”@+id/button2″ android:textColor=”#ff5bff1f” android:textSize=”25dp” /> </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 Storage 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 installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window − Now what you need to do is to enter any text in the field. For example , i have entered some text. Press the save button. The following notification would appear in you AVD − Now when you press the load button, the application will read the file , and display the data. In case of our, following data would be returned

Android – Notifications

Android – Notifications ”; Previous Next A notification is a message you can display to the user outside of your application”s normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time. Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persistent which means alert flashes on the screen for a few seconds and then disappears. To see the details of the notification, you will have to select the icon which will display notification drawer having detail about the notification. While working with emulator with virtual device, you will have to click and drag down the status bar to expand it which will give you detail as follows. This will be just 64 dp tall and called normal view. Above expanded form can have a Big View which will have additional detail about the notification. You can add upto six additional lines in the notification. The following screen shot shows such notification. Create and Send Notifications You have simple way to create a notification. Follow the following steps in your application to create a notification − Step 1 – Create Notification Builder As a first step is to create a notification builder using NotificationCompat.Builder.build(). You will use Notification Builder to set various Notification properties like its small and large icons, title, priority etc. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) Step 2 – Setting Notification Properties Once you have Builder object, you can set its Notification properties using Builder object as per your requirement. But this is mandatory to set at least following − A small icon, set by setSmallIcon() A title, set by setContentTitle() Detail text, set by setContentText() mBuilder.setSmallIcon(R.drawable.notification_icon); mBuilder.setContentTitle(“Notification Alert, Click Me!”); mBuilder.setContentText(“Hi, This is Android Notification Detail!”); You have plenty of optional properties which you can set for your notification. To learn more about them, see the reference documentation for NotificationCompat.Builder. Step 3 – Attach Actions This is an optional part and required if you want to attach an action with the notification. An action allows users to go directly from the notification to an Activity in your application, where they can look at one or more events or do further work. The action is defined by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method of NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent(). A PendingIntent object helps you to perform an action on your applications behalf, often at a later time, without caring of whether or not your application is running. We take help of stack builder object which will contain an artificial back stack for the started Activity. This ensures that navigating backward from the Activity leads out of your application to the Home screen. Intent resultIntent = new Intent(this, ResultActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(ResultActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); Step 4 – Issue the notification Finally, you pass the Notification object to the system by calling NotificationManager.notify() to send your notification. Make sure you call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // notificationID allows you to update the notification later on. mNotificationManager.notify(notificationID, mBuilder.build()); The NotificationCompat.Builder Class The NotificationCompat.Builder class allows easier control over all the flags, as well as help constructing the typical notification layouts. Following are few important and most frequently used methods available as a part of NotificationCompat.Builder class. Sr.No. Constants & Description 1 Notification build() Combine all of the options that have been set and return a new Notification object. 2 NotificationCompat.Builder setAutoCancel (boolean autoCancel) Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel. 3 NotificationCompat.Builder setContent (RemoteViews views) Supply a custom RemoteViews to use instead of the standard one. 4 NotificationCompat.Builder setContentInfo (CharSequence info) Set the large text at the right-hand side of the notification. 5 NotificationCompat.Builder setContentIntent (PendingIntent intent) Supply a PendingIntent to send when the notification is clicked. 6 NotificationCompat.Builder setContentText (CharSequence text) Set the text (second row) of the notification, in a standard notification. 7 NotificationCompat.Builder setContentTitle (CharSequence title) Set the text (first row) of the notification, in a standard notification. 8 NotificationCompat.Builder setDefaults (int defaults) Set the default notification options that will be used. 9 NotificationCompat.Builder setLargeIcon (Bitmap icon) Set the large icon that is shown in the ticker and notification. 10 NotificationCompat.Builder setNumber (int number) Set the large number at the right-hand side of the notification. 11 NotificationCompat.Builder setOngoing (boolean ongoing) Set whether this is an ongoing notification. 12 NotificationCompat.Builder setSmallIcon (int icon) Set the small icon to use in the notification layouts. 13 NotificationCompat.Builder setStyle (NotificationCompat.Style style) Add a rich notification style to be applied at build time. 14 NotificationCompat.Builder setTicker (CharSequence tickerText) Set the text that is displayed in the status bar when the notification first arrives. 15 NotificationCompat.Builder setVibrate (long[] pattern) Set the vibration pattern to use. 16 NotificationCompat.Builder setWhen (long when) Set the time that the event occurred. Notifications in the panel are sorted by this time. Example Following example shows the functionality of a Android notification using a NotificationCompat.Builder Class which has been introduced in Android 4.1. Step Description 1 You will use Android studio IDE to create an Android application and name it as tutorialspoint under a package com.example.notificationdemo. 2 Modify src/MainActivity.java file and add the code to notify(“”), if user click on the button,it will call android notification

Android – Questions and Answers

Android Questions and Answers ”; Previous Next Android Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 Android Interview Questions This section provides a huge collection of Android Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Android Online Quiz This section provides a great collection of Android Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Android Online Test If you are preparing to appear for a Java and Android Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Android Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;

Android – ProgressBar

Android Progress Bar using ProgressDialog ”; Previous Next Progress bars are used to show progress of a task. For example, when you are uploading or downloading something from the internet, it is better to show the progress of download/upload to the user. In android there is a class called ProgressDialog that allows you to create progress bar. In order to do this, you need to instantiate an object of this class. Its syntax is. ProgressDialog progress = new ProgressDialog(this); Now you can set some properties of this dialog. Such as, its style, its text etc. progress.setMessage(“Downloading Music 🙂 “); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setIndeterminate(true); Apart from these methods, there are other methods that are provided by the ProgressDialog class Sr. No Title & description 1 getMax() This method returns the maximum value of the progress. 2 incrementProgressBy(int diff) This method increments the progress bar by the difference of value passed as a parameter. 3 setIndeterminate(boolean indeterminate) This method sets the progress indicator as determinate or indeterminate. 4 setMax(int max) This method sets the maximum value of the progress dialog. 5 setProgress(int value) This method is used to update the progress dialog with some specific value. 6 show(Context context, CharSequence title, CharSequence message) This is a static method, used to display progress dialog. Example This example demonstrates the horizontal use of the progress dialog which is in fact a progress bar. It display a progress bar on pressing the button. To experiment with this example, you need to run this on an actual device after developing the application according to the steps below. 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 progress code to display the progress dialog. 3 Modify res/layout/activity_main.xml file to add respective XML code. 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.app.ProgressDialog; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends ActionBarActivity { Button b1; private ProgressDialog progress; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button2); } public void download(View view){ progress=new ProgressDialog(this); progress.setMessage(“Downloading Music”); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setIndeterminate(true); progress.setProgress(0); progress.show(); final int totalProgressTime = 100; final Thread t = new Thread() { @Override public void run() { int jumpTime = 0; while(jumpTime < totalProgressTime) { try { sleep(200); jumpTime += 5; progress.setProgress(jumpTime); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; t.start(); } } Modify the content of res/layout/activity_main.xml to the following − <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=”Progress bar” /> <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″ /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Download” android:onClick=”download” android:id=”@+id/button2″ android:layout_marginLeft=”125dp” android:layout_marginStart=”125dp” android:layout_centerVertical=”true” /> </RelativeLayout> This is the default AndroidManifest.xml − <?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 your application. We assume, you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Select your mobile device as an option and then check your mobile device which will display following screen − Just press the button to start the Progress bar. After pressing, following screen would appear − It will continuously update itself. Print Page Previous Next Advertisements ”;

Android – ImageSwitcher

Android – Image Switcher ”; Previous Next Sometimes you don”t want an image to appear abruptly on the screen, rather you want to apply some kind of animation to the image when it transitions from one image to another. This is supported by android in the form of ImageSwitcher. An image switcher allows you to add some transitions on the images through the way they appear on screen. In order to use image Switcher, you need to define its XML component first. Its syntax is given below − <ImageSwitcher android:id=”@+id/imageSwitcher1″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_centerHorizontal=”true” android:layout_centerVertical=”true” > </ImageSwitcher> Now we create an intance of ImageSwithcer in java file and get a reference of this XML component. Its syntax is given below − private ImageSwitcher imageSwitcher; imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1); The next thing we need to do implement the ViewFactory interface and implement unimplemented method that returns an imageView. Its syntax is below − imageSwitcher.setImageResource(R.drawable.ic_launcher); imageSwitcher.setFactory(new ViewFactory() { public View makeView() { ImageView myView = new ImageView(getApplicationContext()); return myView; } } The last thing you need to do is to add Animation to the ImageSwitcher. You need to define an object of Animation class through AnimationUtilities class by calling a static method loadAnimation. Its syntax is given below − Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left); imageSwitcher.setInAnimation(in); imageSwitcher.setOutAnimation(out); The method setInAnimaton sets the animation of the appearance of the object on the screen whereas setOutAnimation does the opposite. The method loadAnimation() creates an animation object. Apart from these methods, there are other methods defined in the ImageSwitcher class. They are defined below − Sr.No Method & description 1 setImageDrawable(Drawable drawable) Sets an image with image switcher. The image is passed in the form of bitmap 2 setImageResource(int resid) Sets an image with image switcher. The image is passed in the form of integer id 3 setImageURI(Uri uri) Sets an image with image switcher. THe image is passed in the form of URI 4 ImageSwitcher(Context context, AttributeSet attrs) Returns an image switcher object with already setting some attributes passed in the method 5 onInitializeAccessibilityEvent (AccessibilityEvent event) Initializes an AccessibilityEvent with information about this View which is the event source 6 onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo info) Initializes an AccessibilityNodeInfo with information about this view Example The below example demonstrates some of the image switcher effects on the bitmap. It crates a basic application that allows you to view the animation effects on the images. To experiment with this example , you need to run this on an actual device. Steps Description 1 You will use Android studio IDE 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 src/MainActivity.java. In the below code tp and abc indicates the logo of tutorialspoint.com package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.app.ActionBar.LayoutParams; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.Toast; import android.widget.ViewSwitcher.ViewFactory; public class MainActivity extends Activity { private ImageSwitcher sw; private Button b1,b2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b2 = (Button) findViewById(R.id.button2); sw = (ImageSwitcher) findViewById(R.id.imageSwitcher); sw.setFactory(new ViewFactory() { @Override public View makeView() { ImageView myView = new ImageView(getApplicationContext()); myView.setScaleType(ImageView.ScaleType.FIT_CENTER); myView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); return myView; } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), “previous Image”, Toast.LENGTH_LONG).show(); sw.setImageResource(R.drawable.abc); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), “Next Image”, Toast.LENGTH_LONG).show(); sw.setImageResource(R.drawable.tp); } }); } } 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=”Gestures 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” /> <ImageSwitcher android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageSwitcher” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:layout_marginTop=”168dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/left” android:id=”@+id/button” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/right” android:id=”@+id/button2″ android:layout_alignParentBottom=”true” android:layout_alignLeft=”@+id/button” android:layout_alignStart=”@+id/button” /> </RelativeLayout> Following is the content of Strings.xml file. <resources> <string name=”app_name”>My Application</string> <string name=”left”><![CDATA[<]]></string> <string name=”right”><![CDATA[>]]></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 your 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 − Now if you will look at your device screen , you will see the two buttons. Now just select the upper button that right arrow. An image would appear from right and move towards left. It is shown below − Now tap on the below button, that will bring back the previous image with some transition. It is shown below − Print Page Previous Next Advertisements ”;

Android – AudioManager

Android – Audio Manager ”; Previous Next You can easily control your ringer volume and ringer profile i-e:(silent,vibrate,loud e.t.c) in android. Android provides AudioManager class that provides access to these controls. In order to use AndroidManager class, you have to first create an object of AudioManager class by calling the getSystemService() method. Its syntax is given below. private AudioManager myAudioManager; myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); Once you instantiate the object of AudioManager class, you can use setRingerMode method to set the audio or ringer profile of your device. Its syntax is given below. myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); The method setRingerMode takes an integer number as a parameter. For each mode , an integer number is assigned that will differentiate between different modes. The possible modes are. Sr.No Mode & Description 1 RINGER_MODE_VIBRATE This Mode sets the device at vibrate mode. 2 RINGER_MODE_NORMAL This Mode sets the device at normal(loud) mode. 3 RINGER_MODE_SILENT This Mode sets the device at silent mode. Once you have set the mode , you can call the getRingerMode() method to get the set state of the system. Its syntax is given below. int mod = myAudioManager.getRingerMode(); Apart from the getRingerMode method, there are other methods available in the AudioManager class to control the volume and other modes. They are listed below. Sr.No Method & description 1 adjustVolume(int direction, int flags) This method adjusts the volume of the most relevant stream 2 getMode() This method returns the current audio mode 3 getStreamMaxVolume(int streamType) This method returns the maximum volume index for a particular stream 4 getStreamVolume(int streamType) This method returns the current volume index for a particular stream 5 isMusicActive() This method checks whether any music is active. 6 startBluetoothSco() This method Start bluetooth SCO audio connection 7 stopBluetoothSco() This method stop bluetooth SCO audio connection. Example The below example demonstrates the use of AudioManager class. It creates a application that allows you to set different ringer modes for your device. To experiment with this example , you need to run this on an actual device. Steps Description 1 You will use Android studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add AudioManager code 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 4 Modify res/values/string.xml file and add necessary string components. 5 Modify AndroidManifest.xml to add necessary permissions. 6 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.example.sairamkrishna.myapplication; import android.app.Activity; import android.content.Context; import android.media.AudioManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { Button mode,ring,vibrate,silent; private AudioManager myAudioManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); vibrate=(Button)findViewById(R.id.button3); ring=(Button)findViewById(R.id.button2); mode=(Button)findViewById(R.id.button); silent=(Button)findViewById(R.id.button4); myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); vibrate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); Toast.makeText(MainActivity.this,”Now in Vibrate Mode”, Toast.LENGTH_LONG).show(); } }); ring.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); Toast.makeText(MainActivity.this,”Now in Ringing Mode”, Toast.LENGTH_LONG).show(); } }); silent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); Toast.makeText(MainActivity.this,”Now in silent Mode”, Toast.LENGTH_LONG).show(); } }); mode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int mod=myAudioManager.getRingerMode(); if(mod==AudioManager.RINGER_MODE_VIBRATE){ Toast.makeText(MainActivity.this,”Now in Vibrate Mode”, Toast.LENGTH_LONG).show(); } else if(mod==AudioManager.RINGER_MODE_NORMAL){ Toast.makeText(MainActivity.this,”Now in Ringing Mode”, Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this,”Now in Vibrate Mode”, Toast.LENGTH_LONG).show(); } } }); } } Here is the content of activity_main.xml Here abc indicates the logo of tutorialspoint <?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=”Android Audio Recording” android:id=”@+id/textView” android:textSize=”30dp” android:layout_alignParentTop=”true” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorialspoint” android:id=”@+id/textView2″ android:textColor=”#ff3eff0f” android:textSize=”35dp” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView2″ android:layout_alignLeft=”@+id/textView2″ android:layout_alignStart=”@+id/textView2″ android:layout_alignRight=”@+id/textView2″ android:layout_alignEnd=”@+id/textView2″ /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Mode” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_marginTop=”59dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Ring” android:id=”@+id/button2″ android:layout_alignTop=”@+id/button” android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”vibrate” android:id=”@+id/button3″ android:layout_alignTop=”@+id/button2″ android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Silent” android:id=”@+id/button4″ android:layout_below=”@+id/button2″ android:layout_alignLeft=”@+id/button2″ android:layout_alignStart=”@+id/button2″ /> </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.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” 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 your application. I assume you have connected your actual Android Mobile device with your computer. 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 will display Images Now select silent button, you would get silent icon at Notification bar Now just select the ring button and then press the current mode button to see that if its status has been set. Now press the Vibrate button and then press the current mode button to see that if it is set or not.It will display the following screen. Print Page Previous Next Advertisements ”;

Android – Google Maps

Android – Google Maps ”; Previous Next Android allows us to integrate google maps in our application. You can show any location on the map , or can show different routes on the map e.t.c. You can also customize the map according to your choices. Google Map – Layout file Now you have to add the map fragment into xml layout file. Its syntax is given below − <fragment android:id=”@+id/map” android:name=”com.google.android.gms.maps.MapFragment” android:layout_width=”match_parent” android:layout_height=”match_parent”/> Google Map – AndroidManifest file The next thing you need to do is to add some permissions along with the Google Map API key in the AndroidManifest.XML file. Its syntax is given below − <!–Permissions–> <uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” /> <uses-permission android:name=”android.permission.INTERNET” /> <uses-permission android:name=”com.google.android.providers.gsf.permission. READ_GSERVICES” /> <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” /> <!–Google MAP API key–> <meta-data android:name=”com.google.android.maps.v2.API_KEY” android:value=”AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0″ /> Customizing Google Map You can easily customize google map from its default view , and change it according to your demand. Adding Marker You can place a maker with some text over it displaying your location on the map. It can be done by via addMarker() method. Its syntax is given below − final LatLng TutorialsPoint = new LatLng(21 , 57); Marker TP = googleMap.addMarker(new MarkerOptions() .position(TutorialsPoint).title(“TutorialsPoint”)); Changing Map Type You can also change the type of the MAP. There are four different types of map and each give a different view of the map. These types are Normal,Hybrid,Satellite and terrain. You can use them as below googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); Enable/Disable zoom You can also enable or disable the zoom gestures in the map by calling the setZoomControlsEnabled(boolean) method. Its syntax is given below − googleMap.getUiSettings().setZoomGesturesEnabled(true); Apart from these customization, there are other methods available in the GoogleMap class , that helps you more customize the map. They are listed below − Sr.No Method & description 1 addCircle(CircleOptions options) This method add a circle to the map 2 addPolygon(PolygonOptions options) This method add a polygon to the map 3 addTileOverlay(TileOverlayOptions options) This method add tile overlay to the map 4 animateCamera(CameraUpdate update) This method Moves the map according to the update with an animation 5 clear() This method removes everything from the map. 6 getMyLocation() This method returns the currently displayed user location. 7 moveCamera(CameraUpdate update) This method repositions the camera according to the instructions defined in the update 8 setTrafficEnabled(boolean enabled) This method Toggles the traffic layer on or off. 9 snapshot(GoogleMap.SnapshotReadyCallback callback) This method Takes a snapshot of the map 10 stopAnimation() This method stops the camera animation if there is one in progress Example Here is an example demonstrating the use of GoogleMap class. It creates a basic M application that allows you to navigate through the map. To experiment with this example , you can run this on an actual device or in an emulator. Create a project with google maps activity as shown below − It will open the following screen and copy the console url for API Key as shown below − Copy this and paste it to your browser. It will give the following screen − Click on continue and click on Create API Key then it will show the following screen Here is the content of activity_main.xml. <fragment xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:map=”http://schemas.android.com/apk/res-auto” xmlns:tools=”http://schemas.android.com/tools” android:id=”@+id/map” android:name=”com.google.android.gms.maps.SupportMapFragment” android:layout_width=”match_parent” android:layout_height=”match_parent” tools:context=”com.example.tutorialspoint7.myapplication.MapsActivity” /> Here is the content of MapActivity.java. In the below code we have given sample latitude and longitude details package com.example.tutorialspoint7.myapplication; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. * In this case, we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device. * This method will only be triggered once the user has installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng TutorialsPoint = new LatLng(21, 57); mMap.addMarker(new MarkerOptions().position(TutorialsPoint).title(“Tutorialspoint.com”)); mMap.moveCamera(CameraUpdateFactory.newLatLng(TutorialsPoint)); } } 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.tutorialspoint7.myapplication”> <!– The ACCESS_COARSE/FINE_LOCATION permissions are not required to use Google Maps Android API v2, but you must specify either coarse or fine location permissions for the ”MyLocation” functionality. –> <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” /> <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” /> <uses-permission android:name=”android.permission.INTERNET” /> <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:supportsRtl=”true” android:theme=”@style/AppTheme”> <!– The API key for Google Maps-based APIs is defined as a string resource. (See the file “res/values/google_maps_api.xml”). Note that the API key is linked to the encryption key used to sign the APK. You need a different API key for each encryption key, including the release key that is used to sign the APK for publishing. You can define the keys for the debug and release targets in src/debug/ and src/release/. –> <meta-data android:name=”com.google.android.geo.API_KEY” android:value=”AIzaSyAXhBdyKxUo_cb-EkSgWJQTdqR0QjLcqes” /> <activity android:name=”.MapsActivity” android:label=”@string/title_activity_maps”> <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Output should be like this − Print Page Previous Next Advertisements ”;