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

Unit 5: Android Terminologies and

Resource Handling
1. Terminologies
a. Content
b. Activity
c. Intent
d. Linked Activity using Intent
e. Calling Build-in Application using Intent

2. Notification Service
3. Broadcast
4. Adapter Resources
a. Working with different types of Resources
Content
● It Reside in android.content package
● Contains classes is for accessing and publishing data on a device.
● It includes three main categories of APIs:
○ Content Sharing
○ Package Management
○ Resource Management

1. Content sharing (android.content)

For sharing content between application components. The most important


classes are:
● ContentProvider and ContentResolver for managing and publishing
persistent data associated with an application.
● Intent and IntentFilter, for delivering structured messages between
different application components—allowing components to initiate
other components and return results.

2. Package management (android.content.pm)


● For accessing information about an Android package (an .apk),
including information about its activities, permissions, services,
signatures, and providers.
● The most important class for accessing this information is
PackageManager.
3. Resource management (android.content.res)

● For retrieving resource data associated with an application, such as


strings, drawables, media, and device configuration details.
● The most important class for accessing this data is Resources.
Activity
Check out following Google Slide link :
https://docs.google.com/presentation/d/11FHzE4nn90BprlgVwaox5Ee9Wt
hIsm_bf700qainFSc/edit#slide=id.gc6f75fceb_0_0

Code :

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/btnClickMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="onClick_ClickMe"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Welcome Android Developer"
android:textSize="40sp"
android:textColor="#000"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.unit5.activitylifecycle;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

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

@Override
protected void onStart() {
super.onStart();
print("onStart()");
}

@Override protected void onResume() {


super.onResume();
print("onResume()");
}

@Override protected void onPause() {


super.onPause();
print("onPause()");
}

@Override protected void onStop() {


super.onStop();
print("onStop()");
}

@Override protected void onDestroy() {


super.onDestroy();
print("onDestroy()");
}

@Override protected void onRestart() {


super.onRestart();
print("onRestart()");
}

private void print(String msg) {


Log.e("Unit5FirstAct", msg);
}

public void onClick_ClickMe(View v) {


Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}

SecondActivity.java
package com.unit5.activitylifecycle;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

public class SecondActivity extends AppCompatActivity {

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

@Override
protected void onStart() {
super.onStart();
print("onStart()");
}

@Override protected void onResume() {


super.onResume();
print("onResume()");
}

@Override protected void onPause() {


super.onPause();
print("onPause()");
}

@Override protected void onStop() {


super.onStop();
print("onStop()");
}

@Override protected void onDestroy() {


super.onDestroy();
print("onDestroy()");
}

@Override protected void onRestart() {


super.onRestart();
print("onRestart()");
}

private void print(String msg) {


Log.e("Unit5SecondAct", msg);
}
}

android_manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unit5.activitylifecycle">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ActivityLifecycle">
<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>

<activity
android:name=".SecondActivity"
android:exported="false" />

</application>

</manifest>
Intent
● An Intent is an "intention" to perform an action; in other words,
a messaging object you can use to request an action from another app
component
● An Intent is a simple message object that is used to communicate
between android components such as Activities, Content providers,
Broadcast receivers and Services. Intents are also used to transfer
data between activities.
● Intents are generally used for starting a new activity using
startActivity().

Use of Intent
1. For Launching an Activity
2. To start a New Service
3. For Broadcasting Messages
4. To Display a list of contacts in ListView
Types of Intent in Android
Intent is of two types:
1. Explicit Intent
2. Implicit Intent

Explicit Intent
An explicit intent is an Intent where you explicitly define the component that
needs to be called by the Android System. An explicit intent is one that you
can use to launch a specific app component, such as a particular activity or
service in your app.

Syntax:
Intent i = new Intent(getApplicationContext(), NextActivity.class);
i.putExtra(“value1” , “This value for Next Activity”);
i.putExtra(“value2” , “This value for Next Activity”);
Implicit Intent
The implicit intent is the intent where instead of defining the exact
components, you define the action that you want to perform for different
activities.
An Implicit intent specifies an action that can invoke any app on the device
to be able to perform an action. Using an Implicit Intent is useful when your
app cannot perform the action but other apps probably can and you’d like
the user to pick which app to use.

Syntax:
Intent i=new Intent();
i.setAction(Intent.ACTION_SEND);

