在我的应用程序中,我想在后台获得电池电量,因为我想在电池电量低或电池电量满或处于任何电量时在文本中宣布它。我用过广播接收器,可以得到电池电量,但不知道如何在后台得到它。有人能帮忙吗?
你想要实现的东西可以通过intent Service来完成,如果你在文档中找到它,这里是链接intent Service,这种类型的intent可以在后台触发,可以用来执行各种简单的操作,比如你的操作,因为它们没有任何接口,而只是在后台执行的操作。
这里还有一个视频指南后台服务,你可以自己使用它来获取电池百分比,并在特定条件后公布
编辑2:
(XML中不需要,因为这是后台进程/操作)这是一个代码,用于获取电池百分比,并在广播接收器中使用文本到语音宣布它,
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);
}
}
在Android Manifest中注册接收器并添加意图过滤器,如下所示(在application标签下)
<receiver android:name=".myBackgroundProcess"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="BackgroundProcess"/>
</intent-filter>
</receiver>