Android pause and resume downloading file to sdcard - android

I am making an application in which I need to download a file from server and save it to sd card of android device.
Apart of this there is a feature for the user to pause and resume the file.
The problem I am facing is that I am able to download file to sdcard but when try to pause and resume it, it gets starts from the beginning.......
Here is the source ......
public class DownloadWithProgressActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn, pauseButton, resumeButton;
private ProgressBar bar;
URLConnection conexion;
OutputStream output;
static int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button) findViewById(R.id.startBtn);
pauseButton = (Button) findViewById(R.id.button1);
resumeButton = (Button) findViewById(R.id.button2);
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setVisibility(ProgressBar.INVISIBLE);
bar.setId(0);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
resumeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// not getting what to write here
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String doInBackground(String... aurl) {
int downloaded = 0;
File file = new File("/sdcard/some_photo_from_gdansk_poland.jpg");
URL url = null;
try {
url = new URL(aurl[0]);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conexion = url.openConnection();
if (file.exists()) {
downloaded = (int) file.length();
conexion.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
else {
conexion.setRequestProperty("Range", "bytes=" + downloaded
+ "-");
}
} catch (Exception exception1) {
}
conexion.setDoInput(true);
conexion.setDoOutput(true);
System.out.println(tryGetFileSize(url));
conexion.setRequestProperty("Range", "bytes=" + count + "-");
try {
conexion.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = null;
try {
input = new BufferedInputStream(url.openStream());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte data[] = new byte[1024];
long total = 0;
try {
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
bar.setProgress(Integer.parseInt(progress[0]));
System.out.println(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String unused) {
}
int tryGetFileSize(URL url) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
return conn.getContentLength();
} catch (IOException e) {
return -1;
} finally {
conn.disconnect();
}
}
}
}
Please help.......
Thanks
Nikhil

connection.setRequestProperty("Range", "bytes=" + ***downloaded*** + "-");
Make "downloaded" as global variable, because download start from this position.
when you press on restart button, check value of this downloaded variable,must not zero all time.

This line return a wrong file size, I used the same code to open a Zip file on the net :
int lenghtOfFile = conexion.getContentLength();
How can I pause download other than by closing the output?
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
resumeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// not getting what to write here
}
});

Related

pausing download to add garbage to file then resuming - android