There are some other standard actions that intents can use for launching
activities.
The Different Methods Used in Intent
● Action_Main
● Action_Pick
● Action_Chooser
● Action_Dial
● Action_Call
● Action_Send
● Action_SendTo
1. ACTION_MAIN
Use: Adds an action to an intent Filter.
<action android:name = “string”>
2. ACTION_PICK
Syntax:
It is using for picking the image from CAMERA or GALLERY.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 12352);
3. ACTION_CHOOSER
Use: It is used for choosing the image from the gallery.
Intent select = new Intent(Intent.ACTION_CAMERA); send.setData(uri);
startActivity(Intent.createChooser(select,”Select an Image from Camera”));
4. ACTION_DIAL
Use – Display the phone dialer with the given number filled in.
String phoneNo = "tel:123456";
Intent intentForCall = new Intent(Intent.ACTION_DIAL,
Uri.parse(phoneNo));
startActivity(intentForCall);
5. ACTION_CALL
Use: Placing and immediate phone call
String data = “tel : 651234567”;
Intent myActivity = new Intent(Intent.ACTION_CALL, Uri.parse(myNumber);
startActivity(myActivity);
Permission Needed:
<uses-permission android:name = “android.permission.CALL_PHONE” />
6. ACTION_SEND
Use: Sending Text content from one activity to other.
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, “This is my text to Send”);
sendIntent.setType(“text/plain”);
startActivity(sendIntent);
7. ACTION_SENDTO
Use : Preparing an SMS. The text is supplied as an Extra element. The
intent accepts such as values to be called “sms_body”
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(“smsto :
15555215556 “));
intent.putExtra(“sms_body”,”are we playing cricket today?”);
startActivity(intent);
Examples Of Intent
There is a simple application with two screens:
1. First Screen contains three controls – TextView , EditText, and Button
2. Second Screen contains a TextView
3. Now Go to File -> New -> Android Project with Project Name
IntentDemo
4. Set the target device and select target android device version.
5. Click on Finish.
Linked Activity using Intent

Code
Calling Build-in Application using
Intent
https://www.openglprojects.in/2015/06/how-to-call-built-in-applications-usi
ng-intents-in-android.html#gsc.tab=0
Notification Service
● A notification is a message you can display to the user outside of
your application's normal UI.
● When you tell the system to issue a notification, it first appears as an
icon in the notification area.
● To see the details of the notification, the user opens the notification
drawer.
● Both the notification area and the notification drawer are
system-controlled areas that the user can view at any time.

Create and Send Notifications


You have simple way to create a notification. Follow the following steps in
your application to create a notification −

Step 1 - Create Notification Builder


As a first step is to create a notification builder using
NotificationCompat.Builder.build(). You will use Notification Builder to set
various Notification properties like its small and large icons, title, priority
etc.
NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(this)

Step 2 - Setting Notification Properties


Once you have Builder object, you can set its Notification properties using
Builder object as per your requirement. But this is mandatory to set at least
following −
● A small icon, set by setSmallIcon()
● A title, set by setContentTitle()
● Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");

Step 3 - Issue the notification


Finally, you pass the Notification object to the system by calling
NotificationManager.notify() to send your notification.
Make sure you call NotificationCompat.Builder.build() method on builder
object before notifying it. This method combines all of the options that
have been set and return a new Notification object.

NotificationManager mNotificationManager = (NotificationManager)


getSystemService(Context.NOTIFICATION_SERVICE);

// notificationID allows you to update the notification later on.


mNotificationManager.notify(notificationID, mBuilder.build());
The NotificationCompat.Builder Class
The NotificationCompat.Builder class allows easier control over all the
flags, as well as help constructing the typical notification layouts. Following
are few important and most frequently used methods available as a part of
NotificationCompat.Builder class.
Sr.No Constants & Description
.

1 Notification build()
Combine all of the options that have been set and return a new
Notification object.

2 NotificationCompat.Builder setAutoCancel (boolean


autoCancel)
Setting this flag will make it so the notification is automatically
canceled when the user clicks it in the panel.

3 NotificationCompat.Builder setContent (RemoteViews views)


Supply a custom RemoteViews to use instead of the standard
one.

4 NotificationCompat.Builder setContentInfo (CharSequence


info)
Set the large text at the right-hand side of the notification.

5 NotificationCompat.Builder setContentIntent (PendingIntent


intent)
Supply a PendingIntent to send when the notification is clicked.
6 NotificationCompat.Builder setContentText (CharSequence
text)
Set the text (second row) of the notification, in a standard
notification.

7 NotificationCompat.Builder setContentTitle (CharSequence


title)
Set the text (first row) of the notification, in a standard
notification.

8 NotificationCompat.Builder setDefaults (int defaults)


Set the default notification options that will be used.

9 NotificationCompat.Builder setLargeIcon (Bitmap icon)


Set the large icon that is shown in the ticker and notification.

10 NotificationCompat.Builder setNumber (int number)


Set the large number at the right-hand side of the notification.

11 NotificationCompat.Builder setOngoing (boolean ongoing)


Set whether this is an ongoing notification.

12 NotificationCompat.Builder setSmallIcon (int icon)


Set the small icon to use in the notification layouts.

13 NotificationCompat.Builder setStyle (NotificationCompat.Style


style)
Add a rich notification style to be applied at build time.
14 NotificationCompat.Builder setTicker (CharSequence
tickerText)
Set the text that is displayed in the status bar when the
notification first arrives.

15 NotificationCompat.Builder setVibrate (long[] pattern)


Set the vibration pattern to use.

16 NotificationCompat.Builder setWhen (long when)


