Android_Slip_3B

Step1:

Open Android Studio and create a new project with an Empty Activity template.

In the res/layout/activity_main.xml file, add a Button widget:

    <Button
    android:id="@+id/buttonStartService"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Audio Service"
    android:onClick="startAudioService"/>

Step 2:

Create a new Java class for the AudioService that extends Service:
    import android.app.Service;
    import android.content.Intent;
    import android.media.MediaPlayer;
    import android.os.IBinder;

    public class AudioService extends Service {

    private MediaPlayer mediaPlayer;

    @Override
    public void onCreate() {
    super.onCreate();
    mediaPlayer = MediaPlayer.create(this, R.raw.your_audio_file);
    // Replace with your audio file
    mediaPlayer.setLooping(true);
    // To loop the audio
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    mediaPlayer.start();
    return START_STICKY;
    }

    @Override
    public void onDestroy() {
    super.onDestroy();
    mediaPlayer.stop();
    mediaPlayer.release();
    }

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

In the MainActivity.java file, implement the startAudioService method:
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import androidx.appcompat.app.AppCompatActivity;

    public class MainActivity extends AppCompatActivity {

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

    public void startAudioService(View view) {
    startService(new Intent(this, AudioService.class));
    }
    }

No comments:

Post a Comment