Search code examples
androidservicebroadcastreceiverforeground-servicebatterylevel

How to get the battery level in background and announce it?


In my app, I want to get the battery level in the background because I want to announce it in the text to speech when the battery level is low or when the battery is full or at any level. I have used the broadcast receivers and can get the battery level but don't know how to get it in the background. Anyone can help?


Solution

  • The thing that you want to achieve can be done via intent Service, if you dig in the docs you can find it yourself, here is the link Intent Service, This type of intent can be fired in the background and can be used to perform various simple operations such as yours, because they don't have any interface but rather just operations executed in background.

    Also here is a video guide Background Services which you can use for yourself to get battery percentage and announce it after a certain condition

    Edit 2:

    (Nothing Required in XML as this is a background process/operation) This is a code to get the battery percentage and announce it using Text to speech in broadcast receiver,

    MainActivity.java

    package com.example.text_to_speech;
    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.speech.tts.TextToSpeech;
    import android.widget.Button;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Intent intent=new Intent(this,myBackgroundProcess.class);
            intent.setAction("BackgroundProcess");
            PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
            AlarmManager alarmManger= (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManger.setRepeating(AlarmManager.RTC_WAKEUP,0,10,pendingIntent);//change this time based on your liking which will fire the intent
    
        }
    
    }
    

    customerclass- myBackgroundProcess.java

    package com.example.text_to_speech;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.os.BatteryManager;
    import android.speech.tts.TextToSpeech;
    import android.util.Log;
    
    import java.util.Locale;
    
    import static android.content.Context.BATTERY_SERVICE;
    
    public class myBackgroundProcess extends BroadcastReceiver {
        private TextToSpeech mTTS;
    
        @Override
        public void onReceive(Context context, Intent intent) {
            mTTS = new TextToSpeech(context.getApplicationContext(), new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {
                    if (status != TextToSpeech.ERROR) {
                        int result = mTTS.setLanguage(Locale.US);
    
                        if (result == TextToSpeech.LANG_MISSING_DATA
                                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                            Log.e("TTS", "Language not supported");
                            
                        } else {
    
                            BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
                            int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
                            if(batLevel==100 || batLevel<=10 || batLevel==50)
                            speak(context,batLevel);
    
                        }
                    } else {
                        Log.e("TTS", "Initialization failed");
                        
                    }
                }
            });
    
        }
        public void speak(Context context, int batlevel)
        {
            mTTS.setPitch(10);
            mTTS.setSpeechRate(1);
            String text=String.valueOf(batlevel);
            mTTS.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
    
    }
    

    In Android Manifest Register the receiver and add intent filter to it as shown below (below application tag)

    <receiver android:name=".myBackgroundProcess"
                android:enabled="true"
                android:exported="true"
                >
                <intent-filter>
                    <action android:name="BackgroundProcess"/>
                </intent-filter>
            </receiver>