Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Mobile Application Development 22617 Prepared by Darshan Sir

Important Concepts for Coding:

1. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.geeksforgeeks"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="27" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myservice">

<application
...>

<service android:name=".MyService" />

<activity android:name=".MainActivity">
...
</activity>
</application>

</manifest>

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

2. 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"
tools:context=".MainActivity">

</RelativeLayout>

3. MainActivity.java

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

4. Button onClick

Button myButton = findViewById(R.id.myButton);

myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button clicked!",
Toast.LENGTH_SHORT).show();
}
});

5. Creating Custom Toast Message

Toast toast = new Toast(getApplicationContext());


toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

1. Write a Program for implementing Geocoding and reverse Geocoding.

import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

private Geocoder geocoder;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

geocoder = new Geocoder(this, Locale.getDefault());

String locationName = "1600 Amphitheatre Parkway, Mountain View,


CA";
try {
List<Address> addresses =
geocoder.getFromLocationName(locationName, 1);
if (!addresses.isEmpty()) {
Address address = addresses.get(0);
double latitude = address.getLatitude();
double longitude = address.getLongitude();
displayToast("Geocoding Result: Latitude - " + latitude +
", Longitude - " + longitude);
} else {
displayToast("Location not found!");
}
} catch (IOException e) {
e.printStackTrace();
displayToast("Geocoding failed: " + e.getMessage());
}

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

double latitude = 37.423021;


double longitude = -122.083739;
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
if (!addresses.isEmpty()) {
Address address = addresses.get(0);
String addressText = address.getAddressLine(0);
displayToast("Reverse Geocoding Result: " + addressText);
} else {
displayToast("Address not found!");
}
} catch (IOException e) {
e.printStackTrace();
displayToast("Reverse geocoding failed: " + e.getMessage());
}
}

private void displayToast(String message) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
2.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

3. Write a Program to send and receive SMS.

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


<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

package com.example.testreceivesms;

import androidx.appcompat.app.AppCompatActivity;

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


SmsReceiver sms = new SmsReceiver();
EditText et1, et2;
Button b1;

@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=findViewById(R.id.etPhno);
et2=findViewById(R.id.etmsg);
b1=findViewById(R.id.btnSms);
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.
SEND_S
MS)!=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new
String[]{Manifest.permission.SEND_SMS},100);
}
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String phno= et1.getText().toString();
String msg=et2.getText().toString();
SmsManager smsManager= SmsManager.getDefault();
smsManager.sendTextMessage(phno,null,msg,null,null);
Toast.makeText(MainActivity.this,"Sms sent successfully",
Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,"Sms failed to send... try again",
Toast.LENGTH_LONG).show();
}

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

}
});
}

@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new
IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(sms, filter);
}

@Override
protected void onStop() {
super.onStop();
unregisterReceiver(sms);
}
}

package com.example.testreceivesms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {


SmsReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
// Retrieve the SMS Messages received
Object[] sms = (Object[]) bundle.get("pdus");
// For every SMS message received
for (int i=0; i < sms.length; i++) {
// Convert Object array
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String phone = smsMessage.getOriginatingAddress();
String message = smsMessage.getMessageBody().toString();
Toast.makeText(context, “Received from “+ phone + ": " + message,
Toast.LENGTH_SHORT).show();
}
}

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

}
}

4. SQLite Database.

<?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"
tools:context=".MainActivity">
<TextView
android:text="Insert Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="@+id/textView"
android:gravity="center"
android:textSize="20dp"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="ID"
android:id="@+id/editid"
android:layout_below="@+id/textView"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"
android:layout_below="@+id/editid"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Mobile No."
android:id="@+id/editmobile"
android:layout_below="@+id/editname"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Address"
android:lines="3"
android:id="@+id/editaddress"
android:layout_below="@+id/editmobile"/>
<EditText
android:layout_width="fill_parent"

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

android:layout_height="wrap_content"
android:hint="Pin Code"
android:id="@+id/editpincode"
android:layout_below="@+id/editaddress"/>
<Button
android:text="Insert Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editpincode"
android:layout_centerHorizontal="true"
android:id="@+id/button" />
<TextView
android:text="Search Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:id="@+id/textView1"
android:gravity="center"
android:textSize="20dp"
android:layout_below="@+id/button"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter ID"
android:id="@+id/editsearchid"
android:layout_below="@+id/textView1"/>
<Button
android:text="Search Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editsearchid"
android:layout_centerHorizontal="true"
android:id="@+id/button1" />
</RelativeLayout>

package in.msbte.database;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

