Professional Documents
Culture Documents
Chap-7. Peer To Peer To Communication: Accessing Telephony Hardware
Chap-7. Peer To Peer To Communication: Accessing Telephony Hardware
write the code to display the information about the telephony services.
1. package com.javatpoint.telephonymanager;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.content.Context;
5. import android.telephony.TelephonyManager;
6. import android.view.Menu;
7. import android.widget.TextView;
8. public class MainActivity extends Activity {
9. TextView textView1;
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_main);
14.
15. textView1=(TextView)findViewById(R.id.textView1);
16.
17. //Get the instance of TelephonyManager
18. TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPH
ONY_SERVICE);
19. //Calling the methods of TelephonyManager the returns the information
20. String IMEINumber=tm.getDeviceId();
21. String subscriberID=tm.getDeviceId();
22. String SIMSerialNumber=tm.getSimSerialNumber();
23. String networkCountryISO=tm.getNetworkCountryIso();
24. String SIMCountryISO=tm.getSimCountryIso();
25. String softwareVersion=tm.getDeviceSoftwareVersion();
26. String voiceMailNumber=tm.getVoiceMailNumber();
27.
28. //Get the phone type
29. String strphoneType="";
30.
31. int phoneType=tm.getPhoneType();
32.
33. switch (phoneType)
34. {
35. case (TelephonyManager.PHONE_TYPE_CDMA):
36. strphoneType="CDMA";
37. break;
38. case (TelephonyManager.PHONE_TYPE_GSM):
39. strphoneType="GSM";
40. break;
41. case (TelephonyManager.PHONE_TYPE_NONE):
42. strphoneType="NONE";
43. break;
44. }
45. //getting information if phone is in roaming
46. boolean isRoaming=tm.isNetworkRoaming();
47.
48. String info="Phone Details:\n";
49. info+="\n IMEI Number:"+IMEINumber;
50. info+="\n SubscriberID:"+subscriberID;
51. info+="\n Sim Serial Number:"+SIMSerialNumber;
52. info+="\n Network Country ISO:"+networkCountryISO;
53. info+="\n SIM Country ISO:"+SIMCountryISO;
54. info+="\n Software Version:"+softwareVersion;
55. info+="\n Voice Mail Number:"+voiceMailNumber;
56. info+="\n Phone Network Type:"+strphoneType;
57. info+="\n In Roaming? :"+isRoaming;
58.
59. textView1.setText(info);//displaying the information in the textView
60. }
61.
62.
63. }
Introducing Android Instant Messaging: -
Instant messaging is a set of communication technologies used for text-based
communication between two or more participants over the internet. Im allows effective and
efficient communication, allowing immediate receipt of acknowledgment or reply. In the
company, colleagues can send and reply instant message in real time without face to face,
meanwhile the work report can be shared during the instant chat session; it can make a
virtual conference without get all the related people together in a physical meeting room.
Using instant messages for interoffice communication is quicker than phone calls or emails.
More than one person can chat at the same time. This is a huge benefit of using an instant
messenger. Instead of relying on a conference call or copying others on an email message,
everybody can join and have a discussion in real time. Better than email, if you truly want
to communicate instantly you need to consider all your options.
Example:
1. Facebook
2. What’s App
3. Yahoo
4. Gmail
5. Hike
6. Instagram
7. Snapchat
Features:-
The bindService method accepts two input parameters, an Intent, which specifi es a component to
bind to, and a ServiceConnection implementation. The following skeleton code demonstrates the
pattern used to bind to the GTalk service:
i.setComponent(GTalkServiceConstants.GTALK_SERVICE_COMPONENT);
gtalkService = IGTalkService.Stub.asInterface(service);
gtalkService = null;
};
A bound GTalk Service represents a connection between your application and the GTalk Service
APIs.
Try
gTalkConnection = gtalkService.getDefaultConnection();
imSession = gTalkConnection.getDefaultImSession();
catch (RemoteException e) { }
}
};
You can attach a Chat Listener to a Chat Session to listen to the messages associated with it.
Handling Chat Sessions is particularly useful for integrating text messaging within your own
applications. Using a Chat Session, you can create a chat room for multiplayer games, or integrate
person-toperson messaging within a mobile social networking application.
Managing Group Chat Sessions: You can get a list of participants in a Chat Session using the
getParticipants method. You can also send text or data messages to each chat member as you would
in a normal chat, as well as invite new members using inviteContact. The leave method lets you exit
a chat room and end the session.
// TODO Notify user that a new participant has joined the conversation.
}
// Fired when a participant leaves a chat room.
};
The uses-permission tag will allow the application to send SMS messages. Sending SMS message with
the application will potentially incur additional cost on the user’s end.
Indicating the SMS permissions in the AndroidManifest.xml file will let the user decide whether to allow
the application to install or not.
SendActivity Class:
private void sendSMS()
{
PendingIntent sent = this.createPendingResult(SENT, new Intent(),
PendingIntent.FLAG_UPDATE_CURRENT);
String messageText = _message.getText().toString();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendDataMessage(_phoneNumber.getText().toString(), null,
SMS_PORT, messageText.getBytes(), sent, null);
}
To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly
instantiate this class; instead you will call the getDefault() static method to obtain
an SmsManager object. The sendDataMessage() method sends the SMS message with a PendingIntent.
The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending
the message, you can use a PendingIntent object to update the current activity, and onActivityResult will
be triggered.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data)
{
String toast = null;
switch (requestCode)
{
case SENT :
switch (resultCode)
{
case RESULT_OK :
toast = "OK";
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE :
toast = "Generic Failure";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF :
toast = "Radio Off";
break;
case SmsManager.RESULT_ERROR_NULL_PDU :
toast = "Null Pdu";
break;
}
break;
}
if (toast != null)
{
Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
}
}
The uses-permission tags will allow the application to receive and read SMS messages. Lets create a
class that extends the BroadcastReceiver class and override the onReceive() method:
@Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
String recMsgString = "";
String fromAddress = "";
SmsMessage recMsg = null;
byte[] data = null;
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdus.length; i++)
{
recMsg = SmsMessage.createFromPdu((byte[]) pdus[i]);
try
{
data = recMsg.getUserData();
}
catch (Exception e)
{
}
if (data != null)
{
for (int index = 0; index < data.length; ++index)
{
recMsgString += Character.toString((char) data[index]);
}
}
fromAddress = recMsg.getOriginatingAddress();
}
}
When SMS messages are received, the onReceive() method will be invoked. The SMS message is
contained and attached to the Intent object via a Bundle object.
Introducing SMS: - 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);
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;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
String phoneNo;
String message;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn.setOnClickListener(new View.OnClickListener() {
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
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
return;
Or you can access files from your SD card or phone memory for playing, if you don't want to
include them in your application
If we want to play a video file saved in our SD card or phone memory, we need a video player
control
Create a blank project
Place a Video View control on your main layout
Edit main activity (.java file) to include the following lines of code
v.setVideoPath("/sdcard/abc.mp4");
v.start();
// include the following line if you want your video view control to have play, pause, FF controls
v.setMediaController(new MediaController(this));
For access or use camera, you need to access/communicate directly with the built-in camera
App
Your App will communicate with camera App and get image/video captured/recorded and
then you can use it
Create a blank project, in this example we’ll capture an image and then display it on our
main activity
Edit the layout.xml to insert a Button and an Image View control
Edit the main activity (.java file) and place the following lines of code in it
iv = (ImageView) findViewById(R.id.imageView1);
b.setOnClickListener(new OnClickListener() {
@Override
startActivityForResult(i, 0);
});
@Override
iv.setImageBitmap(bmap);
* An intent is needed to communicate with the camera App. The results are expected
(image/video file), so the start activity method is called for results. The bitmap image returned is
then displayed using Image View control
Introducing Sensor Manager:
Most of the android devices have built-in sensors that measure motion, orientation, and various
environmental conditions. The android platform supports three broad categories of sensors .
Motion Sensors
Environmental sensors
Position sensors
Some of the sensors are hardware based and some are software based sensors. Whatever the
sensor is, android allows us to get the raw data from these sensors and use it in our application.
For this android provides us with some classes.
Android provides SensorManager and Sensor classes to use the sensors in our application. In
order to use sensors, first thing you need to do is to instantiate the object of SensorManager
class.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorManager;
TextView tv1=null;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1.setVisibility(View.GONE);
tv1.setVisibility(View.VISIBLE);
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
@Override
// Handle action bar item clicks here. The action bar will
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
return super.onOptionsItemSelected(item);
Using Bluetooth:
Among many ways, Bluetooth is a way to send or receive data between two different devices. Android
platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data
with other Bluetooth devices.
Apart form the parried Devices , there are other methods in the API that gives more control over
Blueetooth. They are listed below.
1
enable():-This method enables the adapter if not enabled
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
Button b1,b2,b3,b4;
private Set<BluetoothDevice>pairedDevices;
ListView lv;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
if (!BA.isEnabled()) {
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned
on",Toast.LENGTH_LONG).show();
} else {
BA.disable();
startActivityForResult(getVisible, 0);
lv.setAdapter(adapter);
A device can have various types of network connections. This lesson focuses on using either a Wi-Fi or a
mobile network connection. For the full list of possible network types, see ConnectivityManager.
Wi-Fi is typically faster. Also, mobile data is often metered, which can get expensive. A common strategy
for apps is to only fetch large data if a Wi-Fi network is available.
Android - Wi-Fi
Android allows applications to access to view the access the state of the wireless connections at very
low level. Application can access almost all the information of a wifi connection .
The information that an application can access includes connected network's link speed,IP address,
negotiation state, other networks information. Applications can also scan, add, save, terminate and
initiate Wi-Fi connections.
Android provides WifiManager API to manage all aspects of WIFI connectivity. We can instantiate this
class by calling getSystemServicemethod. Its syntax is given below −
1
addNetwork(WifiConfiguration config):-This method add a new network
description to the set of configured networks.
2
createWifiLock(String tag):-This method creates a new WifiLock.
3
disconnect():-This method disassociate from the currently active access
point.
4
enableNetwork(int netId, boolean disableOthers):-This method allow a
previously configured network to be associated with.
5
getWifiState():-This method gets the Wi-Fi enabled state
6
isWifiEnabled():-This method return whether Wi-Fi is enabled or disabled.
7
setWifiEnabled(boolean enabled):-This method enable or disable Wi-Fi.
8
updateNetwork(WifiConfiguration config):-This method update the
network description of an existing configured network.
package com.example.sairamkrishna.myapplication;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
Button enableButton,disableButton;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enableButton=(Button)findViewById(R.id.button1);
disableButton=(Button)findViewById(R.id.button2);
enableButton.setOnClickListener(new OnClickListener(){
wifi.setWifiEnabled(true);
});
disableButton.setOnClickListener(new OnClickListener(){
wifi.setWifiEnabled(false);
});