সিঙ্গলটন মিডিয়া প্লেয়ার বাস্তবায়ন
সিঙ্গলটন ডিজাইন প্যাটার্ন মিডিয়া প্লেয়ারের একক ইনস্ট্যান্স নিশ্চিত করে, যা রিসোর্স লিক এবং একাধিক প্লেব্যাক রোধ করে।
ধাপ ১: প্রজেক্ট তৈরি
Android Studio-তে নতুন প্রজেক্ট তৈরি করুন। res/raw ফোল্ডারে sample.mp3 রাখুন।
ধাপ ২: লেআউট (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/show"
android:text="সিঙ্গলটন থেকে গান চালান"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
ধাপ ৩: MainActivity.java
package com.example.mediaplayersingleton;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button show;
SingleTonExample singletonExample;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = findViewById(R.id.show);
singletonExample = SingleTonExample.getInstance();
singletonExample.init(getApplicationContext());
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mediaPlayer = singletonExample.getSingletonMedia();
mediaPlayer.start();
}
});
}
}
ধাপ ৪: সিঙ্গলটন ক্লাস (SingleTonExample.java)
package com.example.mediaplayersingleton;
import android.content.Context;
import android.media.MediaPlayer;
public class SingleTonExample {
private static MediaPlayer mediaPlayer;
private static SingleTonExample ourInstance = new SingleTonExample();
private Context appContext;
private SingleTonExample() { }
public static Context get() {
return getInstance().getContext();
}
public static synchronized SingleTonExample getInstance() {
return ourInstance;
}
public void init(Context context) {
if (appContext == null) {
this.appContext = context;
}
}
private Context getContext() {
return appContext;
}
public static MediaPlayer getSingletonMedia() {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(get(), R.raw.sample);
}
return mediaPlayer;
}
}
সেরা অনুশীলন
- MediaPlayer রিলিজ করতে onDestroy()-এ cleanup করুন
- এরর হ্যান্ডলিং যোগ করুন
- লুপিং, পজেশন কন্ট্রোল ইত্যাদি ফিচার যোগ করুন
পরিচালনা
অ্যাপ্লিকেশন চালান। বাটনে ক্লিক করলে সিঙ্গলটন মিডিয়া প্লেয়ার থেকে গান বাজাবে।