public class MainActivity extends AppCompatActivity {


SQLiteDatabase sqLiteDatabaseObj;
EditText editTextID, editTextName, editMobileNo, editAddress, editPincode,
editSearchid;
String cid, cname, cmobile, caddress, cpincode, sql_query, sid;
Button EnterData, SearchData;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EnterData = (Button)findViewById(R.id.button);
SearchData = (Button)findViewById(R.id.button1);
editTextID = (EditText)findViewById(R.id.editid);
editTextName = (EditText)findViewById(R.id.editname);
editMobileNo = (EditText)findViewById(R.id.editmobile);
editAddress = (EditText)findViewById(R.id.editaddress);
editPincode = (EditText)findViewById(R.id.editpincode);
editSearchid = (EditText)findViewById(R.id.editsearchid);
EnterData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS
AndroidJSonTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, cid
VARCHAR, name VARCHAR, mobile VARCHAR, address VARCHAR, pincode
VARCHAR);");
cid = editTextID.getText().toString();
cname = editTextName.getText().toString() ;
cmobile = editMobileNo.getText().toString();
caddress = editAddress.getText().toString();
cpincode = editPincode.getText().toString();
sql_query = "INSERT INTO AndroidJSonTable (cid, name, mobile, address,
pincode) VALUES('"+cid+"', '"+cname+"', '"+cmobile+"', '"+caddress+"',
'"+cpincode+"');";
sqLiteDatabaseObj.execSQL(sql_query);
Toast.makeText(getApplicationContext(), "Data Inserted Successfully",
Toast.LENGTH_LONG).show();
}
});
SearchData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sid = editSearchid.getText().toString();
Cursor cursor = sqLiteDatabaseObj.rawQuery( "select * from
AndroidJSonTable

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

where cid="+sid+"", null );


StringBuffer buffer= new StringBuffer();
while (cursor.moveToNext())
{
String cid =cursor.getString(1);
String name =cursor.getString(2);
String mob =cursor.getString(3);
String addr =cursor.getString(4);
String pcode =cursor.getString(5);
buffer.append(cid+ " " + name + " " + mob +" " + addr +" " + pcode +"
\n");
Toast.makeText(getApplicationContext(), buffer,
Toast.LENGTH_LONG).show();
} }); } }

5. Demonstrate Date and Time Picker

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

private TextView dateTextView;


private TextView timeTextView;
private DatePicker datePicker;
private TimePicker timePicker;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

dateTextView = findViewById(R.id.dateTextView);
timeTextView = findViewById(R.id.timeTextView);
datePicker = findViewById(R.id.datePicker);
timePicker = findViewById(R.id.timePicker);
Button fetchDateTimeButton =
findViewById(R.id.fetchDateTimeButton);

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

fetchDateTimeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fetchDateTime();
}
});
}

private void fetchDateTime() {


int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1;
int year = datePicker.getYear();

int hour = timePicker.getCurrentHour();


int minute = timePicker.getCurrentMinute();

// Display the selected date and time in TextViews


dateTextView.setText(formatDate(day, month, year));
timeTextView.setText(formatTime(hour, minute));
}

private String formatDate(int day, int month, int year) {


Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, day); // month is zero-based
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy",
Locale.getDefault());
return sdf.format(calendar.getTime());
}

private String formatTime(int hour, int minute) {


return String.format(Locale.getDefault(), "%02d:%02d", hour,
minute);
}
}

6. Display Users Current Location

<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="example.com.mapexample.MapsActivity" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
<uses-permission android:name="android.permission.INTERNET" />

import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.api.GoogleApiClient;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.location.LocationServices;

import android.location.Location;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

public class MapsActivity extends FragmentActivity implements


OnMapReadyCallback,
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {

private GoogleMap mMap;


Location mLastLocation;
Marker mCurrLocationMarker;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;

@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

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

// used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {


if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}

protected synchronized void buildGoogleApiClient() {


mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {

mLocationRequest = new LocationRequest();


mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);

mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POW
ER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoog
leApiClient,
mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {

@Override
public void onLocationChanged(Location location) {

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
// Place current location marker
LatLng latLng = new LatLng(location.getLatitude(),
location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDes
criptorFactory.HUE_GREEN));
mCurrLocationMarker = mMap.addMarker(markerOptions);

// move map camera


mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

// stop location updates


if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogl
eApiClient,
this);
}
}

@Override

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

public void onConnectionFailed(ConnectionResult connectionResult) {


}
}

7. Develop a program for Bluetooth Connectivity

<uses-permission android:name="android.permission.BLUETOOTH" />


<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<RelativeLayout
xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView android:text=""
android:id="@+id/out"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="49dp"
android:text="TURN_ON" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="27dp"
android:text="DISCOVERABLE" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button2"
android:layout_below="@+id/button2"
android:layout_marginTop="28dp"
android:text="TURN_OFF" />

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

</RelativeLayout>

package com.example.bluetooth;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVERABLE_BT = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView out=(TextView)findViewById(R.id.out);
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
final BluetoothAdapter mBluetoothAdapter =
BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
out.append("device not supported");
}
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (!mBluetoothAdapter.isDiscovering()) {

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

//out.append("MAKING YOUR DEVICE DISCOVERABLE");


Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOVERA
BLE",
Toast.LENGTH_LONG);
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVER
ABLE);
startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);

}
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mBluetoothAdapter.disable();
//out.append("TURN_OFF BLUETOOTH");
Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGT
H_LONG);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