I wish to pause the file download at a particular point and add some bytes of data to it and then resume the download. How do I do it?
Below is a code snippet showing what I am downloading :-
private void startDownload() {
String url = "http://coderzheaven.com/sample_folder/sample_file.png";
new DownloadFileAsync().execute(url);
}
Now, below is the DownloadFileAsync class
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Length of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"downloaded_file.png");
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
connection.setRequestProperty("Range", "bytes=" + ***downloaded*** + "-");
Make "downloaded" as global variable, because download start from this position.
when you press on restart button, check value of this downloaded variable,must not zero all time.
Please change the things in below code
public class DownloadWithProgressActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn, pauseButton, resumeButton;
private ProgressBar bar;
URLConnection conexion;
OutputStream output;
static int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button) findViewById(R.id.startBtn);
pauseButton = (Button) findViewById(R.id.button1);
resumeButton = (Button) findViewById(R.id.button2);
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setVisibility(ProgressBar.INVISIBLE);
bar.setId(0);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
resumeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// not getting what to write here
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String doInBackground(String... aurl) {
int downloaded = 0;
File file = new File("/sdcard/some_photo_from_gdansk_poland.jpg");
URL url = null;
try {
url = new URL(aurl[0]);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conexion = url.openConnection();
if (file.exists()) {
downloaded = (int) file.length();
conexion.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
else {
conexion.setRequestProperty("Range", "bytes=" + downloaded
+ "-");
}
} catch (Exception exception1) {
}
conexion.setDoInput(true);
conexion.setDoOutput(true);
System.out.println(tryGetFileSize(url));
conexion.setRequestProperty("Range", "bytes=" + count + "-");
try {
conexion.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = null;
try {
input = new BufferedInputStream(url.openStream());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte data[] = new byte[1024];
long total = 0;
try {
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
bar.setProgress(Integer.parseInt(progress[0]));
System.out.println(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String unused) {
}
int tryGetFileSize(URL url) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
return conn.getContentLength();
} catch (IOException e) {
return -1;
} finally {
conn.disconnect();
}
}
}
}

Android Software caused connection abort and Async task

I use a bluetooth_access Async task to establish a connection and I need continue to use the input stream and out stream of the bluetooth socket I established.
The issue I having is when I clicked button1 or button2, it sometimes (not all the times) cause Software caused connection abort. It got tripped on out.write(bytes) when clicked.
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)this.findViewById(R.id.button1);
button2 = (Button)this.findViewById(R.id.button2);
button3 = (Button)this.findViewById(R.id.button3);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
try {
for (int i = 0; i < 3; i++) {
test();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean connected = false;
private BluetoothSocket sock;
private InputStream in;
private OutputStream out;
private Button button1;
private Button button2;
private Button button3;
private TextView data_t;
private BufferedReader in_read;
public void test() throws Exception {
if (connected) {
return;
}
new bluetooth_access().execute("");
}
#Override
public void onClick(View v){
// TODO Auto-generated method stub
if(v.equals(button1)){
String s = "turn left";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(v.equals(button2)){
String s = "turn right";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//new post_data().execute("");
}
if(v.equals(button3)){
String s = "read ADC";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class bluetooth_access extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
BluetoothDevice Pi = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice("00:15:83:0C:BF:EB");
Method m=null;
try {
m = Pi.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sock = (BluetoothSocket)m.invoke(Pi, Integer.valueOf(1));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sock.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("PiTest", "++++ Connected");
return null;
}
#Override
protected void onPostExecute(String result) {
;
TextView text = (TextView) findViewById(R.id.textView5);
text.setText("Connected through Bluetooth");
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
// original
try {
in = sock.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out=sock.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
You are trying to write to a socket stream from your main UI thread (from onClick), i would consider doing all socket communication from asynctask itself, or another thread if needed.
your connected variable is not being set, not sure if that was intentional, it can cause multiple execution of your bluetooth asynctask.

How to download all files from server to SD-card

I have several files uploaded to my server , now what i am trying to do is i want to download all files one by one and save it in to one folder.
So basically i was trying to do something like [this][1] but some how i am not able to achieve this so i think an alternate way to do it. So i am planning to download all audio file of particular folder of server to my SD-card folder and then i will give path of SD-card to list-view and play that audio.
So basically my question is how can i download all file from server folder to my SD-card folder.
I have below piece of code which is working fine for single file.
public class ServerFileList extends Activity {
Uri uri;
URL urlAudio;
ListView mListView;
ProgressDialog pDialog;
private MediaPlayer mp = new MediaPlayer();
private List<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.serverfilelist);
mListView = (ListView) findViewById(R.id.listAudio);
// new getAudiofromServer().execute();
new downloadAudio().execute();
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
playSong(urlAudio + myList.get(position));
}
});
}
public void updateProgress(int currentSize, int totalSize) {
TextView mTextView = new TextView(ServerFileList.this);
mTextView.setText(Long.toString((currentSize / totalSize) * 100) + "%");
}
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
class downloadAudio extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ServerFileList.this);
pDialog.setMessage("Downloading File list from server, Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// set the download URL, a url that points to a file on the internet
// this is the file to be downloaded
URL url = null;
try {
url = new URL("http://server/folder/uploadAudio/abcd.mp3");
} catch (MalformedURLException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
// create the new connection
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e5) {
// TODO Auto-generated catch block
e5.printStackTrace();
}
// set up some things on the connection
try {
urlConnection.setRequestMethod("GET");
} catch (ProtocolException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
urlConnection.setDoOutput(true);
// and connect!
try {
urlConnection.connect();
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
// set the path where we want to save the file
// in this case, going to save it on the root directory of the
// sd card.
String MEDIA_PATH = new String(
Environment.getExternalStorageDirectory()
+ "/newDirectory/");
File SDCardRoot = new File(MEDIA_PATH);
if (!SDCardRoot.exists()) {
SDCardRoot.mkdir();
}
// create a new file, specifying the path, and the filename
// which we want to save the file as.
File file = new File(SDCardRoot, System.currentTimeMillis()
+ ".mp3");
// this will be used to write the downloaded data into the file we
// created
FileOutputStream fileOutput = null;
try {
fileOutput = new FileOutputStream(file);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// this will be used in reading the data from the internet
InputStream inputStream = null;
try {
inputStream = urlConnection.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// this is the total size of the file
int totalSize = urlConnection.getContentLength();
// variable to store total downloaded bytes
int downloadedSize = 0;
// create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; // used to store a temporary size of the
// buffer
// now, read through the input buffer and write the contents to the
// file
try {
while ((bufferLength = inputStream.read(buffer)) > 0) {
// add the data in the buffer to the file in the file output
// stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
// add up the size so we know how much is downloaded
downloadedSize += bufferLength;
// this is where you would do something to report the
// prgress,
// like this maybe
updateProgress(downloadedSize, totalSize);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close the output stream when done
try {
fileOutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
// catch some possible errors...
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
class getAudiofromServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ServerFileList.this);
pDialog.setMessage("Getting File list from server, Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(String... arg0) {
try {
urlAudio = new URL("http://server/folder/uploadAudio");
} catch (MalformedURLException e) {
e.printStackTrace();
}
ApacheURLLister lister1 = new ApacheURLLister();
try {
myList = lister1.listAll(urlAudio);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
ServerFileList.this, android.R.layout.simple_list_item_1,
myList);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setCacheColorHint(Color.TRANSPARENT);
}
}
}
Try follow steps,
Write a server side component which will return back the list of the files in the directory in which all the audio files are hosted.
In your downloadAudio class, instead of downloading a file, initially make a call to the component described above to get the list.
Move the code which you have written in an function which will take String argument.
Loop on the url list from step 2 and call function in step 3 with parameter as current element of url list.
Keep all checks and balances to ensure all the files are downloaded.
Your issue is more of design issue then programming.
I have solved the problem by adding ivy jar file as a library and then added following code.
try {
urlAudio = new URL("http://server/folder/uploadAudio");
} catch (MalformedURLException e) {
e.printStackTrace();
}
ApacheURLLister lister1 = new ApacheURLLister();
try {
myList = lister1.listAll(urlAudio);
} catch (IOException e) {
e.printStackTrace();
}
return null;

display all textfiles in listview created by your app

The code creates a text file in local memory, but how do I get all files created by my application in a list view:
public class newfile extends Activity {
public EditText textBox,textbox2;
FileOutputStream fos=null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newfile);
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
textBox = (EditText) findViewById(R.id.txtText1);
textbox2 = (EditText) findViewById(R.id.fname);
String FILENAME = textbox2.getText().toString();
String value = textBox.getText().toString();
try{
fos = openFileOutput(FILENAME,MODE_WORLD_WRITEABLE);
}
catch(IOException e)
{
e.printStackTrace();
}
byte[] buffer = value.getBytes();
try {
fos.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_LONG).show();
finish();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
You can get a list all application files using Context.fileList. Then use ArrayAdapter to populate your list view

Receiving Info of a ShoutCast stream on Android

I am currently making an app to go with my online radio site, I am coding it with Android 2.2 (API 8) and I have got the Shoutcast Stream working with two buttons.
Here is the code on my main class:
public class GrooveOfMusicRadioActivity extends Activity {
/** Called when the activity is first created. */
MediaPlayer mediaPlayer;
Button start, stop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mediaPlayer.pause();
}
});
String url = "http://67.212.165.106:8161"; // your URL here
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException 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();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So I was wondering so how do I receive the stream title,song,artist etc.. and make it appear
The main XML is in a relative layout
Thanks, I am a total noob when it comes to programming.
Thanks mark :)
I just had to get meta data myself, I basically did the same stuff from: Pulling Track Info From an Audio Stream Using PHP. A lot of data is in the headers so you can use those, but all I wanted was the Stream Title, so thats what I got.
Activity mainAct = this;
public void getNowPlaying(View v) {
Log.w("getNowPlaying", "fired");
new Thread(new Runnable() {
public void run() {
String title = null, djName = null;
try {
URL updateURL = new URL(YOUR_STREAM_URL_HERE);
URLConnection conn = updateURL.openConnection();
conn.setRequestProperty("Icy-MetaData", "1");
int interval = Integer.valueOf(conn.getHeaderField("icy-metaint")); // You can get more headers if you wish. There is other useful data.
InputStream is = conn.getInputStream();
int skipped = 0;
while (skipped < interval) {
skipped += is.skip(interval - skipped);
}
int metadataLength = is.read() * 16;
int bytesRead = 0;
int offset = 0;
byte[] bytes = new byte[metadataLength];
while (bytesRead < metadataLength && bytesRead != -1) {
bytesRead = is.read(bytes, offset, metadataLength);
offset = bytesRead;
}
String metaData = new String(bytes).trim();
title = metaData.substring(metaData.indexOf("StreamTitle='") + 13, metaData.indexOf(" / ", metaData.indexOf("StreamTitle='"))).trim();
djName = metaData.substring(metaData.indexOf(" / ", metaData.indexOf("StreamTitle='")) + 3, metaData.indexOf("';", metaData.indexOf("StreamTitle='"))).trim();
Log.w("metadata", metaData);
is.close();
} catch (MalformedURLException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace(); }
final String titleFin = title;
final String djNameFin = djName;
mainAct.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mainAct, titleFin + "\n" + djNameFin, Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
What you're using to play the stream has no knowledge of (and doesn't care about) the metadata. You're going to have to deal with that separately.
See these posts for something you can easily adapt to Android:
Pulling Track Info From an Audio Stream Using PHP
http://www.smackfu.com/stuff/programming/shoutcast.html

Categories

Resources