请注意: 我正在backgroundService
中运行整个代码。
[我想要的是每当我将手机断开/连接到USB或AC适配器时,都会显示一条敬酒消息。
我的问题是,吐司消息会自动重复。 BroadcastReceiver
提供更新时,该方法会不断执行,并且吐司一遍又一遍地出现。
没有连接电缆时,将重复“已卸下充电”的吐司消息。当连接了交流适配器或USB充电器时,相应的消息。
import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.BatteryManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import static com.hashware.batteryalert.App.channelID;
public class MyService extends Service {
private static final String TAG = MyService.class.getSimpleName();
public int level, voltage, status, plugged;
private final IBinder iBinder = new bindingService();
private MediaPlayer player;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter intF = new IntentFilter();
intF.addAction(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(br,intF);
Log.d(TAG, "onStartCommand: ServiceStarted");
return START_STICKY;
}
// TODO: Fetching live battery data
BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);
status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,0);
plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,0);
switch (plugged){
case BatteryManager.BATTERY_PLUGGED_AC:
notificationCreate();
Toast.makeText(MyService.this,"Charging : AC Supply", Toast.LENGTH_SHORT).show();
break;
case BatteryManager.BATTERY_PLUGGED_USB:
notificationCreate();
Toast.makeText(MyService.this,"Charging : USB Supply", Toast.LENGTH_SHORT).show();
break;
case BatteryManager.BATTERY_PLUGGED_WIRELESS:
notificationCreate();
Toast.makeText(MyService.this,"Charging : Wireless Supply", Toast.LENGTH_SHORT).show();
break;
case 0:
stopForeground(true);
break;
}
// TODO: Notify Battery Status
if (status == BatteryManager.BATTERY_STATUS_FULL) {
if (player == null) {
player = MediaPlayer.create(MyService.this, R.raw.electric_shock01);
player.start();
player.setLooping(true);
}
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
if (player != null) {
player.release();
player = null;
Toast.makeText(MyService.this, "Disconnected After Full charge !", Toast.LENGTH_SHORT).show();
}
else if (player == null){
Toast.makeText(MyService.this, "Charging Removed !", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onReceive: BLANK");
}
}
}
};
[如果只需要检测手机何时与USB /适配器连接或断开连接,则可能应该监视充电状态的变化,而不是ACTION_BATTERY_CHANGED
。请参考此https://developer.android.com/training/monitoring-device-state/battery-monitoring#MonitorChargeState