Android Example 2
Android Example 2
Android - PHP/MYSQL
In this chapter , we are going to explain, how you can integrate PHP and
MYSQL with your android application. This is very useful in case you have a
webserver, and you want to access its data on your android application.
PHP - MYSQL
Creating Database
MYSQL database can be created easily using this simple script. The CREATE
DATABASE statement creates the database.
<?php
$con=mysqli_connect("example.com","username","password");
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
}
?>
Creating Tables
Once database is created, its time to create some tables in the database.
The CREATE TABLE statement creates the database.
<?php
$con=mysqli_connect("example.com","username","password","my_db");
$sql="CREATE TABLE table1(Username CHAR(30),Password CHAR(30),Role
CHAR(30))";
if (mysqli_query($con,$sql)) {
echo "Table have been created successfully";
}
?>
<?php
$con=mysqli_connect("example.com","username","password","my_db");
$sql="INSERT INTO table1 (FirstName, LastName, Age) VALUES ('admin',
'admin','adminstrator')";
if (mysqli_query($con,$sql)) {
echo "Values have been inserted successfully";
}
?>
<?php
$con=mysqli_connect("example.com","username","password","database name");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT Role FROM table1 where
Username='$username'
and Password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
The second method is to use POST method. The only change in the above
script is to replace $_GET with $_POST. In Post method, the variables are
not passed through URL.
request.setURI(new URI(link));
After that you need to call execute method of HttpClient class and receive
it in a HttpResponse object. After that you need to open streams to receive
the data.
The last thing you need to do is to write this data to the link. After writing,
you need to open stream to receive the responded data.
InputStreamReader(conn.getInputStream()));
Example
The below example is a complete example of connecting your android
application with MYSQL database via PHP page. It creates a basic
application that allows you to login using GET and POST method.
In this example a database with the name of temp has been created at
000webhost.com. In that database, a table has been created with the name
of table1. This table has three fields. (Username, Password, Role). The table
has only one record which is ("admin","admin","administrator").
The php page has been given below which takes parameters by post
method.
<?php
$con=mysqli_connect("mysql10.000webhost.com","username","password","db_name")
;
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT Role FROM table1 where
Username='$username' and Password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
Android Part
To experiment with this example , you need to run this on an actual device
on which wifi internet is connected.
Steps Description
1 You will use Android studio IDE to create an Android application and name
it as PHPMYSQL under a package com.example.phpmysql.
7 Run the application and choose a running android device and install the
application on it and verify the results.
package com.example.phpmysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
@Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link =
"http://myphpmysqlweb.hostei.com/login.php?username="+username+"&
password="+password;
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
in.close();
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
} else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://myphpmysqlweb.hostei.com/loginpost.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" +
URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
URLEncoder.encode(password, "UTF-8");
conn.setDoOutput(true);
OutputStreamWriter wr = new
OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
@Override
Add the following content to build.gradle and rebuild the whole project.
android {
useLibrary 'org.apache.http.legacy'
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="25dp"
android:ems="10"
android:inputType="textPassword" >
</EditText>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="44dp"
android:ems="10" >
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="@string/Username" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="@string/App"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView5"
android:layout_alignLeft="@+id/textView6"
android:text="@string/Role"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="10sp" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView6"
android:layout_marginTop="27dp"
android:layout_toLeftOf="@+id/editText1"
android:text="@string/LoginRole" />
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView6"
android:layout_alignLeft="@+id/textView5"
android:layout_marginBottom="27dp"
android:text="@string/method" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView8"
android:layout_below="@+id/button1"
android:layout_marginTop="86dp"
android:text="@string/LoginStatus" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView4"
android:layout_centerHorizontal="true"
android:text="@string/Status"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="10sp" />
<TextView
android:id="@+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView8"
android:layout_alignLeft="@+id/textView6"
android:text="@string/Choose"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="10sp" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/textView6"
android:onClick="loginPost"
android:text="@string/LoginPost" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button2"
android:layout_alignBottom="@+id/button2"
android:layout_alignLeft="@+id/textView2"
android:onClick="login"
android:text="@string/LoginGet" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="@string/Password" />
</RelativeLayout>
<string name="app_name">PHPMYSQL</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Username">Username</string>
<string name="Password">Password</string>
<string name="LoginGet">Login - Get</string>
<string name="LoginPost">Login - Post</string>
<string name="App">Login Application</string>
<string name="LoginStatus">Login Status</string>
<string name="LoginRole">Login Role</string>
<string name="Status">Not login</string>
<string name="Role">Not assigned</string>
<string name="method">Login Method</string>
<string name="Choose">Choose Method</string>
</resources>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.phpmysql" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.phpmysql.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 PHPMYSQL 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. 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 −
Now press the Get button and wait a few seconds and response will be
downloaded and will be shown to you. In this case, the response is the
ROLE that is fetched in case of admin as username and password.It is
shown in the figure below −
Now again press the POST button and same result would appear. It is
shown in the figure below −
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.
Now you can set some properties of this dialog. Such as, its style, its text
etc.
Apart from these methods, there are other methods that are provided by
the ProgressDialog class
1
getMax()
2
incrementProgressBy(int diff)
This method increments the progress bar by the difference of value passed
as a parameter.
3
setIndeterminate(boolean indeterminate)
4
setMax(int max)
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)
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
package com.example.sairamkrishna.myapplication.
4 Run the application and choose a running android device and install the
application on it and verify the results.
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;
<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>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<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 −
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.
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!--Permissions-->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />
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 −
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 −
addCircle(CircleOptions options)
1
This method add a circle to the map
addPolygon(PolygonOptions options)
2
This method add a polygon to the map
addTileOverlay(TileOverlayOptions options)
3
This method add tile overlay to the map
animateCamera(CameraUpdate update)
4
This method Moves the map according to the update with an animation
clear()
5
This method removes everything from the map.
getMyLocation()
6
This method returns the currently displayed user location.
moveCamera(CameraUpdate update)
setTrafficEnabled(boolean enabled)
8
This method Toggles the traffic layer on or off.
snapshot(GoogleMap.SnapshotReadyCallback callback)
9
This method Takes a snapshot of the map
stopAnimation()
10
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.
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
<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" />
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;
@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);
}
/**
@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));
}
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
<!--
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>
Previous Page
Next Page
SmsManager API
Apart from the above method, there are few other important functions
available in SmsManager class. These methods are listed below −
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()
3
void sendDataMessage(String destinationAddress, String
scAddress, short destinationPort, byte[] data, PendingIntent
sentIntent, PendingIntent deliveryIntent)
4
void sendMultipartTextMessage(String destinationAddress, String
scAddress, ArrayList<String> parts, ArrayList<PendingIntent>
sentIntents, ArrayList<PendingIntent> deliveryIntents)
5
void sendTextMessage(String destinationAddress, String
scAddress, String text, PendingIntent sentIntent, PendingIntent
deliveryIntent)
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.
6 Run the application to launch Android emulator and verify the result of the
changes done in the application.
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
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);
<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"
<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>
<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>
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.
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
Here address and sms_body are case sensitive and should be specified in small
characters only. You can specify more than one number in single string but
separated by semi-colon (;).
Example
Following example shows you in practical how to use Intent object to launch
SMS client to send an SMS to the given recipients.
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.
6 Run the application to launch Android emulator and verify the result of the
changes done in the application.
package com.example.tutorialspoint;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" , new String ("01234"));
smsIntent.putExtra("sms_body" , "Test ");
try {
startActivity(smsIntent);
finish();
Log.i("Finished sending SMS...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
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="Drag and Drop Example"
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="30dp"
android:textColor="#ff14be3c" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_marginTop="48dp"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Compose SMS"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="54dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
</RelativeLayout>
</resources>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint" >
<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>
Select your mobile device as an option and then check your mobile device
which will display following screen −
Now use Compose SMS button to launch Android built-in SMS clients which
is shown below −
You can modify either of the given default fields and finally use send SMS
button to send your SMS to the mentioned recipient.