请注意: 我正在
backgroundService
中运行整个代码。我只想在手机中连接USB或AC适配器时显示一条吐司消息(每个操作仅一次),>]
但是问题是,如果在所有时间自动重复敬酒消息。由于
BroadcastReceiver
已在不断提供更新,因此该方法每次都会执行,并且吐司会一次又一次地重复。例如如果电缆断开连接,则为USB或交流适配器,并且在断开连接的情况下,即使在连接了充电器,交流适配器或USB的情况下,也会重复显示“ Charging Removed”的祝酒消息。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"); } } } };
[请注意:我正在backgroundService中运行整个代码。我只想在手机上连接USB或AC适配器时显示一条吐司消息(每个动作仅一次),但...
[如果只需要检测手机何时与USB /适配器连接或断开连接,则可能应该监视充电状态的变化,而不是ACTION_BATTERY_CHANGED
。请参考此https://developer.android.com/training/monitoring-device-state/battery-monitoring#MonitorChargeState