এন্ড্রয়েডে BroadcastReceiver দিয়ে চার্জিং স্ট্যাটাস জানা
এই উদাহরণে দেখানো হয়েছে কিভাবে BroadcastReceiver ব্যবহার করে ডিভাইসের পাওয়ার কেবল সংযুক্ত হলে তা শনাক্ত করা যায়।
পদক্ষেপ ১: নতুন প্রজেক্ট তৈরি করুন
Android Studio-তে File → New Project এ যান এবং প্রজেক্টের জন্য প্রয়োজনীয় বিবরণ পূরণ করুন।
পদক্ষেপ ২: লেআউট ফাইল সংশোধন করুন (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
পদক্ষেপ ৩: MainActivity.java-তে BroadcastReceiver লজিক যোগ করুন
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(mMessageReceiver);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mMessageReceiver, new IntentFilter(Intent.ACTION_POWER_CONNECTED));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
textView.setText("ডিভাইস পাওয়ার সংযুক্ত হয়েছে");
}
};
}
অ্যাপ্লিকেশন চালান
ডিভাইস কম্পিউটারের সাথে সংযুক্ত থাকলে, Android Studio-তে Run আইকনে ক্লিক করে অ্যাপটি চালান। চার্জার সংযুক্ত করলে "ডিভাইস পাওয়ার সংযুক্ত হয়েছে" মেসেজ দেখাবে।