Professional Documents
Culture Documents
_____________________________________________________________________________________
MainActivity.java
package com.example.androidserviceexample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
//Button objects
private Button buttonStart;
private Button buttonStop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onClick(View view) {
if(view == buttonStart){
//Start the service here
startService(new Intent(this, MyService.class));
super.onStart();
Toast.makeText(MainActivity.this,"Your service has started",
Toast.LENGTH_SHORT).show();
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:orientation="vertical"
tools:ignore="RtlCompat">
<Button
android:id="@+id/btnStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Start Service" />
<Button
android:id="@+id/btnStop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Stop Service" />
</LinearLayout>
</RelativeLayout>
Android_Manifest.xml
<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Output
Explaination
I create MyService extends service that has onStop method and onStartCommand. In method
onStartCommand, I set the loop to play the player non-stop when user hit button StartService. The
service doesn’t need user interaction and it runs on background. While method onStop contain a
function that will stop the player when the service is destroyed.
In MainActivity.java, there is a method that handle the functionality of the button. When a user hit the
start button, the player will start ring (from Myservice class) and will pop up small message “Your service
has started” because of the toast. Same as buttonStop. The toast provide a message directly after the
button has hit and automatically disappear after a timeout.