Set the time that the event occurred. Notifications in the panel
are sorted by this time.
Example
package com.example.notificationdemo;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {


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

b1 = (Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotification();
}
});
}

private void addNotification() {


NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");

Intent notificationIntent = new Intent(this, MainActivity.class);


PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);

// Add as notification
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
Following will be the content of res/layout/notification.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TextView
android:layout_width="fill_parent"
android:layout_height="400dp"
android:text="Hi, Your Detailed notification view goes here...." />
</LinearLayout>
Following is the content of the modified main activity file
package com.example.notificationdemo;

import android.os.Bundle;
import android.app.Activity;

public class NotificationViewActivity extends Activity{


@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
}
}
Following will be the content of res/layout/activity_main.xml file −
<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="Notification 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_centerHorizontal="true"
android:layout_marginTop="48dp" />

<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"
android:layout_marginTop="42dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification"
android:id="@+id/button"
android:layout_marginTop="62dp"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
</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="action_settings">Settings</string>
<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.notificationdemo" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.notificationdemo.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>

<activity android:name=".NotificationView"
android:label="Details of notification"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>

</application>
</manifest>
Broadcast
● Android apps can send or receive broadcast messages from the
Android system and other Android apps, similar to the
publish-subscribe design pattern.
● These broadcasts are sent when an event of interest occurs. For
example, the Android system sends broadcasts when various system
events occur, such as when the system boots up or the device starts
charging.
● Apps can also send custom broadcasts, for example, to notify other
apps of something that they might be interested in (for example,
some new data has been downloaded).
● Apps can register to receive specific broadcasts. When a broadcast
is sent, the system automatically routes broadcasts to apps that have
subscribed to receive that particular type of broadcast.
● Generally speaking, broadcasts can be used as a messaging system
across apps and outside of the normal user flow. However, you must
be careful not to abuse the opportunity to respond to broadcasts and
run jobs in the background that can contribute to a slow system
performance, as described in the following video.
Video : https://youtu.be/vBjTXKpaFj8

Imp. Predefined System Broadcast Intent


1. android.intent.action.AIRPLANE_MODE
2. android.intent.action.BATTERY_CHANGED
3. android.intent.action.BATTERY_LOW
4. android.intent.action.BOOT_COMPLETED
5. android.intent.action.LOCALE_CHANGED
6. android.intent.action.NEW_OUTGOING_CALL
7. android.intent.action.REBOOT
8. android.intent.action.SCREEN_OFF
9. android.intent.action.SCREEN_ON
10. android.intent.action.TIMEZONE_CHANGED
11. android.intent.action.WALLPAPER_CHANGED
12. android.media.RINGER_MODE_CHANGED
13. android.net.wifi.WIFI_STATE_CHANGED
14. android.net.wifi.p2p.CONNECTION_STATE_CHANGE
15. android.provider.Telephony.SMS_RECEIVED
Adapter Resources
public class Resources

extends Object

java.lang.Object

↳ android.content.res.Resources

● Class for accessing an application's resources.


● The Android resource system keeps track of all non-code assets
associated with an application.
● You can generally acquire the Resources instance associated with
your application with getResources().
● The Android SDK tools compile your application's resources into the
application binary at build time.
● To use a resource, you must install it correctly in the source tree
(inside your project's res/ directory) and build your application.
● Using application resources makes it easy to update various
characteristics of your application without modifying code, and—by
providing sets of alternative resources—enables you to optimize your
application for a variety of device configurations (such as for different
languages and screen sizes).
● This is an important aspect of developing Android applications that
are compatible on different types of devices.
a. Working with different types of Resources

Important Public methods

final AssetManager getAssets()


Retrieve underlying AssetManager storage
for these resources.

int getColor(int id)


This method was deprecated in API level 23.
UsegetColor(int,
android.content.res.Resources.Theme)
instead.

Configuration getConfiguration()
Return the current configuration that is in
effect for this resource object.

float getDimension(int id)


Retrieve a dimensional for a particular
resource ID.

Drawable getDrawable(int id, Resources.Theme


theme)
Return a drawable object associated with a
particular resource ID and styled for the
specified theme.

Typeface getFont(int id)


Return the Typeface value associated with a
particular resource ID.

int[] getIntArray(int id)


Return the int array associated with a
particular resource ID.
int getInteger(int id)
Return an integer associated with a
particular resource ID.

XmlResourceParser getLayout(int id)


Return an XmlResourceParser through
which you can read a view layout description
for the given resource ID.

String getResourcePackageName(int resid)


Return the package name for a given
resource identifier.

String getString(int id)


Return the string value associated with a
particular resource ID. It will be stripped of
any styled text information.

String[] getStringArray(int id)


Return the string array associated with a
particular resource ID.

void getValue(String name, TypedValue outValue,


boolean resolveRefs)
Return the raw data associated with a
particular resource ID.

void getValue(int id, TypedValue outValue,


boolean resolveRefs)
Return the raw data associated with a
particular resource ID.

You might also like