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

Tutorial 7 - Service and Broadcast Receiver

The document discusses two examples of using services and broadcast receivers in Android. The first example plays a sound using a background service. The second example uses a service to broadcast messages that are received by a broadcast receiver in an activity.

Uploaded by

batoolnf11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Tutorial 7 - Service and Broadcast Receiver

The document discusses two examples of using services and broadcast receivers in Android. The first example plays a sound using a background service. The second example uses a service to broadcast messages that are received by a broadcast receiver in an activity.

Uploaded by

batoolnf11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Tutorial 7 -

Services and BroadcastReceiver

SWE 483- Mobile Application Development


Spring 2022
Table of Contents
Example #1: android-service 2
Activity_main.xml 2
MainActivity.java 3
MyService1.java 4
AndroidManifest.xml 5
Demo 5
Example #2: android-service-broadcastreceiver 6
Activity_main.xml 6
MainActivity.Java 7
BroadcastService.Java 8
AndroidManifest.xml 9
Demo 10

2
Tutorial 7
(Services and BroadcastReceivers)
Example #1: Play Sound in the background service

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">

<TextView
android:id="@+id/txtMsg"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="88dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Play Sound Service is now working in the background !"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/btnStopService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop My Service"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtMsg"
app:layout_constraintVertical_bias="0.07" />
</androidx.constraintlayout.widget.ConstraintLayout>

3
MainActivity.java

package com.example.ch5_example;

import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


TextView txtMsg;
Button btnStopService;
ComponentName service;
Intent intentMyService;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtMsg= (TextView) findViewById(R.id.txtMsg);

intentMyService = new Intent(this, MyService1.class);


service = startService(intentMyService);

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


btnStopService.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
stopService((intentMyService));
txtMsg.setText("After Stopping My Service: \n" + service.getClassName());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), 1).show();
}
}
} );
}
}

4
MyService1.java
package com.example.ch5_example;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import static android.media.MediaPlayer.*;

public class MyService1 extends Service {


private MediaPlayer player;

@Override
public void onCreate() {
super.onCreate();
Log.i ("<<MyService1-onStart>>", "I am alive-1!");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("<<MyService1-onStart>>", "I did something very quickly");
player = MediaPlayer.create(this, Settings.System.DEFAULT_ALARM_ALERT_URI);
player.setLooping(true);
player.start();
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
Log.i("<<MyService1-onDestroy>>", "I am dead-1");
player.stop();
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
}

5
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ch5_example">

<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.Ch5Example">
<service
android:name=".MyService1"
android:enabled="true"
android:exported="true">
</service>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="4" />
</manifest>

Demo

6
Example #2: Service and Broadcastreceiver

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">

<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

7
MainActivity.Java
package com.example.ch5example3;
// https://www.truiton.com/2014/09/android-service-broadcastreceiver-example/
import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


public static final String mBroadcastStringAction = "ch5.broadcast.string";
public static final String mBroadcastIntegerAction = "ch5.broadcast.integer";
public static final String mBroadcastArrayListAction = "ch5.broadcast.arraylist";
private TextView mTextView;
private IntentFilter mIntentFilter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textview1);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(mBroadcastStringAction);
mIntentFilter.addAction(mBroadcastIntegerAction);
mIntentFilter.addAction(mBroadcastArrayListAction);
Intent serviceIntent = new Intent(this, BroadcastService.class);
startService(serviceIntent);
}
@Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}

@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}

private BroadcastReceiver mReceiver = new BroadcastReceiver() {


@Override
public void onReceive(Context context, Intent intent) {
mTextView.setText(mTextView.getText()
+ "Broadcast From Service: \n");
if (intent.getAction().equals(mBroadcastStringAction)) {
mTextView.setText(mTextView.getText()
+ intent.getStringExtra("Data") + "\n\n");
} else if (intent.getAction().equals(mBroadcastIntegerAction)) {
mTextView.setText(mTextView.getText().toString()
+ intent.getIntExtra("Data", 0) + "\n\n");
} else if (intent.getAction().equals(mBroadcastArrayListAction)) {
mTextView.setText(mTextView.getText()
+ intent.getStringArrayListExtra("Data").toString()
+ "\n\n");
Intent stopIntent = new Intent(MainActivity.this,

8
BroadcastService.class);
stopService(stopIntent);
}
}
};

BroadcastService.Java
package com.example.ch5example3;

import android.annotation.TargetApi;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import java.util.ArrayList;

public class BroadcastService extends Service {


private String LOG_TAG = null;
private ArrayList<String> mList;
@Override
public void onCreate() {
super.onCreate();
LOG_TAG = this.getClass().getSimpleName();
Log.i (LOG_TAG, "In onCreate");
mList = new ArrayList<String>();
mList.add("Object 1");
mList.add("Object 2");
mList.add("Object 3");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOG_TAG, "In onStartCommand");
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.mBroadcastStringAction);
broadcastIntent.putExtra("Data", "Broadcast Data");
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.mBroadcastIntegerAction);
broadcastIntent.putExtra("Data", 10);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

9
broadcastIntent
.setAction(MainActivity.mBroadcastArrayListAction);
broadcastIntent.putExtra("Data", mList);
sendBroadcast(broadcastIntent);
}
}).start();
return START_REDELIVER_INTENT;
}
@Override
public IBinder onBind(Intent intent) {
// Wont be called as service is not bound
Log.i(LOG_TAG, "In onBind");
return null;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(LOG_TAG, "In onTaskRemoved");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
}

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

<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.Ch5Example3">
<service
android:name=".BroadcastService"
android:enabled="true"
android:exported="true"></service>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

10
Demo

11

You might also like