IntentService থেকে শেয়ার ডায়ালগ খোলা
Intent Service ব্যাকগ্রাউন্ডে অ্যাসিঙ্ক্রোনাস অপারেশন করে। এই উদাহরণটি দেখায় কীভাবে IntentService থেকে শেয়ার ইন্টেন্ট পাঠানো যায়।
ধাপ ১: নতুন প্রজেক্ট তৈরি করুন
Android Studio-তে File → New Project-এ যান এবং প্রজেক্ট তৈরি করুন।
ধাপ ২: লেআউট ফাইলে কোড যোগ করুন
res/layout/activity_main.xml ফাইলে নিচের কোড যোগ করুন:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="সার্ভিস শুরু করুন"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ধাপ ৩: MainActivity.java-তে কোড যোগ করুন
package com.example.andy.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setOnClickListener(v -> {
startService(new Intent(MainActivity.this, MyService.class));
});
}
}
ধাপ ৪: Service ক্লাস তৈরি করুন
package com.example.andy.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends IntentService {
public MyService() {
super(MyService.class.getSimpleName());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "বিষয়");
sharingIntent.putExtra(Intent.EXTRA_TEXT, "Tutorialspoint.com");
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // সার্ভিস থেকে অ্যাক্টিভিটি শুরু করতে
startActivity(Intent.createChooser(sharingIntent, "শেয়ার করুন"));
stopSelf(); // সার্ভিস বন্ধ করা
}
}
গুরুত্বপূর্ণ: সার্ভিস থেকে অ্যাক্টিভিটি শুরু করতে Intent.FLAG_ACTIVITY_NEW_TASK ফ্ল্যাগ যোগ করা আবশ্যক।
ধাপ ৫: Manifest-এ সার্ভিস ডিক্লেয়ার করুন
<service android:name=".MyService" />
অ্যাপ্লিকেশন চালান
অ্যাপটি চালান। "সার্ভিস শুরু করুন" টেক্সটে ক্লিক করলে সার্ভিস শুরু হবে এবং সিস্টেম শেয়ার ডায়ালগ খুলবে।