如果存在文件,在sdcard中播放音乐

时间:2014-02-04 11:23:29

标签: android android-sdcard android-music-player

我正在播放SD卡中的音乐而文件存在它正在播放音乐文件但是如果它不存在我的应用程序崩溃我该怎么办?

package com.example.downloadplay;

public class AudioPlayer extends Activity implements OnClickListener {
Button playButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

playButton = (Button) this.findViewById(R.id.ButtonPlayStop);
playButton.setOnClickListener(this);
}

public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/bluetooth/یه سوال دارم مگه.mp3");

 intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
 startActivity(intent);
 }
 }

3 个答案:

答案 0 :(得分:1)

检查文件是否存在

if(audioFile.exists())
{
  intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
  startActivity(intent);
}
else
{
   // show error
}

答案 1 :(得分:1)

您可以使用File.exists()

检查文件是否存在
File f = new File(filePathString);
if(f.exists())
{ 
 //Play your sound
}
else
{
  //And your other stuffs goes here
}
  

注意exists()也会为目录返回

答案 2 :(得分:0)

使用以下代码。

if(audioFile.exists())
{
  intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
  startActivity(intent);
}
else
{
   Builder alert = new AlertDialog.Builder(activity_name.this);
                    alert.setTitle("Alert");
                    alert.setMessage("File does not exist");
                    alert.setPositiveButton("OK", null);
                    alert.show();
}
相关问题