0% found this document useful (0 votes)
18 views

Lecture 7 - Networking, SMS and Toast Notification

Uploaded by

Night Cloud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Lecture 7 - Networking, SMS and Toast Notification

Uploaded by

Night Cloud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Mobile Applications Development

University of Science and Technology


Faculty of Computer Science & Information Technology
Department of Computer science and Information and Communication Technology

Lecture (8)

Networking, SMS and Mr. Mohanad Shahata


Toast notification

This content has been cited from Mr. Kirolos Tharwat’s content.
Networking

2
Networking

•Android lets your application connect to the


internet or any other local network and
allows you to perform network operations.

•A device can have various types of network


connections. This lecture focuses on using
either a Wi-Fi or a mobile network
connection.

3
Checking Network Connection

•Before you perform any network operations, you


must first check that are you connected to that
network or internet e.t.c. For this android
provides ConnectivityManager class. You need
to instantiate an object of this class by calling
getSystemService() method. Its syntax is given
below:

ConnectivityManager check = (ConnectivityManager)


this.context.getSystemService(Context.CONNECTIVITY_SERVICE);

4
• Once you instantiate the object of
ConnectivityManager class, you can use
getAllNetworkInfo method to get the information of all
the networks. This method returns an array of
NetworkInfo. So you have to receive it like this.
NetworkInfo[] info = check.getAllNetworkInfo();

• The last thing you need to do is to check Connected


State of the network. Its syntax is given below:

for (int i = 0; i<info.length; i++){


if (info[i].getState() == NetworkInfo.State.CONNECTED){
Toast.makeText(context, "Internet is connected
Toast.LENGTH_SHORT).show();
}
} 5
SMS

6
Sending SMS
•In android, we can send SMS from our android
application in two ways either by
using SMSManager API or Intent based on our
requirements.

•If we use SMSManager API, it will directly send


SMS from our application.
• In case if we use Intent with proper action
(ACTION_VIEW), it will invoke a built-in SMS
app to send SMS from our application.

7
1. send SMS using SMSManager API
In android, to send SMS using SMSManager API we
need to write the code like as shown below.

SmsManager smgr= SmsManager.getDefault();


smgr.sendTextMessage(MobileNumber,null,Message,null,null);

8
Following are the five arguments to the
sendTextMessage() method:

sendTextMessage(destAddress,​ scAddress,​ text,​ sentIntent,​ deliveryIntent )

➤ destAddress : Phone number of the recipient


➤ scAddress : Service center address; use null for default SMSC
➤ text : Content of the SMS message
➤ sentIntent : Pending intent to invoke when the message is sent.
➤ deliveryIntent : Pending intent to invoke when the message has
been delivered.

9
•SMSManager API required SEND_SMS permission in
our android manifest to send SMS.

•Following is the code snippet to set SEND_SMS perm


issions in manifest file.

< uses-permission android:name="android.permission.SEND


_SMS" />

