我是软件开发的新手,我正在尝试制作一个在收费时发出声音的应用程序。我第一次将它连接到充电线时,它会播放两次声音,这是不可预期的。此外,当我连接和断开电缆太快时,它也会播放两次。 有谁知道这个问题的解决方案?
package com.mccharginggimmick;
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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
IntentFilter intentFilter;
BroadcastReceiver broadcastReceiver;
MediaPlayer mediaPlayerOff;
MediaPlayer mediaPlayerOn;
boolean playedOnceOn;
boolean playedOnceOff;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging){
onCharge();
}
else{
onDisconnect();
}
}
};
MainActivity.this.registerReceiver(broadcastReceiver, intentFilter);
}
public void onCharge(){
if(!playedOnceOn){
imageView.setVisibility(View.INVISIBLE);
mediaPlayerOn = MediaPlayer.create(this, R.raw.btnon);
mediaPlayerOn.start();
mediaPlayerOn.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayerOn.stop();
playedOnceOn = true;
playedOnceOff = false;
}
});
}
}
public void onDisconnect(){
if(!playedOnceOff){
imageView.setVisibility(View.VISIBLE);
mediaPlayerOff = MediaPlayer.create(this, R.raw.btnoff);
mediaPlayerOff.start();
mediaPlayerOff.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayerOff.stop();
playedOnceOff = true;
playedOnceOn = false;
}
});
}
}
}
答案 0 :(得分:0)
在类
中定义isCabelConnected
boolean isCabelConnected = false;
然后在onClick
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
boolean isFullCharged = status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging && !isCabelConnected){
onCharge();
isCabelConnected = true;
} else if (isFullCharged && isCabelConnected){
onCharge();
}
else{
onDisconnect();
isCabelConnected = false;
}
此代码将在连接电缆时发出声音,在完全充电时发出另一声音