8. Develop a program to implement Implicit and Explicit Intent.

package com.example.intentdemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button explicitButton = findViewById(R.id.explicitButton);


explicitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Explicit Intent
Intent intent = new Intent(MainActivity.this,
SecondActivity.class);
startActivity(intent);
}
});

Button implicitButton = findViewById(R.id.implicitButton);


implicitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Implicit Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(android.net.Uri.parse("https://www.example.c
om"));
startActivity(intent);
}
});
}
}

9. Develop a program to implement Sensors.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.view.View;
import android.widget.TextView;
import java.util.List;

public class MainActivity extends AppCompatActivity {


private SensorManager mgr;
private TextView txtList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

mgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
txtList = (TextView)findViewById(R.id.sensorslist);
List<Sensor> sensorList = mgr.getSensorList(Sensor.TYPE_ALL);
StringBuilder strBuilder = new StringBuilder();
for(Sensor s: sensorList){
strBuilder.append(s.getName()+"\n");
}
txtList.setVisibility(View.VISIBLE);
txtList.setText(strBuilder);
}
}

10. Develop a program to capture Image with Camera and display it.

package com.example.ifcdiv;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {


Button b1;
ImageView imageView;
int CAMERA_REQUEST = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.photo);
imageView = findViewById(R.id.image);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
});
}

@Override

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

protected void onActivityResult(int requestCode, int resultCode,


Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
Bitmap image = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(image);
}
}
}

11. Develop a program to implement Service.

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {

@Override
public void onCreate() {
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

Runnable runnable = new Runnable() {


@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stopSelf();
}
};

Thread thread = new Thread(runnable);


thread.start();

return START_STICKY;

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

@Override
public IBinder onBind(Intent intent) {
return null;
}
}

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void startService(View view) {


Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
}
}

<service android:name=".MyService" />

12. Develop a program to implement Broadcast Receiver.


13. Develop a program to send and receive email.

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


// define objects for edit text and button
Button button;
EditText sendto, subject, body;

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting instance of edittext and button
sendto = findViewById(R.id.editText1);
subject = findViewById(R.id.editText2);
body = findViewById(R.id.editText3);
button = findViewById(R.id.button);
button.setOnClickListener(view -> {
String emailsend = sendto.getText().toString();
String emailsubject = subject.getText().toString();
String emailbody = body.getText().toString();
// define Intent object with action attribute as ACTION_SEND
Intent intent = new Intent(Intent.ACTION_SEND);
// add three fields to intent using putExtra function
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailsend});
intent.putExtra(Intent.EXTRA_SUBJECT, emailsubject);
intent.putExtra(Intent.EXTRA_TEXT, emailbody);
// set type of intent
intent.setType("message/rfc822");
// startActivity with intent with chooser as Email client using
createChooser function
startActivity(Intent.createChooser(intent, "Choose an Email client
:"));
});
}
}

import androidx.appcompat.app.AppCompatActivity;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


GmailReceiver gml;
IntentFilter intf;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gml = new GmailReceiver();
intf = new IntentFilter("android.intent.action.VIEW");
}

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

@Override
protected void onResume() {
super.onResume();
registerReceiver(gml, intf);
}

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(gml);
}
}

package com.example.myemailprog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.widget.Toast;
public class GmailReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Email Received", Toast.LENGTH_LONG).show();

14. Develop a program to implement Animation.

<translate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXDelta="-100%"
android:toXDelta="100%"
android:repeatCount="infinite"
android:interpolator="@android:anim/linear_interpolator"/>

import android.os.Bundle;
import android.view.animation.Animation;

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

import android.view.animation.AnimationUtils;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the TextView


TextView animatedTextView = findViewById(R.id.animatedTextView);

// Load the animation


Animation slideRightAnimation =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_right);

// Start the animation


animatedTextView.startAnimation(slideRightAnimation);
}
}
15.

16. Develop a program for implementing Asynchronous Tasks.

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText time;
private TextView finalResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (EditText) findViewById(R.id.in_time);
button = (Button) findViewById(R.id.btn_run);
finalResult = (TextView) findViewById(R.id.tv_result);
button.setOnClickListener(new View.OnClickListener() {
@Override

V2V EdTech LLP


Mobile Application Development 22617 Prepared by Darshan Sir

public void onClick(View v) {


AsyncTaskRunner runner = new AsyncTaskRunner();
String sleepTime = time.getText().toString();
runner.execute(sleepTime);
}
});
}
privateclass AsyncTaskRunner extends AsyncTask<String, String, String>{
private String resp;
ProgressDialog progressDialog;
@Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
@Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
}

V2V EdTech LLP

You might also like