2016-08-10 79 views
1

我已經制定了一種機制,可以檢測地圖中的位置並計算與用戶的距離(以米爲單位)。如何在Java Android的onLocationChanged中播放MediaPlayer一次?

我想播放原始音頻文件,如果這個位置是在期望的距離(在我的情況下在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米。

我知道它爲什麼會發生,但我找不到正確的方法來做到這一點。

任何人都可以幫助我嗎?

在此先感謝!

回答

1
@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米的圈內,它就會設置。如果是,它會讓你播放音頻,如果沒有,它不會做任何事情。我很抱歉我的英語,並希望我幫助你。

相關問題