我使用以下代码播放音频文件(.wav),但当活动处于横向模式时,它会播放带有Echo的文件(如同时播放两个声音)。
public class Find_n_Display_StationActivity extends Activity
{
GPSTracker gps;
TextView txtvw,locNameTV;
boolean calculating_distance=false;
ArrayList<String>data=new ArrayList<String>();
ArrayList<String>latArray=new ArrayList<String>();
ArrayList<String>longArray=new ArrayList<String>();
MySQLiteHelper db = new MySQLiteHelper(this);
ImageView profileIV;
PendingIntent intent;
String reached_station="empty";
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.find_n__display__statn_activity);
txtvw=(TextView)findViewById(R.id.textView2);
locNameTV=(TextView)findViewById(R.id.textView1);
profileIV=(ImageView)findViewById(R.id.image11);
profileIV.setVisibility(View.GONE);
//Put in LANDSCAPE MODE...
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//Show FULL-SCREEN Activity
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Calling/Starting Thread to Handl Uncaught Exeption
Thread.setDefaultUncaughtExceptionHandler(onRuntimeError);
//(((( This will retrieve DATA from service to this Activity ))))
gps = new GPSTracker(this);
LocalBroadcastManager.getInstance(this.getApplicationContext()).registerReceiver(
mMessageReceiver, new IntentFilter("GPSLocationUpdates"));
// mp=new MediaPlayer();
}//EOF Oncreate Method...
//(((( This Function is Called if App Crash, So, App is start Automatically after crash ))))
private Thread.UncaughtExceptionHandler onRuntimeError= new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread thread, Throwable ex)
{
Intent i=new Intent(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
};
// (((( This Class Get Data From Service class GPSTracker.class() ))))
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("Status");
Bundle b = intent.getBundleExtra("Location");
Location lastKnownLoc = (Location) b.getParcelable("Location");
if (lastKnownLoc != null)
{
String s1=String.valueOf(lastKnownLoc.getLatitude());
String s2=String.valueOf(lastKnownLoc.getLongitude());
double current_lat=Double.parseDouble(s1);
double current_long=Double.parseDouble(s2);
txtvw.setText("____________________________\n\n\n"+current_lat+"\n"+current_long);
//showtoast("You have changed your Location");
if(calculating_distance==false)
{
calculating_distance=true;
FindDistance(current_lat,current_long);
}
Turn_On_Screen();
}
}};
private String stationPlayed="empty";
@SuppressWarnings("deprecation")
public void Turn_On_Screen()
{
WakeLock screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
screenLock.acquire();
//later
//screenLock.release();
}
//(((( Find Distance Betwee All Points ))))))
public void FindDistance(double current_lat,double current_long)
{
Move_App_Back_to_ForeGround();
ArrayList<String>stationNameArray=new ArrayList<String>();
ArrayList<String>imageArray=new ArrayList<String>();
ArrayList<String>voiceArray=new ArrayList<String>();
imageArray=db.Get_ImageList();
voiceArray=db.Get_VoiceList();
stationNameArray=db.Get_StionNameAraay();
latArray=db.Get_LatAraay();
longArray=db.Get_LongAraay();
float smallest_dis=10000;
String next_station="";
boolean found_station=false;
for(int i=1;i<latArray.size();i++)
{
float lat1 = Float.parseFloat(latArray.get(i));
float long1 = Float.parseFloat(longArray.get(i));
float dis=FindDistance((float)current_lat,(float)current_long,lat1, long1);
if(dis<smallest_dis)
{
smallest_dis=dis;
next_station=stationNameArray.get(i);
}
if(dis<=50)
{
Set_Pic_n_Voice(imageArray.get(i),voiceArray.get(i),stationNameArray.get(i));
// showtoast("station-name="+ stationNameArray.get(i));
break;
}
}
locNameTV.setText("You are Heading towards Station="+next_station+"\n You are only "+smallest_dis+" Meter away...");
calculating_distance=false;
}
public void Set_Pic_n_Voice(String image,final String voice,final String station_name)
{
DisplayImage(image);
if(!reached_station.equalsIgnoreCase(station_name))
reached_station=""+station_name; //Don't play voice for same station just display pic always
//Wait for 4 seconds to play this voice
Runnable r = new Runnable()
{
public void run()
{
if(!stationPlayed.equalsIgnoreCase(station_name))
{
PlayVoice(voice);
stationPlayed=station_name;
}
}
};
android.os.Handler h = new android.os.Handler();
h.postDelayed(r, 5000);// */
}
//(((( Displaying Picture For the Station ))))
public void DisplayImage(String image)
{
profileIV.setVisibility(View.VISIBLE);
File imageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"Bus_StationApp_Folder/Images",image);
if (imageFile.exists())
{
File imgFile = new File(imageFile.getAbsolutePath()); // path of your file
Picasso.with(this).load(Uri.fromFile(new File(imageFile.getAbsolutePath()))).into(profileIV);
/*
FileInputStream fis = null;
try {
fis = new FileInputStream(imgFile);
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 8;
//options.inPurgeable = true;
// options.inScaled = true;
Bitmap bm = BitmapFactory.decodeStream(fis, null,options);
profileIV.setImageBitmap(bm);//*/
}
else
profileIV.setImageResource(R.drawable.default_station_pic);
}
//(((( Playing Voice For The Station ))))))
public void PlayVoice(String voice)
{
calculating_distance=true;
// Play_Audio_File ob=new Play_Audio_File(this);
//ob.PlayVoice(voice);
File voiceFile = new File(Environment.getExternalStorageDirectory()+File.separator+"Bus_StationApp_Folder/Voices",voice);
if (voiceFile.exists())
{
if(!mp.isPlaying())
{
mp.reset();
try {
mp.setDataSource(voiceFile.getAbsolutePath());
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
calculating_distance=false;
}
});
}
else
{
//mp.reset();
mp= MediaPlayer.create(this, R.drawable.default_station_voice);
if(!mp.isPlaying())
{
mp.start();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
calculating_distance=false;
}
});
}
//*/
}
//((((( Find distance between two geolocation )))
public float FindDistance(float lat1, float lng1, float lat2, float lng2)
{
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
//((( Move App To Screen from Background ))))
public void Move_App_Back_to_ForeGround()
{
boolean foregroud=false;
try
{
foregroud = new ForegroundCheckTask().execute(getApplicationContext()).get();
} catch (InterruptedException e)
{ e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
if(!foregroud)
{
//Open Activity IF it is in Background...
Intent it = new Intent("intent.my.action");
it.setComponent(new ComponentName(this.getPackageName(), Find_n_Display_StationActivity.class.getName()));
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.getApplicationContext().startActivity(it);
}
}
class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {
@Override
protected Boolean doInBackground(Context... params) {
final Context context = params[0].getApplicationContext();
return isAppOnForeground(context);
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
//SHOW-TOAST-MESSAGE
public void showtoast(String str)
{
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
public void OnBackPressed()
{
}
} // EOF活动......
答案 0 :(得分:1)
你以某种方式调用PlayVoice()
方法两次。你的内部if
语句阻止这种情况的原因是因为你必须在调用mp = new MediaPlayer();
之前调用PlayVoice()
,否则第一次调用该方法会导致{{1来自NullPointerException
条件中的mp.isPlaying()
调用。由于if
现在指向新的mp
实例,MediaPlayer
会返回isPlaying()
,并且false
块会再次执行,即使前一个实例仍在播放。
要防止同时播放if
个多个实例,请在声明行中仅对MediaPlayer
实例化一次,移除MediaPlayer
中的mp = new MediaPlayer();
行(以及您可能在其他任何地方)拥有它,并取消评论那里的PlayVoice()
电话。
mp.reset();
方法被调用两次,因为您在PlayVoice()
的{{1}}方法中要求更改横向广告,并且您正在使用Activity
方法。不要自己处理配置更改。这导致以纵向模式启动的onCreate()
被销毁并重新创建,这意味着Activity
第二次运行,但在第一个onCreate()
实例中启动的MediaPlayer
是在第二个实例中创建并启动新的时仍在播放。
您可以通过强制Activity
从一开始就以横向方向启动来防止这种情况发生。您可以通过将Activity
添加到清单中的android:screenOrientation="landscape"
标记来执行此操作。您也可以立即删除<activity>
来电,因为不再需要它。