من مستقیما ننوشتم sdcARD و طبق گفته ی شما نوشتم.اگر اجازه بدین کل کدها رو براتون می نویسم .از سایت شما هم استفاده کردم فقط ببخشید که طولانیه
هدف: دانلود از اینترنت و ذخیره ی فایل در حافظه و بعد اجرای همون فایل در یک محیطی مثل مدیاپلیر.
1- فایل Main_DownloadJirjirak.java. قراره فایل رو از یه آدرسی دانلود کنه و تو حافظه ذخیره کنه:
2- فایل یا همون اکتیویتی Main_JirjirakPage.java که وظیفه ی اجرای فایل دانلودی رو بر عهده داره.(اینجا ار raw میخونه ولی من میخوام از همون جایی که دانلود و ذخیره شده بخونه) :
اکتیویتی Main.java که صفح ه ی اولیه که تو اجرا نشون داده میشه :
هدف: دانلود از اینترنت و ذخیره ی فایل در حافظه و بعد اجرای همون فایل در یک محیطی مثل مدیاپلیر.
1- فایل Main_DownloadJirjirak.java. قراره فایل رو از یه آدرسی دانلود کنه و تو حافظه ذخیره کنه:
کد پیاچپی:
کد پیاچپی:
public class Main_DownloadJirjirak extends Activity {
public ProgressDialog mProgressDialog;
private Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_downloadjirjirak);
button1=(Button)findViewById(R.id.button1);
final DownloadTask downloadTask = new DownloadTask(Main_DownloadJirjirak.this); // MainActivity = activity name
// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(Main_DownloadJirjirak.this); // MainActivity = activity name
mProgressDialog.setMessage("File is downloading ...");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// execute this when the downloader must be fired
downloadTask.execute("https://yuma.servershost.net:2083/cpsess7509643735/download?skipencode=1&file=%2fhome%2fdastsazi%2fsound_gheseh%2fjirjirak.mp3"); // the url to the file you want to download
Intent Main_Page=new Intent(Main_DownloadJirjirak.this,Main.class) ;
startActivity(Main_Page);
}
});
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
@SuppressWarnings("resource")
@Override
protected String doInBackground(String... sUrl) {
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
wl.acquire();
try {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
File root = android.os.Environment.getExternalStorageDirectory();
File file = new File(root.getAbsolutePath() + "/jirjirak.mp3");
input= connection.getInputStream();
output = new FileOutputStream(root.getAbsolutePath() + "/jirjirak.mp3");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled())
return null;
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
}
catch (IOException ignored) { }
if (connection != null)
connection.disconnect();
}
} finally {
wl.release();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"Download completed ", Toast.LENGTH_SHORT).show();
}
}
}
2- فایل یا همون اکتیویتی Main_JirjirakPage.java که وظیفه ی اجرای فایل دانلودی رو بر عهده داره.(اینجا ار raw میخونه ولی من میخوام از همون جایی که دانلود و ذخیره شده بخونه) :
کد پیاچپی:
public class Main_JirjirakPage extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2000, backwardTime = 2000;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout of the Activity
setContentView(R.layout.main_jirjirakpage);
//initialize views
initializeViews();
}
public void initializeViews(){
songName = (TextView) findViewById(R.id.songName);
mediaPlayer = MediaPlayer.create(this,R.raw.jirjirak);
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
songName.setText("Sample_Song.mp3");
seekbar.setMax((int) finalTime);
seekbar.setClickable(false);
}
// play mp3 song
public void play(View view) {
try {
mediaPlayer.setDataSource("data/mine/jirjirak.mp3");
} 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();
}
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaing
double timeRemaining = finalTime - timeElapsed;
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
}
اکتیویتی Main.java که صفح ه ی اولیه که تو اجرا نشون داده میشه :
کد پیاچپی:
public class Main extends ActionBarActivity {
private ImageView imageView1_main_jirjirak;
private ImageView imageView1_main_moosh;
private ImageView imageView1_main_andaze_donya;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView1_main_jirjirak=(ImageView) findViewById(R.id.imageView1_main_jirjirak);
imageView1_main_moosh=(ImageView) findViewById(R.id.imageView1_main_moosh);
imageView1_main_andaze_donya=(ImageView) findViewById(R.id.imageView1_main_andaze_donya);
imageView1_main_jirjirak.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
File root = android.os.Environment.getExternalStorageDirectory();
File file2=new File(root.getAbsolutePath() + "/jirjirak.mp3");
if (file2.exists()){
Intent jirjirak=new Intent(Main.this,com.jirjirak.com.Main_JirjirakPage.class) ;
startActivity(jirjirak);
}
else
{
Intent mydownload=new Intent(Main.this,com.jirjirak.com.Main_DownloadJirjirak.class) ;
startActivity(mydownload);
}
}
});