Chapter 3-MP
Chapter 3-MP
Chapter 3
The activity attribute android:name will represent the name of class and we can also add multiple
attributes like icon, label, theme, permissions, etc. to an activity element based on our requirements.
In android application, activities can be implemented as a subclass of Activity class like as shown
below.
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
SEng3035 Page 1
Mobile Programming
3.2. Fragments
In the previous section you learned what an activity is and how to use it. In a small-screen device (such as
a smartphone), an activity typically fills the entire screen, displaying the various views that make up the
user interface of an application. The activity is essentially a container for views.
However, when an activity is displayed in a large-screen device, such as on a tablet, it is somewhat out of
place. Because the screen is much bigger, all the views in an activity must be arranged to make full use of
the increased space, resulting in complex changes to the view hierarchy. A better approach is to have
“mini-activities,” each containing its own set of views. During runtime, an activity can contain one or
more of these mini-activities, depending on the screen orientation in which the device is held. In Android
3.0 and later, these mini-activities are known as fragments.
SEng3035 Page 4
Mobile Programming
Think of a fragment as another form of activity. You create fragments to contain views, just like
activities. Fragments are always embedded in an activity. For example, Figure 3.2.1 shows two
fragments. Fragment 1 might contain a ListView showing a list of book titles. Fragment 2 might contain
some TextViews and ImageViews showing some text and images.
Now imagine the application is running on an Android tablet in portrait mode (or on an Android
smartphone). In this case, Fragment 1 may be embedded in one activity, while Fragment 2 may be
embedded in another activity (see Figure 3.2.2). When users select an item in the list in Fragment
1,Activity 2 will be started.
If the application is now displayed in a tablet in landscape mode, both fragments can be embedded within
a single activity, as shown in Figure 3.2.3.
SEng3035 Page 5
Mobile Programming
Method Description
onAttach() It is called when the fragment has been associated with an activity.
onActivityCreated() It is called when the fragment activity has been created and the fragment view hierarchy
instantiated.
onPause() It is called when fragment is no longer visible and it indicates that the user is leaving the
fragment.
onDestoryView() The view hierarchy which associated with the fragment is being removed after executing this
method.
onDetach() It is called immediately after the fragment disassociated from the activity.
Example:
Following is the example of creating a two fragments, two buttons and showing the respective fragment
when click on button in android application.
1. Create a new android application using android studio and give name as Fragments.
2. Now we need to create our own custom fragment layout files
(listitems_info.xml, details_info.xml) in \res\layout path to display those fragments in
main layout for that right click on your layout folder Go to New select Layout resource
file and give name as listitems_info.xml. Once we create a new file listitems_info.xml,
open it and write the code like as shown below
listitems_info.xml
SEng3035 Page 6
Mobile Programming
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/list" />
</LinearLayout>
3. Same way create another file details_info.xml, open it and write the code like as shown below
details_info.xml
4. Now we need to create our own custom fragment class files (ListMenuFragment.java,
DetailsFragment.java) in \java\com.example.fragmentsexample path to bind and display data
in fragments for that right click on your application folder Go to New select Java Class and
give name as DetailsFragment.java. Once we create a new file DetailsFragment.java, open it
and write the code like as shown below
DetailsFragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailsFragment extends Fragment {
TextView name,location;
SEng3035 Page 7
Mobile Programming
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_info,
container, false);
name = (TextView)view.findViewById(R.id.Name);
location = (TextView)view.findViewById(R.id.Location);
return view;
}
public void change(String uname, String ulocation){
name.setText(uname);
location.setText(ulocation);
}
}
5. If you observe above code we extended class with Fragment and used LayoutInflater to show
the details of fragment. We defined a function change() to change the text in textview. Same
way create another file ListMenuFragment.java, open it and write the code like as shown
below
ListMenuFragment.java
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListMenuFragment extends ListFragment {
String[] users = new String[] { "Abebe","Samson","Kirubel","Helen" };
String[] location = new String[]{"Gondar","Bahir Dar","Addis
Ababa","Debre Markos"};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.listitems_info,
container, false);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, users);
setListAdapter(adapter);
return view;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
SEng3035 Page 8
Mobile Programming
DetailsFragment txt =
(DetailsFragment)getFragmentManager().findFragmentById(R.id.fragment2);
txt.change("Name: "+ users[position],"Location :
"+ location[position]);
getListView().setSelector(android.R.color.holo_blue_dark);
}
}
6. If you observe above code we extended our class using ListFragment and we defined two
arrays of strings users, location which contains names and locations. We
defined onListItemClick event to update the name and location in DetailsFragment based
on the list item which we clicked. Now we need to display our fragments horizontally side by
side in main layout for that open activity_main.xml file and write code like as shown below
activity_main.xml
We are not going to make any modifications for our main activity file ( MainActivity.java) and manifest
file (AndroidMainfest.xml).
3.3. Intents
Android uses Intent for communicating between the components (such as activities, services, broadcast
receivers and content providers) of an Application and also from one application to another application.
For example: Intent facilitates you to redirect your activity to another activity on occurrence of any event.
By calling, startActivity() you can perform this task.
SEng3035 Page 9
Mobile Programming
In the above example, foreground activity is getting redirected to another activity i.e.
SecondActivity.java. getApplicationContext() returns the context for your foreground activity.
In android, Intents are the objects of android.content.Intent type and intents are mainly useful to
perform following things.
Component Description
Starting an Activity By passing an Intent object to startActivity() method we can start a new Activity
or existing Activity to perform required things.
Starting a Service By passing an Intent object to startService() method we can start a new Service or
send required instructions to an existing Service.
Delivering a Broadcast By passing an Intent object to sendBroadcast() method we can deliver our messages
to other app broadcast receivers.
Types of Intents:
There are two types of intents: Explicit Intent and Implicit Intent
Explicit Intent:
Explicit Intents are used to connect the application internally. In Explicit we use the name of component
which will be affected by Intent. For Example: If we know class name then we can navigate the app from
One Activity to another activity using Intent. In the similar way we can start a service to download a file
in background process. Explicit Intent works internally within an application to perform navigation and
data transfer. The below given code snippet will help you understand the concept of Explicit Intents
Here SecondActivity is the JAVA class name where the activity will now be navigated.
Implicit Intent:
In Implicit Intents we do need to specify the name of the component. We just specify the Action which
has to be performed and further this action is handled by the component of another application. The basic
example of implicit Intent is to open any web page.
Let’s take an example to understand Implicit Intents more clearly. We have to open a website using intent
in your application. See the code snippet given below
SEng3035 Page 10
Mobile Programming
intentObj.setData(Uri.parse("https://www.google.com"));
startActivity(intentObj);
Unlike Explicit Intent you do not use any class name to pass through Intent(). In this example we have
just specified an action. Now when we run this code then Android will automatically start your web
browser and it will open Google home page.
Example:
The example will show you both implicit and explicit Intent together. Let’s implement Intent for a very
basic use. In the below example we will Navigate from one Activity to another and open a web homepage
of Google using Intent.
Create a project in Android Studio and named it “Intents”. Make an activity, which would
consists Java file; MainActivity.java and an xml file for User interface which would be
activity_main.xml
Step 1: Let’s design the UI of activity_main.xml:
First design the text view displaying basic details of the App
Second design the two button of Explicit Intent Example and Implicit Intent Example
Below is the complete code of activity_main.xml
<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:textAppearance="?android:attr/textAppearanceMedium"
android:text="If you click on Explicit example we will navigate to
second
activity within App and if you click on Implicit example Google
Homepage will
open in Browser"
android:id="@+id/textView2"
android:clickable="false"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp"
android:background="#3e7d02"
android:textColor="#ffffff" />
SEng3035 Page 11
Mobile Programming
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit Intent Example"
android:id="@+id/explicit_Intent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="147dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Implicit Intent Example"
android:id="@+id/implicit_Intent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Step 3: Implement onClick event for Implicit and Explicit Button inside MainActivity.java
SEng3035 Page 12
Mobile Programming
Now we will use setOnClickListener() method to implement OnClick event on both the button. Implicit
button will open AbhiAndroid.com homepage in browser and Explicit button will move to
SecondActivity.java.
Below is the complete code of MainActivity.java
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button explicit_btn, implicit_btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
explicit_btn = (Button)findViewById(R.id.explicit_Intent);
implicit_btn = (Button) findViewById(R.id.implicit_Intent);
//implement Onclick event for Explicit Intent
explicit_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),
SecondActivity.class);
startActivity(intent);
}
});
//implement onClick event for Implicit Intent
implicit_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
}
});
} }
import android.support.v7.app.AppCompatActivity;
SEng3035 Page 13
Mobile Programming
import android.os.Bundle;
import android.widget.Toast;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toast.makeText(getApplicationContext(), "We are moved to second
Activity”, Toast.LENGTH_LONG).show();
}
}
Testing:
Now run the above program in your Emulator.
First Click on Explicit Intent Example. The SecondActivity will be open within the App.
Now go back in Emulator and click on Implicit Intent Example. The google.com homepage will
open in Browser (make sure you have internet)
Benefits of Intent in Android
SEng3035 Page 14
Mobile Programming
Android uses Intents for facilitating communication between its components like Activities, Services and
Broadcast Receivers.
For an Activity: Every screen in Android application represents an activity. To start a new activity you
need to pass an Intent object to startActivity() method. This Intent object helps to start a new activity and
passing data to the second activity.
For Services: Services work in background of an Android application and it does not require any user
Interface. Intents could be used to start a Service that performs one-time task(for example: Downloading
some file) or for starting a Service you need to pass Intent to startService() method.
For Broadcast Receivers: There are various messages that an app receives; these messages are called as
Broadcast Receivers. (For example, a broadcast message could be initiated to intimate that the file
downloading is completed and ready to use). Android system initiates some broadcast message on several
events, such as System Reboot, Low Battery warning message etc.
For Android Applications: Whenever you need to navigate to another activity of your app or you need
to send some information to next activity then we can always prefer to Intents for doing so.
SEng3035 Page 15
Mobile Programming
SEng3035 Page 16
Mobile Programming
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="200dp"
android:text="Next Page"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
3. Now create the service implementation class by inheriting the Service class and overriding its
callback methods. MyService.java
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyService extends Service {
MediaPlayer myPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) { return null; }
@Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.sun);
myPlayer.setLooping(false); // Set looping
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
myPlayer.start();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
} }
SEng3035 Page 17
Mobile Programming
4. Now create the MainActivity class to perform event handling. Here, we are writing the code to
start and stop service. Additionally, calling the second activity on buttonNext.
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClick
Listener{
Button buttonStart, buttonStop,buttonNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = findViewById(R.id.buttonStart);
buttonStop = findViewById(R.id.buttonStop);
buttonNext = findViewById(R.id.buttonNext);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
buttonNext.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class));
break;
case R.id.buttonNext:
Intent intent=new Intent(this,NextPage.class);
startActivity(intent);
break;
}
}
}
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class NextPage extends AppCompatActivity {
@Override
SEng3035 Page 18
Mobile Programming
6. Finally, declare the service in the manifest file. Let's see the complete AndroidManifest.xml file
SEng3035 Page 19