如何在 Java Android 的 onLocationChanged 中播放一次 MediaPlayer?
How to play MediaPlayer once in onLocationChanged in Java Android?
我已经开发了一种机制,可以检测地图中的位置并计算它与用户的距离(以米为单位)。
如果该位置在所需距离内(在我的例子中是 30 米),我想播放原始音频文件。
我已经在我的 onLocationChanged() 中编写了这段代码
@Override
public void onLocationChanged(Location location) {
try {
float dis = calcdist(location.getLatitude(),location.getLongitude,lat,lng);
if(dis <= 30) {
MediaPlayer mp = MediaPlayer.create(this,R.raw.sound);
mp.setLooping(false);
mp.start();
} else {
mp.stop();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
}
现在的问题是,每当用户移动时,它会再次启动该功能并一遍又一遍地播放声音,直到距离超过 30 米。
我知道为什么会这样,但我找不到正确的方法。
谁能帮帮我?
提前致谢!
@Override
public void onLocationChanged(Location location) {
try {
int a = 0;
float dis = calcdist(location.getLatitude(),location.getLongitude,lat,lng);
if(dis <= 30) {
int a = a+1; //add 1 if you are in the circle
if(a = 1) { //if a=1 it will do the rest
MediaPlayer mp = MediaPlayer.create(this,R.raw.sound);
mp.setLooping(false);
mp.start();
} else {
mp.stop();
}
}
//if you are not int he circle
if(dis > 30) {
int a = 0;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
}
这个呢?如果您已经在那个 30 米的圆圈内,它就会设置。如果是,它会让你播放那个音频,如果不是,它不会做任何事情。我很抱歉我的英语不好,希望我能帮到你。
我已经开发了一种机制,可以检测地图中的位置并计算它与用户的距离(以米为单位)。
如果该位置在所需距离内(在我的例子中是 30 米),我想播放原始音频文件。
我已经在我的 onLocationChanged() 中编写了这段代码
@Override
public void onLocationChanged(Location location) {
try {
float dis = calcdist(location.getLatitude(),location.getLongitude,lat,lng);
if(dis <= 30) {
MediaPlayer mp = MediaPlayer.create(this,R.raw.sound);
mp.setLooping(false);
mp.start();
} else {
mp.stop();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
}
现在的问题是,每当用户移动时,它会再次启动该功能并一遍又一遍地播放声音,直到距离超过 30 米。
我知道为什么会这样,但我找不到正确的方法。
谁能帮帮我?
提前致谢!
@Override
public void onLocationChanged(Location location) {
try {
int a = 0;
float dis = calcdist(location.getLatitude(),location.getLongitude,lat,lng);
if(dis <= 30) {
int a = a+1; //add 1 if you are in the circle
if(a = 1) { //if a=1 it will do the rest
MediaPlayer mp = MediaPlayer.create(this,R.raw.sound);
mp.setLooping(false);
mp.start();
} else {
mp.stop();
}
}
//if you are not int he circle
if(dis > 30) {
int a = 0;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
}
这个呢?如果您已经在那个 30 米的圆圈内,它就会设置。如果是,它会让你播放那个音频,如果不是,它不会做任何事情。我很抱歉我的英语不好,希望我能帮到你。