Android Programming

Hands On No. 17 : Creating Application as Service

Source Code of backgroud_demo.java
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;

public class backgroud_demo extends Service {

private MediaPlayer mplayer;


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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mplayer = MediaPlayer.create(this,
R.raw.iphone);
mplayer.setLooping(true);
mplayer.start();
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
mplayer.stop();
}
}
Source Code of MainActivity.java
import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button play,stop1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button) findViewById(R.id.btn1);

stop1 = (Button) findViewById(R.id.btn3);
play.setOnClickListener(this);
stop1.setOnClickListener(this);

}
@Override
public void onClick(View view) {
if (view == play) {
startService(new Intent(this, backgroud_demo.class));

} else if (view == stop1) {
stopService(new Intent(this, backgroud_demo.class));

}
}


}
Source Code of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >

<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="PLAY" android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
/>

<Button
android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="STOP" android:layout_marginTop="40dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp" />

</LinearLayout>

Add below line in AndroidManifest.xml

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