10
Example to send SMS using SMSManager API
• Create a new android application using android studio and give names
as SendSMSExample.
• activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <TextView
<LinearLayout xmlns:android="http://schemas.android android:id="@+id/secTxt"
.com/apk/res/android" android:layout_width="wrap_content"
android:orientation="vertical" android:layout_width android:layout_height="wrap_content"
="match_parent" android:text="Message"
android:layout_height="match_parent"> android:layout_marginLeft="100dp" />
<TextView <EditText
android:id="@+id/fstTxt" android:id="@+id/msgTxt"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="100dp" android:layout_marginLeft="100dp"
android:layout_marginTop="150dp" android:ems="10" />
android:text="Mobile No" /> <Button
<EditText android:id="@+id/btnSend"
android:id="@+id/mblTxt" android:layout_width="wrap_content"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp"
android:layout_marginLeft="100dp" android:text="Send SMS" />
android:ems="10"/> </LinearLayout>
11
Example to send SMS using SMSManager API
• Now open our main activity file MainActivity.java from \src\main\java\com.
tutlane.sendsmsexample pat and write the code like as shown below
• MainActivity.java
package com.tutlane.sendsmsexample; txtMobile = (EditText)findViewById(R.id.mblTxt);
import android.content.Intent; txtMessage = (EditText)findViewById(R.id.msgTxt);
import android.net.Uri; btnSms = (Button)findViewById(R.id.btnSend);
import android.provider.Telephony;
import android.support.v7.app.AppCompatActivity;
btnSms.setOnClickListener(new View.OnClickListener() {
import android.os.Bundle; @Override
import android.telephony.SmsManager; public void onClick(View v) {
import android.view.View; try{
import android.widget.*; SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(txtMobile.getText().toStri
public ng(),null,txtMessage.getText().toString(),null,null);
class MainActivity extends AppCompatActivity {
Toast.makeText(MainActivity.this, "SMS Sent
private EditText txtMobile; Successfully", Toast.LENGTH_SHORT).show();
private EditText txtMessage; }
private Button btnSms; catch (Exception e){
@Override Toast.makeText(MainActivity.this, "SMS Failed to
Send, Please try again", Toast.LENGTH_SHORT).show();
} }
protected void onCreate(Bundle }
savedInstanceState) { });
super.onCreate(savedInstanceState); } 12
setContentView(R.layout.activity_main);
Example to send SMS using SMSManager API
• If you observe above code, we are sending SMS using SMSManager API on
button click. As discussed, we need to add a SEND_SMS permission in our
android manifest.
• Now open android manifest file (AndroidManifest.xml) and write the code like
as shown below AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <activity android:name=".MainActiv
<manifest xmlns:android="http://schemas.android.co
ity">
m/apk/res/android"
package="com.tutlane.sendsmsexample"> <intent-filter>
<uses- <action android:name="andr
permission android:name="android.permission.SEND_ oid.intent.action.MAIN" />
SMS"/>
<category android:name="an
<application
android:allowBackup="true" droid.intent.category.LAUNCHER" />
android:icon="@mipmap/ic_launcher" </intent-filter>
android:label="@string/app_name" </activity>
android:roundIcon="@mipmap/ic_launcher_roun
</application>
d"
android:supportsRtl="true" </manifest>
android:theme="@style/AppTheme">

If you observe above AndroidManifest.xml file, we added 13


Output of Android Send SMS Example
• When we run above program in android studio we will get the result like
as shown below.

Once you enter all details and click on Send SMS button it will send SMS and show
the alert message like as mentioned in above image. The above example we
implemented using SMSManager API 14
2. Sending SMS using Intent
• In android, Intent is a messaging object which is used to request an
action from another app component such as activities, services,
broadcast , receivers, and content providers.
• To send SMS using the Intent object, we need to write the code like as
shown below.

Intent sInt = new Intent(Intent.ACTION_VIEW);


sInt.putExtra("address", new String[]{txtMobile.getText().toString()});
sInt.putExtra("sms_body",txtMessage.getText().toString());
sInt.setType("vnd.android-dir/mms-sms");

• Even for Intent, it required a SEND_SMS permission in our android manifest to s


end SMS. Following is the code snippet to set SEND_SMS permissions in manife
st file.
< uses-permission android:name="android.permission.SEND_SMS" />

15
Using Implicit Intents (ACTION_VIEW)
• Using Android implicit intents we can display a list of
SMS client apps that the user already has on his phone
that he can use.
String phoneNo = "123456789";
String messageBody = "Hello SMS";

Intent smsIntent = new Intent(Intent.ACTION_VIEW);


smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", phoneNo );
smsIntent.putExtra("sms_body", messageBody );

startActivity(smsIntent);

16
Using Implicit Intents (ACTION_SENDTO )

String phoneNo = "123456789";


String messageBody = "Hello SMS";

Uri uri = Uri.parse("smsto:" + phoneNo );


Intent smsIntent = new Intent(Intent.ACTION_SENDTO, uri);
smsIntent.putExtra("sms_body", messageBody );

startActivity(smsIntent);

17
Receiving SMS

• Besides sending SMS messages from your Android


applications, you can also receive incoming SMS
messages from within your application by using a
BroadcastReceiver object.

• This is useful when you want your application to


perform an action when a certain SMS message is
received.

18
Receiving SMS
Add the following statements to the AndroidManifest.xml
file:
<application>
. . . .
<receiver android:name=”.SMSReceiver”>

<intent-filter>


<action android:name=
“android.provider.Telephony.SMS_RECEIVED” />

</intent-filter>
</receiver>

</application>

<uses-permission android:name=”android.permission.RECEIVE_SMS” />

19
BroadcastReceiver

The BroadcastReceiver class enables your


application to receive intents sent by other
applications using the sendBroadcast() method.

Essentially, it enables your application to handle


events raised by other applications.

When an intent is received, the onReceive()


method is called. You need to override this method.

20
BroadcastReceiver
public class SMSReceiver extends BroadcastReceiver
{
​@Override
​public void onReceive(Context context, Intent intent)
{
....
}
}
You also need to set the launchMode attribute of the <activity> element
in the AndroidManifest.xml file to singleTask:
<activity android:name=”.MainActivity”
android:label=”@string/app_name”
android:launchMode=”singleTask” >

21
Toast Notification

22
Toast Notification
• A toast notification communicates messages to the
user. These messages pop up as an overlay onto the
user’s current screen, often displaying a validation
warning message.

• Special Note:
In Android, Toast is used when we required to notify user
about an operation without expecting any user input.
It displays a small popup for message and automatically
fades out after timeout.

23
Toast Notification
Code Syntax

Toast toast = Toast.makeText(context, text, duration).show();

The toast notification code uses a Toast object and the


makeText( ) method with three parameters:
1. The context (displays the activity name).
2. The text message.
3. The duration of the interval that the toast is displayed
(LENGTH_SHORT or LENGTH_LONG).

To display the toast notification, a show( ) method displays


the Toast object.
24
Toast Notification
Other Methods:
setGravity(int,int,int): This method is used to set the gravity
for the Toast. This method accepts three parameters: a
Gravity constant, an x-position offset, and a y-position offset.
setDuration(int duration): This method is used to set the
duration for the Toast.
setText(CharSequence s): This method is used to set the
text for the Toast.
Toast toast = Toast.makeText(getApplicationContext(), "Simple msg", Toast.LENGTH_LONG);

toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);


toast.setDuration(Toast.LENGTH_SHORT);
toast.setText("Changed Toast Text");

toast.show(); // display the Toast


25
Mobile Applications Development

Thanks

You might also like