Android – Push Notification ”; Previous Next A notification is a message you can display to the user outside of your application”s normal UI. You can create your own notifications in android very easily. Android provides NotificationManager class for this purpose. In order to use this class, you need to instantiate an object of this class by requesting the android system through getSystemService() method. Its syntax is given below − NotificationManager NM; NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); After that you will create Notification through Notification class and specify its attributes such as icon,title and time e.t.c. Its syntax is given below − Notification notify = new Notification(android.R.drawable.stat_notify_more,title,System.currentTimeMillis()); The next thing you need to do is to create a PendingIntent by passing context and intent as a parameter. By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself. PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(),0); The last thing you need to do is to call setLatestEventInfo method of the Notification class and pass the pending intent along with notification subject and body details. Its syntax is given below. And then finally call the notify method of the NotificationManager class. notify.setLatestEventInfo(getApplicationContext(), subject, body,pending); NM.notify(0, notify); Apart from the notify method, there are other methods available in the NotificationManager class. They are listed below − Sr.No Method & description 1 cancel(int id) This method cancel a previously shown notification. 2 cancel(String tag, int id) This method also cancel a previously shown notification. 3 cancelAll() This method cancel all previously shown notifications. 4 notify(int id, Notification notification) This method post a notification to be shown in the status bar. 5 notify(String tag, int id, Notification notification) This method also Post a notification to be shown in the status bar. Example The below example demonstrates the use of NotificationManager class. It crates a basic application that allows you to create a notification. 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 under a packagecom.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add Notification code. 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 4 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of MainActivity.java. In the following code abc indicates the logo of tutorialspoint.com package com.example.sairamkrishna.myapplication; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends ActionBarActivity { EditText ed1,ed2,ed3; 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); ed3=(EditText)findViewById(R.id.editText3); Button b1=(Button)findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String tittle=ed1.getText().toString().trim(); String subject=ed2.getText().toString().trim(); String body=ed3.getText().toString().trim(); NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); Notification notify=new Notification.Builder (getApplicationContext()).setContentTitle(tittle).setContentText(body). setContentTitle(subject).setSmallIcon(R.drawable.abc).build(); notify.flags |= Notification.FLAG_AUTO_CANCEL; notif.notify(0, notify); } }); } } 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=”Notification” 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″ /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:layout_below=”@+id/textView2″ android:layout_alignLeft=”@+id/textView2″ android:layout_alignStart=”@+id/textView2″ android:layout_marginTop=”52dp” android:layout_alignRight=”@+id/textView2″ android:layout_alignEnd=”@+id/textView2″ android:hint=”Name” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText2″ android:hint=”Subject” android:layout_below=”@+id/editText” android:layout_alignLeft=”@+id/editText” android:layout_alignStart=”@+id/editText” android:layout_alignRight=”@+id/editText” android:layout_alignEnd=”@+id/editText” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:inputType=”textPersonName” android:ems=”10″ android:id=”@+id/editText3″ android:hint=”Body” android:layout_below=”@+id/editText2″ android:layout_alignLeft=”@+id/editText2″ android:layout_alignStart=”@+id/editText2″ android:layout_alignRight=”@+id/editText2″ android:layout_alignEnd=”@+id/editText2″ /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Notification” android:id=”@+id/button” android:layout_marginTop=”77dp” android:layout_below=”@+id/editText3″ android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” /> </RelativeLayout> 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=”@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 application. To run the app from Android studio, open one of your project”s activity files and click Run icon from the tool bar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Now fill in the field with the title , subject and the body. This has been shown below in the figure − Now click on the notify button and you will see a notification in the top notification bar. It has been shown below − Now scroll down the notification bar and see the notification. This has been shown below in the figure − Print Page Previous Next Advertisements ”;
Category: Android
Android – Sending SMS
Android – Sending SMS ”; Previous Next In Android, you can use SmsManager API or devices Built-in SMS application to send SMS”s. In this tutorial, we shows you two basic examples to send SMS message − SmsManager API SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(“phoneNo”, null, “sms message”, null, null); Built-in SMS application Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra(“sms_body”, “default content”); sendIntent.setType(“vnd.android-dir/mms-sms”); startActivity(sendIntent); Of course, both need SEND_SMS permission. <uses-permission android:name=”android.permission.SEND_SMS” /> Apart from the above method, there are few other important functions available in SmsManager class. These methods are listed below − Sr.No. Method & Description 1 ArrayList<String> divideMessage(String text) This method divides a message text into several fragments, none bigger than the maximum SMS message size. 2 static SmsManager getDefault() This method is used to get the default instance of the SmsManager 3 void sendDataMessage(String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent) This method is used to send a data based SMS to a specific application port. 4 void sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents) Send a multi-part text based SMS. 5 void sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent) Send a text based SMS. Example Following example shows you in practical how to use SmsManager object to send an SMS to the given mobile number. To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work. Step Description 1 You will use Android Studio IDE to create an Android application and name it as tutorialspoint under a package com.example.tutorialspoint. 2 Modify src/MainActivity.java file and add required code to take care of sending sms. 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I”m adding a simple GUI to take mobile number and SMS text to be sent and a simple button to send SMS. 4 No need to define default string constants at res/values/strings.xml. Android studio takes care of default constants. 5 Modify AndroidManifest.xml as shown below 6 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 src/com.example.tutorialspoint/MainActivity.java. package com.example.tutorialspoint; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.app.Activity; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.telephony.SmsManager; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ; Button sendBtn; EditText txtphoneNo; EditText txtMessage; String phoneNo; String message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendBtn = (Button) findViewById(R.id.btnSendSMS); txtphoneNo = (EditText) findViewById(R.id.editText); txtMessage = (EditText) findViewById(R.id.editText2); sendBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { sendSMSMessage(); } }); } protected void sendSMSMessage() { phoneNo = txtphoneNo.getText().toString(); message = txtMessage.getText().toString(); if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS)) { } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS); } } } @Override public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_SEND_SMS: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNo, null, message, null, null); Toast.makeText(getApplicationContext(), “SMS sent.”, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), “SMS faild, please try again.”, Toast.LENGTH_LONG).show(); return; } } } } } Following will be the content of res/layout/activity_main.xml file − Here abc indicates about tutorialspoint logo <?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:paddingBottom=”@dimen/activity_vertical_margin” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” tools:context=”MainActivity”> <TextView android:id=”@+id/textView1″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Sending SMS Example” 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_below=”@+id/textView1″ android:layout_alignRight=”@+id/imageButton” android:layout_alignEnd=”@+id/imageButton” /> <ImageButton android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageButton” android:src=”@drawable/abc” android:layout_below=”@+id/textView2″ android:layout_centerHorizontal=”true” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:hint=”Enter Phone Number” android:phoneNumber=”true” android:textColorHint=”@color/abc_primary_text_material_dark” android:layout_below=”@+id/imageButton” android:layout_centerHorizontal=”true” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText2″ android:layout_below=”@+id/editText” android:layout_alignLeft=”@+id/editText” android:layout_alignStart=”@+id/editText” android:textColorHint=”@color/abc_primary_text_material_dark” android:layout_alignRight=”@+id/imageButton” android:layout_alignEnd=”@+id/imageButton” android:hint=”Enter SMS” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Send Sms” android:id=”@+id/btnSendSMS” android:layout_below=”@+id/editText2″ android:layout_centerHorizontal=”true” android:layout_marginTop=”48dp” /> </RelativeLayout> Following will be the content of res/values/strings.xml to define two new constants − <?xml version=”1.0″ encoding=”utf-8″?> <resources> <string name=”app_name”>tutorialspoint</string> </resources> Following is the default content of AndroidManifest.xml − <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.tutorialspoint” > <uses-permission android:name=”android.permission.SEND_SMS” /> <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”com.example.tutorialspoint.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 tutorialspoint 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 toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application. Now you can enter a desired mobile number and a text message to be sent on that number. Finally click on Send SMS button to send your SMS. Make sure your GSM/CDMA connection is working fine to deliver your SMS to its recipient. You can take a number of SMS separated by comma and then inside your program you will have to parse them into an array string and finally you can use a loop to send message to all the given numbers. That”s how you can write your own SMS client. Next section will show you how to use existing SMS client to send SMS. Using Built-in Intent to send SMS You can use Android Intent to send SMS by calling built-in SMS functionality of the Android. Following section explains different parts of our Intent object required to send an SMS. Intent Object – Action to send SMS You will use ACTION_VIEW action to launch an SMS client installed on your Android device. Following is simple syntax to create an intent with ACTION_VIEW action. Intent smsIntent = new Intent(Intent.ACTION_VIEW); Intent Object – Data/Type to send SMS To send an SMS you need to specify smsto: as URI using setData() method and data type will be to vnd.android-dir/mms-sms using setType() method as follows − smsIntent.setData(Uri.parse(“smsto:”)); smsIntent.setType(“vnd.android-dir/mms-sms”); Intent Object – Extra to send SMS Android has built-in support to add phone number and text message to send an SMS as follows − smsIntent.putExtra(“address”
Android – Alert Dialoges
Android – Alert Dialog ”; Previous Next A Dialog is small window that prompts the user to a decision or enter additional information. Some times in your application, if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use Alert Dialog. In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given below AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); Now you have to set the positive (yes) or negative (no) button using the object of the AlertDialogBuilder class. Its syntax is alertDialogBuilder.setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) alertDialogBuilder.setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) Apart from this , you can use other functions provided by the builder class to customize the alert dialog. These are listed below Sr.No Method type & description 1 setIcon(Drawable icon) This method set the icon of the alert dialog box. 2 setCancelable(boolean cancel able) This method sets the property that the dialog can be cancelled or not 3 setMessage(CharSequence message) This method sets the message to be displayed in the alert dialog 4 setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener) This method sets list of items to be displayed in the dialog as the content. The selected option will be notified by the listener 5 setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) This method Sets the callback that will be called if the dialog is cancelled. 6 setTitle(CharSequence title) This method set the title to be appear in the dialog After creating and setting the dialog builder , you will create an alert dialog by calling the create() method of the builder class. Its syntax is AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); This will create the alert dialog and will show it on the screen. Dialog fragment Before enter into an example we should need to know dialog fragment.Dialog fragment is a fragment which can show fragment in dialog box public class DialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { toast.makeText(this,”enter a text here”,Toast.LENTH_SHORT).show(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); }); // Create the AlertDialog object and return it return builder.create(); } } } List dialog It has used to show list of items in a dialog box.For suppose, user need to select a list of items or else need to click a item from multiple list of items.At this situation we can use list dialog. public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(Pick a Color) .setItems(R.array.colors_array, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // The ”which” argument contains the index position // of the selected item } }); return builder.create(); } Single-choice list dialog It has used to add single choice list to Dialog box.We can check or uncheck as per user choice. public Dialog onCreateDialog(Bundle savedInstanceState) { mSelectedItems = new ArrayList(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(“This is list choice dialog box”); .setMultiChoiceItems(R.array.toppings, null, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { // If the user checked the item, add it to the selected items mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { // Else, if the item is already in the array, remove it mSelectedItems.remove(Integer.valueOf(which)); } } }) // Set the action buttons .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // User clicked OK, so save the mSelectedItems results somewhere // or return them to the component that opened the dialog … } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { … } }); return builder.create(); } Example The following example demonstrates the use of AlertDialog in android. To experiment with this example , you need to run this on an emulator or an actual device. Steps Description 1 You will use Android studio to create an Android application and name it as My Application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add alert dialog code to launch the dialog. 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 4 No need to change default string constants. Android studio takes care of default strings at values/string.xml 5 Run the application and choose a running android device and install the application on it and verify the results. Here is the modified code of src/MainActivity.java package com.example.sairamkrishna.myapplication; import android.app.AlertDialog; import android.content.DialogInterface; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void open(View view){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage(“Are you sure, You wanted to make decision”); alertDialogBuilder.setPositiveButton(“yes”, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { Toast.makeText(MainActivity.this,”You clicked yes button”,Toast.LENGTH_LONG).show(); } }); alertDialogBuilder.setNegativeButton(“No”,new DialogInterface.OnClickListener() { Override public void onClick(DialogInterface dialog, int which) { finish(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } } Here is the modified code of 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:text=”Alert Dialog” 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=”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_alignRight=”@+id/textView2″ android:layout_alignEnd=”@+id/textView2″ android:layout_alignLeft=”@+id/textView” android:layout_alignStart=”@+id/textView” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Alert dialog” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_alignRight=”@+id/textView2″ android:layout_alignEnd=”@+id/textView2″ android:layout_marginTop=”42dp” android:onClick=”open” android:layout_alignLeft=”@+id/imageView” android:layout_alignStart=”@+id/imageView” /> </RelativeLayout> Here is ofStrings.xml <resources> <string name=”app_name”>My Application</string> </resources> Here is the default code 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.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. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your
Android – Phone Calls
Android – Phone Calls ”; Previous Next Android provides Built-in applications for phone calls, in some occasions we may need to make a phone call through our application. This could easily be done by using implicit Intent with appropriate actions. Also, we can use PhoneStateListener and TelephonyManager classes, in order to monitor the changes in some telephony states on the device. This chapter lists down all the simple steps to create an application which can be used to make a Phone Call. You can use Android Intent to make phone call by calling built-in Phone Call functionality of the Android. Following section explains different parts of our Intent object required to make a call. Intent Object – Action to make Phone Call You will use ACTION_CALL action to trigger built-in phone call functionality available in Android device. Following is simple syntax to create an intent with ACTION_CALL action Intent phoneIntent = new Intent(Intent.ACTION_CALL); You can use ACTION_DIAL action instead of ACTION_CALL, in that case you will have option to modify hardcoded phone number before making a call instead of making a direct call. Intent Object – Data/Type to make Phone Call To make a phone call at a given number 91-000-000-0000, you need to specify tel: as URI using setData() method as follows − phoneIntent.setData(Uri.parse(“tel:91-000-000-0000″)); The interesting point is that, to make a phone call, you do not need to specify any extra data or data type. Example Following example shows you in practical how to use Android Intent to make phone call to the given mobile number. To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work. Step Description 1 You will use Android studio IDE to create an Android application and name it as My Application under a package com.example.saira_000.myapplication. 2 Modify src/MainActivity.java file and add required code to take care of making a call. 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I”m adding a simple button to Call 91-000-000-0000 number 4 No need to define default string constants.Android studio takes care of default constants. 5 Modify AndroidManifest.xml as shown below 6 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 src/MainActivity.java. package com.example.saira_000.myapplication; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.buttonCall); button.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse(“tel:0377778888″)); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { return; } startActivity(callIntent); } }); } } Following will be the content of res/layout/activity_main.xml file − <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <Button android:id=”@+id/buttonCall” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”call 0377778888″ /> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants − <?xml version=”1.0″ encoding=”utf-8″?> <resources> <string name=”app_name”>My Application</string> </resources> Following is the default content of AndroidManifest.xml − <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.saira_000.myapplication” > <uses-permission android:name=”android.permission.CALL_PHONE” /> <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”com.example.saira_000.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 My Application 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 toolbar.Select your mobile device as an option and then check your mobile device which will display following screen − Now use Call button to make phone call as shown below − Print Page Previous Next Advertisements ”;
Android – Custom Components
Android – Custom Components ”; Previous Next Implementing own components in pre built-in components with extending subclass with own defined class Android offers a great list of pre-built widgets like Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView etc. which you can use directly in your Android application development, but there may be a situation when you are not satisfied with existing functionality of any of the available widgets. Android provides you with means of creating your own custom components which you can customized to suit your needs. If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods which will give you precise control over the appearance and function of a screen element. This tutorial explains you how to create custom Views and use them in your application using simple and easy steps. Example of Custom Components in Custom View hierarchy Creating a Simple Custom Component Step Description 1 You will use Android studio IDE to create an Android application and name it as myapplication under a package com.example.tutorialspoint7.myapplication as explained in the Hello World Example chapter. 2 Create an XML res/values/attrs.xml file to define new attributes along with their data type. 3 Create src/mainactivity.java file and add the code to define your custom component 4 Modify res/layout/activity_main.xml file and add the code to create Colour compound view instance along with few default attributes and new attributes. 5 Run the application to launch Android emulator and verify the result of the changes done in the application. Create the following attributes file called attrs.xml in your res/values folder. <?xml version=”1.0″ encoding=”utf-8″?> <resources> <declare-styleable name=”TimeView”> <declare-styleable name=”TimeView”> <attr name=”title” format=”string” /> <attr name=”setColor” format=”boolean”/> </declare-styleable> </declare-styleable> </resources> Change the layout file used by the activity to the following. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” xmlns:custom=”http://schemas.android.com/apk/res-auto” android:layout_width=”match_parent” android:layout_height=”match_parent” tools:context=”.MainActivity” > <com.example.tutorialspoint7.myapplication.TimeView android:id=”@+id/timeView” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:textColor=”#fff” android:textSize=”40sp” custom:title=”my time view” custom:setColor=”true” /> <TextView android:layout_width=”match_parent” android:layout_height=”wrap_content” android:id=”@+id/simple” android:layout_below=”@id/timeView” android:layout_marginTop=”10dp” /> </RelativeLayout> Create the following java file called timeview for your compound view. package com.example.tutorialspoint7.myapplication; /** * Created by TutorialsPoint7 on 9/14/2016. */ import java.text.SimpleDateFormat; import java.util.Calendar; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.util.AttributeSet; import android.widget.TextView; public class TimeView extends TextView { private String titleText; private boolean color; public TimeView(Context context) { super(context); setTimeView(); } public TimeView(Context context, AttributeSet attrs) { super(context, attrs); // retrieved values correspond to the positions of the attributes TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TimeView); int count = typedArray.getIndexCount(); try{ for (int i = 0; i < count; ++i) { int attr = typedArray.getIndex(i); // the attr corresponds to the title attribute if(attr == R.styleable.TimeView_title) { // set the text from the layout titleText = typedArray.getString(attr); setTimeView(); } else if(attr == R.styleable.TimeView_setColor) { // set the color of the attr “setColor” color = typedArray.getBoolean(attr, false); decorateText(); } } } // the recycle() will be executed obligatorily finally { // for reuse typedArray.recycle(); } } public TimeView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setTimeView(); } private void setTimeView() { // has the format hour.minuits am/pm SimpleDateFormat dateFormat = new SimpleDateFormat(“hh.mm aa”); String time = dateFormat.format(Calendar.getInstance().getTime()); if(this.titleText != null ) setText(this.titleText+” “+time); else setText(time); } private void decorateText() { // when we set setColor attribute to true in the XML layout if(this.color == true){ // set the characteristics and the color of the shadow setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250)); setBackgroundColor(Color.CYAN); } else { setBackgroundColor(Color.RED); } } } Change your Main activity java file to the following code and run your application. package com.example.tutorialspoint7.myapplication; import android.os.Bundle; import android.widget.TextView; import android.app.Activity; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView simpleText = (TextView) findViewById(R.id.simple); simpleText.setText(“That is a simple TextView”); } } The running application should look like the following screen shot. Print Page Previous Next Advertisements ”;
Android – Drag and Drop
Android – Drag and Drop ”; Previous Next Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. As of API 11 drag and drop of view onto other views or view groups is supported.The framework includes following three important components to support drag & drop functionality − Drag event class. Drag listeners. Helper methods and classes. The Drag/Drop Process There are basically four steps or states in the drag and drop process − Started − This event occurs when you start dragging an item in a layout, your application calls startDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow. The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device. Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout. To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED. Continuing − The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object”s appearance in response to the event or can react by highlighting its View. The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View. Dropped − The user releases the dragged item within the bounding box of a View. The system sends the View object”s listener a drag event with action type ACTION_DROP. Ended − Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over. The DragEvent Class The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process. Constants Following are all constants integers available as a part of DragEvent class. Sr.No. Constants & Description 1 ACTION_DRAG_STARTED Signals the start of a drag and drop operation. 2 ACTION_DRAG_ENTERED Signals to a View that the drag point has entered the bounding box of the View. 3 ACTION_DRAG_LOCATION Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object”s bounding box. 4 ACTION_DRAG_EXITED Signals that the user has moved the drag shadow outside the bounding box of the View. 5 ACTION_DROP Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View. 6 ACTION_DRAG_ENDED Signals to a View that the drag and drop operation has concluded. Methods Following are few important and most frequently used methods available as a part of DragEvent class. Sr.No. Constants & Description 1 int getAction() Inspect the action value of this event.. 2 ClipData getClipData() Returns the ClipData object sent to the system as part of the call to startDrag(). 3 ClipDescription getClipDescription() Returns the ClipDescription object contained in the ClipData. 4 boolean getResult() Returns an indication of the result of the drag and drop operation. 5 float getX() Gets the X coordinate of the drag point. 6 float getY() Gets the Y coordinate of the drag point. 7 String toString() Returns a string representation of this DragEvent object. Listening for Drag Event If you want any of your views within a Layout should respond Drag event then your view either implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a callback method for View object. If this occurs, the system first calls the listener and then defined callback as long as listener returns true. The combination of the onDragEvent(DragEvent) method and View.OnDragListener is analogous to the combination of the onTouchEvent() and View.OnTouchListener used with touch events in old versions of Android. Starting a Drag Event You start with creating a ClipData and ClipData.Item for the data being moved. As part of the ClipData object, supply metadata that is stored in a ClipDescription object within the ClipData. For a drag and drop operation that does not represent data movement, you may want to use null instead of an actual object. Next either you can extend extend View.DragShadowBuilder to create a drag shadow for dragging the view or simply you can use View.DragShadowBuilder(View) to create a default drag shadow that”s the same size as the View argument passed to it, with the touch point centered in the drag shadow. Example Following example shows the functionality of a simple Drag & Drop using View.setOnLongClickListener(), View.setOnTouchListener()and View.OnDragEventListener(). Step Description 1 You will use Android studio IDE to create an Android application and name it as My Application under a package com.example.saira_000.myapplication. 2 Modify src/MainActivity.java file and add the code to define event listeners as well as a call back methods for the logo image used in the example. 3 Copy image abc.png in res/drawable-* folders. You can use images with different resolution in case you want to provide them for different devices. 4 Modify layout XML file res/layout/activity_main.xml to define default view of the logo images. 5 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 src/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.saira_000.myapplication; import android.app.Activity;
Android – Animations
Android – Animations ”; Previous Next Animation is the process of creating motion and shape change Animation in android is possible from many ways. In this chapter we will discuss one easy and widely used way of making animation called tweened animation. Tween Animation Tween Animation takes some parameters such as start value , end value, size , time duration , rotation angle e.t.c and perform the required animation on that object. It can be applied to any type of object. So in order to use this , android has provided us a class called Animation. In order to perform animation in android , we are going to call a static function loadAnimation() of the class AnimationUtils. We are going to receive the result in an instance of Animation Object. Its syntax is as follows − Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.myanimation); Note the second parameter. It is the name of the our animation xml file. You have to create a new folder called anim under res directory and make an xml file under anim folder. This animation class has many useful functions which are listed below − Sr.No Method & Description 1 start() This method starts the animation. 2 setDuration(long duration) This method sets the duration of an animation. 3 getDuration() This method gets the duration which is set by above method 4 end() This method ends the animation. 5 cancel() This method cancels the animation. In order to apply this animation to an object , we will just call the startAnimation() method of the object. Its syntax is − ImageView image1 = (ImageView)findViewById(R.id.imageView1); image.startAnimation(animation); Example The following example demonstrates the use of Animation in android. You would be able to choose different type of animation from the menu and the selected animation will be applied on an imageView on the screen. To experiment with this example , you need to run this on an emulator or an actual device. Steps Description 1 You will use Android studio IDE to create an Android application and name it as My Application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add animation code 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 4 Create a new folder under res directory and call it anim. Confim it by visiting res/anim 5 Right click on anim and click on new and select Android XML file You have to create different files that are listed below. 6 Create files myanimation.xml,clockwise.xml,fade.xml,move.xml,blink.xml,slide.xml and add the XML code. 7 No need to change default string constants. Android studio takes care of default constants at values/string.xml. 8 Run the application and choose a running android device and install the application on it and verify the results. Here is the modified code of MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void clockwise(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.myanimation); image.startAnimation(animation); } public void zoom(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.clockwise); image.startAnimation(animation1); } public void fade(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade); image.startAnimation(animation1); } public void blink(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink); image.startAnimation(animation1); } public void move(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move); image.startAnimation(animation1); } public void slide(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide); image.startAnimation(animation1); } } Here is the modified code of res/layout/activity_main.xml. Here abc indicates about logo of tutorialspoint <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=”Alert Dialog” 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=”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_alignRight=”@+id/textView2″ android:layout_alignEnd=”@+id/textView2″ android:layout_alignLeft=”@+id/textView” android:layout_alignStart=”@+id/textView”/> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”zoom” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_marginTop=”40dp” android:onClick=”clockwise”/> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”clockwise” android:id=”@+id/button2″ android:layout_alignTop=”@+id/button” android:layout_centerHorizontal=”true” android:onClick=”zoom”/> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”fade” android:id=”@+id/button3″ android:layout_alignTop=”@+id/button2″ android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:onClick=”fade”/> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”blink” android:onClick=”blink” android:id=”@+id/button4″ android:layout_below=”@+id/button” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”move” android:onClick=”move” android:id=”@+id/button5″ android:layout_below=”@+id/button2″ android:layout_alignRight=”@+id/button2″ android:layout_alignEnd=”@+id/button2″ android:layout_alignLeft=”@+id/button2″ android:layout_alignStart=”@+id/button2″ /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”slide” android:onClick=”slide” android:id=”@+id/button6″ android:layout_below=”@+id/button3″ android:layout_toRightOf=”@+id/textView” android:layout_toEndOf=”@+id/textView” /> </RelativeLayout> Here is the code of res/anim/myanimation.xml. <?xml version=”1.0″ encoding=”utf-8″?> <set xmlns:android=”http://schemas.android.com/apk/res/android”> <scale xmlns:android=”http://schemas.android.com/apk/res/android” android:fromXScale=”0.5″ android:toXScale=”3.0″ android:fromYScale=”0.5″ android:toYScale=”3.0″ android:duration=”5000″ android:pivotX=”50%” android:pivotY=”50%” > </scale> <scale xmlns:android=”http://schemas.android.com/apk/res/android” android:startOffset=”5000″ android:fromXScale=”3.0″ android:toXScale=”0.5″ android:fromYScale=”3.0″ android:toYScale=”0.5″ android:duration=”5000″ android:pivotX=”50%” android:pivotY=”50%” > </scale> </set> Here is the code of res/anim/clockwise.xml. <?xml version=”1.0″ encoding=”utf-8″?> <set xmlns:android=”http://schemas.android.com/apk/res/android”> <rotate xmlns:android=”http://schemas.android.com/apk/res/android” android:fromDegrees=”0″ android:toDegrees=”360″ android:pivotX=”50%” android:pivotY=”50%” android:duration=”5000″ > </rotate> <rotate xmlns:android=”http://schemas.android.com/apk/res/android” android:startOffset=”5000″ android:fromDegrees=”360″ android:toDegrees=”0″ android:pivotX=”50%” android:pivotY=”50%” android:duration=”5000″ > </rotate> </set> Here is the code of res/anim/fade.xml. <?xml version=”1.0″ encoding=”utf-8″?> <set xmlns:android=”http://schemas.android.com/apk/res/android” android:interpolator=”@android:anim/accelerate_interpolator” > <alpha android:fromAlpha=”0″ android:toAlpha=”1″ android:duration=”2000″ > </alpha> <alpha android:startOffset=”2000″ android:fromAlpha=”1″ android:toAlpha=”0″ android:duration=”2000″ > </alpha> </set> Here is the code of res/anim/blink.xml. <?xml version=”1.0″ encoding=”utf-8″?> <set xmlns:android=”http://schemas.android.com/apk/res/android”> <alpha android:fromAlpha=”0.0″ android:toAlpha=”1.0″ android:interpolator=”@android:anim/accelerate_interpolator” android:duration=”600″ android:repeatMode=”reverse” android:repeatCount=”infinite”/> </set> Here is the code of res/anim/move.xml. <?xml version=”1.0″ encoding=”utf-8″?> <set xmlns:android=”http://schemas.android.com/apk/res/android” android:interpolator=”@android:anim/linear_interpolator” android:fillAfter=”true”> <translate android:fromXDelta=”0%p” android:toXDelta=”75%p” android:duration=”800″ /> </set> Here is the code of res/anim/slide.xml <?xml version=”1.0″ encoding=”utf-8″?> <set xmlns:android=”http://schemas.android.com/apk/res/android” android:fillAfter=”true” > <scale android:duration=”500″ android:fromXScale=”1.0″ android:fromYScale=”1.0″ android:interpolator=”@android:anim/linear_interpolator” android:toXScale=”1.0″ android:toYScale=”0.0″ /> </set> Here is the modified code of res/values/string.xml. <resources> <string name=”app_name”>My Application</string> </resources> Here is the default code 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.animation.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. 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 toolbar. Android studio will display following images Select zoom button, it will display following screen − Now select slide button, it will display following screen Now select move button, it will display following screen Now the clockwise button, it will display following screen Now Fade button, it will display following screen Note − If you run it in emulator , you may not
Android – Emulator
Android – Emulator ”; Previous Next The Android SDK includes a virtual mobile device emulator that runs on your computer. The emulator lets you prototype, develop and test Android applications without using a physical device. In this chapter we are going to explore different functionalities in the emulator that are present in the real android device. Creating AVD If you want to emulate a real device, first crate an AVD with the same device configurations as real device, then launch this AVD from AVD manager. Changing Orientation Usually by default when you launch the emulator, its orientation is vertical, but you can change it orientation by pressing Ctrl+F11 key from keyboard. First launch the emulator. It is shown in the picture below − Once it is launched, press Ctrl+F11 key to change its orientation. It is shown below − Emulator Commands. Apart from just orientation commands, there are other very useful commands of emulator that you should keep in mind while using emulator. They are listed below − Sr.No Command & description 1 Home Shifts to main screen 2 F2 Toggles context sensitive menu 3 F3 Bring out call log 4 F4 End call 5 F5 Search 6 F6 Toggle trackball mode 7 F7 Power button 8 F8 Toggle data network 9 Ctrl+F5 Ring Volume up 10 Ctrl+F6 Ring Volume down Emulator – Sending SMS You can emulate sending SMS to your emulator. There are two ways to do that. You can do that from DDMS which can be found in Android studio, or from Telnet.(Network utility found in windows). Sending SMS through Telnet. Telnet is not enabled by default in windows. You have to enable it to use it. Once enabled you can go to command prompt and start telnet by typing telnet. In order to send SMS , note down the AVD number which can be found on the title bar of the emulator. It could be like this 5554 e.t.c. Once noted , type this command in command prompt. telnet localhost 5554 Press enter when you type the command. It is shown below in the figure. You will see that you are now connected to your emulator. Now type this command to send message. sms send 1234 “hello” Once you type this command , hit enter. Now look at the AVD. You will receive a notification displaying that you got a new text message. It is shown below − Emulator – Making Call You can easily make phone calls to your emulator using telent client. You need to connect to your emulator from telnet. It is discussed in the sending sms topic above. After that you will type this command in the telent window to make a call. Its syntax is given below − gsm call 1234 Once you type this command , hit enter. Now look at the AVD. You will receive a call from the number your put in the command. It is shown below − Emulator – Transferring files You can easily transfer files into the emulator and vice versa. In order to do that, you need to select the DDMS utility in Android studio. After that select the file explorer tab. It is shown below − Browse through the explorer and make new folder , view existing contents e.t.c. Print Page Previous Next Advertisements ”;
Android – UI Controls
Android – UI Controls ”; Previous Next Input controls are the interactive components in your app”s user interface. Android provides a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check box, zoom buttons, toggle buttons, and many more. UI Elements A View is an object that draws something on the screen that the user can interact with and a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the layout of the user interface. You define your layout in an XML file which offers a human-readable structure for the layout, similar to HTML. For example, a simple vertical layout with a text view and a button looks like this − <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <TextView android:id=”@+id/text” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”I am a TextView” /> <Button android:id=”@+id/button” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”I am a Button” /> </LinearLayout> Android UI Controls There are number of UI controls provided by Android that allow you to build the graphical user interface for your app. Sr.No. UI Control & Description 1 TextView This control is used to display text to the user. 2 EditText EditText is a predefined subclass of TextView that includes rich editing capabilities. 3 AutoCompleteTextView The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion suggestions automatically while the user is typing. 4 Button A push-button that can be pressed, or clicked, by the user to perform an action. 5 ImageButton An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its children. This shows a button with an image (instead of text) that can be pressed or clicked by the user. 6 CheckBox An on/off switch that can be toggled by the user. You should use check box when presenting users with a group of selectable options that are not mutually exclusive. 7 ToggleButton An on/off button with a light indicator. 8 RadioButton The RadioButton has two states: either checked or unchecked. 9 RadioGroup A RadioGroup is used to group together one or more RadioButtons. 10 ProgressBar The ProgressBar view provides visual feedback about some ongoing tasks, such as when you are performing a task in the background. 11 Spinner A drop-down list that allows users to select one value from a set. 12 TimePicker The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode. 13 DatePicker The DatePicker view enables users to select a date of the day. Create UI Controls Input controls are the interactive components in your app”s user interface. Android provides a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check box, zoom buttons, toggle buttons, and many more. As explained in previous chapter, a view object may have a unique ID assigned to it which will identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is − android:id=”@+id/text_id” To create a UI Control/View/Widget you will have to define a view/widget in the layout file and assign it a unique ID as follows − <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <TextView android:id=”@+id/text_id” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”I am a TextView” /> </LinearLayout> Then finally create an instance of the Control object and capture it from the layout, use the following − TextView myText = (TextView) findViewById(R.id.text_id); Print Page Previous Next Advertisements ”;
Android – Loading Spinner
Android – Loading Spinner ”; Previous Next You can show progress of a task in android through loading progress bar. The progress bar comes in two shapes. Loading bar and Loading Spinner. In this chapter we will discuss spinner. Spinner is used to display progress of those tasks whose total time of completion is unknown. In order to use that, you just need to define it in the xml like this. <ProgressBar android:id=”@+id/progressBar1″ style=”?android:attr/progressBarStyleLarge” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_centerHorizontal=”true” /> After defining it in xml, you have to get its reference in java file through ProgressBar class. Its syntax is given below − private ProgressBar spinner; spinner = (ProgressBar)findViewById(R.id.progressBar1); After that you can make its disappear , and bring it back when needed through setVisibility Method. Its syntax is given below − spinner.setVisibility(View.GONE); spinner.setVisibility(View.VISIBLE); Apart from these Methods, there are other methods defined in the ProgressBar class , that you can use to handle spinner more effectively. Sr.No Method & description 1 isIndeterminate() Indicate whether this progress bar is in indeterminate mode 2 postInvalidate() Cause an invalidate to happen on a subsequent cycle through the event loop 3 setIndeterminate(boolean indeterminate) Change the indeterminate mode for this progress bar 4 invalidateDrawable(Drawable dr) Invalidates the specified Drawable 5 incrementSecondaryProgressBy(int diff) Increase the progress bar”s secondary progress by the specified amount 6 getProgressDrawable() Get the drawable used to draw the progress bar in progress mode Example Here is an example demonstrating the use of ProgressBar to handle spinner. It creates a basic application that allows you to turn on the spinner on clicking the button. 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 Need to create a xml file in drawable folder.it contains shape and rotate information about the progress bar 5 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.ProgressBar; public class MainActivity extends Activity { Button b1; private ProgressBar spinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); spinner=(ProgressBar)findViewById(R.id.progressBar); spinner.setVisibility(View.GONE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { spinner.setVisibility(View.VISIBLE); } }); } } 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=”Progress Dialog” 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=”download” android:id=”@+id/button” android:layout_below=”@+id/imageView” 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/textView” android:layout_centerHorizontal=”true” /> <ProgressBar style=”?android:attr/progressBarStyleLarge” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/progressBar” android:progressDrawable=”@drawable/circular_progress_bar” android:layout_below=”@+id/button” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:layout_alignLeft=”@+id/textview” android:layout_alignStart=”@+id/textview” android:layout_alignParentBottom=”true” /> </RelativeLayout> Following is the content of the res/drawable/circular_progress_bar.xml. <?xml version=”1.0″ encoding=”utf-8″?> <rotate xmlns:android=”http://schemas.android.com/apk/res/android” android:fromDegrees=”90″ android:pivotX=”50%” android:pivotY=”50%” android:toDegrees=”360″> <shape android:innerRadiusRatio=”3″ android:shape=”ring” android:thicknessRatio=”7.0″> <gradient android:centerColor=”#007DD6″ android:endColor=”#007DD6″ android:startColor=”#007DD6″ android:angle=”0″ android:type=”sweep” android:useLevel=”false” /> </shape> </rotate> 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 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 click on the load spinner button to turn on the loading spinner. It is shown in the image below − Print Page Previous Next Advertisements ”;