Slow rate (Rx) retrieving an attachment from Gmail with javaMail on Android - android

I'm using JavaMail libraries to access Gmail and I'm getting a slow rate (Rx) performance in downloading a compressed file attachment (1 MB):
As you can see, getting the attachment and write it into SD takes around 20 seconds.
Here is my code:
public class MailFile {
InputStream is;
String fileName;
public MailFile( InputStream is, String fileName) {
this.is = is;
this.fileName = fileName;
}
public InputStream getIs() {
return is;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}}
Retrieving a message:
private List<MailFile> getAttachments(Message temp) throws Exception {
List<MailFile> attachments = new ArrayList<MailFile>();
Multipart multipart = (Multipart) temp.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.getFileName()!=null && (bodyPart.getFileName().contains(ZIP_EXT) || bodyPart.getFileName().contains(XLSX_EXT)))
attachments.add(new MailFile(bodyPart.getInputStream(), bodyPart.getFileName()));
}
return attachments;
}
protected String doInBackground(String... params) {
try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
Properties props = new Properties();
//IMAPS protocol
props.setProperty("mail.store.protocol", "imaps");
//Set host address
props.setProperty("mail.imaps.host", "imaps.gmail.com");
//Set specified port
props.setProperty("mail.imaps.port", "993");
//Using SSL
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.partialfetch", "false"); //this line solved my problem
Session imapSession = Session.getInstance(props);
Store store = imapSession.getStore("imaps");
store.connect("imap.gmail.com", SP.getString("incomingMail", activity.getString(R.string.confIncomingDefaultValue)), SP.getString("passwordMail", activity.getString(R.string.confIncomingDefaultValue)));
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
Message msgArr[] = inbox.search(this.searchTerm);
//Message msg = inbox.getMessage(inbox.getMessageCount());
if (msgArr.length > 0) {
Message msg = msgArr[msgArr.length - 1]; //only last message
Object content = msg.getContent();
if (content instanceof Multipart) //si és un correu amb attach
{
Multipart mp = (Multipart) content;
for (MailFile f : getAttachments(msg)) {
if (f.getFileName().contains(XLSX_EXT)) {
new XLSXReader(f.getIs());
// msg.setFlag(Flags.Flag.DELETED, true);
} else if (f.getFileName().contains(ZIP_EXT)) {
long startTime = System.currentTimeMillis();
writeToFile(f.getIs(),new FileOutputStream(f.getFileName()));
long duration = System.currentTimeMillis() - startTime;
Log.d("Time", "Time " + duration + "ms " + duration / 1000.0f + " sec");
ZipperFolders.unzipFile(unzipPath, f.getFileName());
loadZipObjects(f.getFileName());
}
}
doToast(activity.getString(R.string.messagesReceivedOK));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
((PrincipalActivity) activity).setDate(null, false);
}
});
} else
doToast(activity.getString(R.string.messagesReceivedKO));
} else
doToast(activity.getString(R.string.messagesNoneMessages, SP.getString("incomingMail", activity.getString(R.string.confIncomingDefaultValue))));
inbox.close(true);
store.close();
} catch (Exception e) {
e.printStackTrace();
doToast(activity.getString(R.string.messagesConnectionKO));
}
return activity.getString(R.string.messagesReceived);
}
I've tried to use MimeMessage but the result it's the same. If I donwload the same file inside the Gmail app it takes 2 seconds!. What's happening? Is Gmail limiting my bandwith? Am I doing something wrong? Thanks!
EDIT: I've solved myproblem adding props.setProperty("mail.imaps.partialfetch", "false"); before declaring the Session object.
This is the resultant Rx:
From 20 sec. to 2 sec. unbelievable!!

Related

The App connection is timing out before the server could process the data

The app that I Built connects to a local server which I have built in flask, But the python program takes time to execute and the client app closes the connection without taking the return statement and goes to the catch block and says Failed!!!. So what should I do to maintain the connection. I want to show a processing bar or
**
the server should notify the app when done with processing
**
I guess I can even build another button to get the processed data (so I will need notification that the processing is completed)
So what should I do. Can someone guide me in detail?Thanks.
enter code here''' `
import flask
import werkzeug
import time
from flask import flash
app = flask.Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def handle_request():
files_ids = list(flask.request.files)
print("\nNumber of Received Images : ", len(files_ids))
image_num = 1
for file_id in files_ids:
print("\nSaving Image ", str(image_num), "/", len(files_ids))
imagefile = flask.request.files[file_id]
filename = werkzeug.utils.secure_filename(imagefile.filename)
print("Image Filename : " + imagefile.filename)
timestr = time.strftime("%Y%m%d-%H%M%S")
imagefile.save(timestr + '_' + filename)
image_num = image_num + 1
print("\n")
// flash("Connected")
return "Image(s) Uploaded Successfully. Come Back Soon."
app.run(host="0.0.0.0", port=5000, debug=True)
'''
This is the flask code which accepts the incoming connection.
public void connectServer(View v) {
TextView responseText = findViewById(R.id.responseText);
if (imagesSelected == false) { // This means no image is selected and thus nothing to upload.
responseText.setText("No Image Selected to Upload. Select Image(s) and Try Again.");
return;
}
responseText.setText("Sending the Files. Please Wait ...");
EditText ipv4AddressView = findViewById(R.id.IPAddress);
String ipv4Address = ipv4AddressView.getText().toString();
EditText portNumberView = findViewById(R.id.portNumber);
String portNumber = portNumberView.getText().toString();
Matcher matcher = IP_ADDRESS.matcher(ipv4Address);
if (!matcher.matches()) {
responseText.setText("Invalid IPv4 Address. Please Check Your Inputs.");
return;
}
String postUrl = "http://" + ipv4Address + ":" + portNumber + "/";
MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (int i = 0; i < selectedImagesPaths.size(); i++) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
// Read BitMap by file path.
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagesPaths.get(i), options);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
}catch(Exception e){
responseText.setText("Please Make Sure the Selected File is an Image.");
return;
}
byte[] byteArray = stream.toByteArray();
multipartBodyBuilder.addFormDataPart("image" + i, "Android_Flask_" + i + ".jpg", RequestBody.create(MediaType.parse("image/*jpg"), byteArray));
}
RequestBody postBodyImage = multipartBodyBuilder.build();
postRequest(postUrl, postBodyImage);
}
void postRequest(String postUrl, RequestBody postBody) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(postUrl)
.post(postBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// Cancel the post on failure.
call.cancel();
Log.d("FAIL", e.getMessage());
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView responseText = findViewById(R.id.responseText);
responseText.setText("Failed to Connect to Server. Please Try Again.");
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView responseText = findViewById(R.id.responseText);
try {
responseText.setText("Server's Response\n" + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
'''
And This is my android studio connect server code
For getting the image from server to your app use
Picasso.get()
.load("*The link of your server*")
.into(imageView);

Background traffic managment in android

I'm developing an android App that collect some data from 4 sensors via Bluetooh and at the end send the data to a SFTP server.
I'm using the JSCh (ChannelSftp), the thing works fine with some servers, but with the server of my University the App crash.
I have performed a deep debug with the IT officer and we discovered that once the SSH channel is open some background traffic arrives to the server (ex.: myIP --- otherIP--- packet). At that point the firewall close the connection and the App crash.
Is there a way to block the background traffic for a small window of time from the App?. Has anyone had the same problem as me?
Thanks in advance
public class SftpClass extends AsyncTask <Object, Void, String> {
private Context context;
private long size;
private long fileSize;
public SftpClass (Context con){
context = con;
size = 0;
fileSize = -1;
}
#Override
protected String doInBackground(Object... params){
//Params: File file, String host, String port, String username, String password
File file = (File) params[0];
String host = (String) params[1];
String port = (String) params[2];
String username = (String) params[3];
String password = (String) params[4];
String path = (String) params[5];
int portnumber = Integer.valueOf(port);
fileSize = file.length();
String localFilePath = file.getAbsolutePath();
String fileName = localFilePath.substring(localFilePath.lastIndexOf("/") + 1);
String remoteFilePath = fileName;
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(username, host, portnumber);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
final ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.put(localFilePath, path+remoteFilePath);
try
{
Thread.sleep(3000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
SftpATTRS attrs = null;
try {
attrs = sftpChannel.lstat(path+remoteFilePath);
} catch (SftpException e) {
e.printStackTrace();
}
if ( attrs != null){
size = attrs.getSize();
}
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
if (size == fileSize){
Toast.makeText(context, "File uploaded\n"+Long.toString(size)+"Bytes", Toast.LENGTH_SHORT).show();
}
}
}

message.getContent returns null despite being able to get numbers of mails in inbox correctly

I'm using JavaMail API to read emails in my Android app. I debugged my app to find that the number of Message objects in the array are equal to the number of emails I have in my inbox but I'm always getting null when trying to use getContent on the message object. I'm using the jars found here. I'm using imap.gmail.com with all the correct details. I even tried a different email service called mail.com but the error still remains. I'm providing only the method I use to read emails. You can assume everything else is correct.
Code:-
private void initMail(String hostval, String mailStrProt, String uname, String pwd, String authEmail, int mode)
{
uriArrayList = new ArrayList<>();
try {
Log.d("LOGCAT","initMail");
//Set property values
Properties propvals = new Properties();
propvals.put("mail.store.protocol", mailStrProt);
propvals.put("mail.imap.user", uname);
propvals.put("mail.imap.ssl.enable", "true");
propvals.put("mail.imap.host", hostval);
propvals.put("mail.imap.port", "993");
propvals.put("mail.imap.starttls.enable", "true");
Session emailSessionObj = Session.getInstance(propvals, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(uname, pwd);
}
});
//Create POP3 store object and connect with the server
Store storeObj = emailSessionObj.getStore(mailStrProt);
storeObj.connect(hostval, uname, pwd);
//Create folder object and open it in read-only mode
Folder emailFolderObj = storeObj.getFolder("INBOX");
emailFolderObj.open(Folder.READ_ONLY);
//Fetch messages from the folder and print in a loop
Message[] messageobjs = emailFolderObj.getMessages();
for (Message message : messageobjs) {
if(message.getFrom()[0].toString().equals(authEmail)) {
if(message.getContent() instanceof String) { Log.d("LOGCAT","String"); uriArrayList.add(stringToUri(message.getContent().toString())); }
else if(message.getContent() instanceof Multipart) {
Multipart multipart = (Multipart) message.getContent();
MimeBodyPart mimeBodyPart;
for(int i = 0 ; i < multipart.getCount() ; i++) {
if(MimeBodyPart.ATTACHMENT.equalsIgnoreCase(multipart.getBodyPart(i).getDisposition())) {
mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(i);
File file = new File(mimeBodyPart.getFileName());
mimeBodyPart.saveFile(file);
uriArrayList.add(Uri.fromFile(file));
}
}
}
lastReceivedMailDate = message.getSentDate().toString();
}
}
//Now close all the objects
emailFolderObj.close(false);
storeObj.close();
} catch (NoSuchProviderException exp) {
exp.printStackTrace();
} catch (MessagingException exp) {
exp.printStackTrace();
} catch (Exception exp) {
exp.printStackTrace();
}
}
EDIT:
for (Message message : messageobjs) {
Multipart multipart = (Multipart) message.getContent();
MimeBodyPart mimeBodyPart;
for(int i = 0 ; i < multipart.getCount() ; i++) {
mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(i);
File file = new File(mimeBodyPart.getFileName()); //line number 204
mimeBodyPart.saveFile(file);
uriArrayList.add(Uri.fromFile(file));
} }

Android C2DM works with Web Service java-based, but 401 Error comes out if i try in a WS dotNet-based

i did a simple Web Service in Java and i deployed it in JBOSS 5.1.
This WS handles C2DM service for sending a notify message to an Android phone. I set all like i red in google c2dm api, and, first of all, i sign up for accessing to c2dm service. In this case, all works well.
Now i have to do the same in .NET on IIS7. Some clarification about the .Net code:
setRegId() and pushMessage() method are available by WebService.
handShakeRegId() is simply called by setRegId() after String "reg_id" and "device_id" are setted
all code commented are my try for solving problem, but all was useless
Thats the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace WebService1
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
private String accountType = "HOSTED_OR_GOOGLE";
private String email = "example#gmail.com";
private String password = "password";
private String service = "ac2dm";
private String source = "com.cloudTest.app";
private String HTTPHeaderCT = "application/x-www-form-urlencoded";
private String auth;
private String reg_Id;
private String deviceId;
private String collapseKey = "CollapseKey";
public void handShakeRegId()
{
HttpWebRequest req;
Stream reqst;
try
{
req = (HttpWebRequest)WebRequest.Create(#"https://www.google.com/accounts/ClientLogin");
// string proxy = null;
// req.MaximumAutomaticRedirections = 4;
// req.MaximumResponseHeadersLength = 4;
// req.Credentials = CredentialCache.DefaultCredentials;
string data = String.Format("accountType={0}&Email={1}&Passwd={2}&service={3}&source={4}", accountType, email, password, service, source);
byte[] buffer = Encoding.UTF8.GetBytes(data);
// ASCIIEncoding encoding = new ASCIIEncoding();
// byte[] buffer = encoding.GetBytes(data);
req.Method = "POST";
req.ContentType = HTTPHeaderCT;
req.ContentLength = buffer.Length;
// req.Proxy = new WebProxy(proxy, true);
// req.CookieContainer = new CookieContainer();
reqst = req.GetRequestStream(); // add form data to request stream
reqst.Write(buffer, 0, buffer.Length);
}
catch (Exception e)
{
Debug.WriteLine("--------------------");
Debug.Write("(handShakeRegId) Request Error:" + e);
Debug.WriteLine("--------------------");
throw;
}
HttpWebResponse res;
Stream resst;
try
{
res = (HttpWebResponse)req.GetResponse();
resst = res.GetResponseStream();
StreamReader sr = new StreamReader(resst, Encoding.UTF8);
string response = sr.ReadToEnd();
string SID = response.Substring((response.IndexOf("SID=") + 4),
(response.IndexOf("\n") - 4));//extracting SID
string Auth = response.Substring((response.IndexOf("Auth=") + 5),
(response.Length - (response.IndexOf("Auth=") + 5)) - 1);//extracting Auth
auth = Auth;
}
catch (Exception e)
{
Debug.Write("(handShakeRegId) Response Error:" + e);
throw;
}
resst.Flush();
resst.Close();
reqst.Flush();
reqst.Close();
}
[WebMethod]
public void setRegId(String reg_id, String device_id)
{
reg_Id = reg_id;
deviceId = device_id;
Debug.WriteLine("RegID=" + reg_Id);
Debug.WriteLine("--------------------");
Debug.WriteLine("DeviceID=" + deviceId);
handShakeRegId();
}
[WebMethod]
public void pushMessage(String msg)
{
// Needed! Without an SSL Exception comes out
System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; };
HttpWebRequest req;
Stream reqst;
try
{
req = (HttpWebRequest)WebRequest.Create("http://android.apis.google.com/c2dm/send");
//req.MaximumAutomaticRedirections = 4;
//req.MaximumResponseHeadersLength = 4;
//req.Credentials = CredentialCache.DefaultCredentials;
//req.Credentials = new NetworkCredential("example#gmail.com","password");
//req.KeepAlive = true;
//string proxy = null;
string data = String.Format("registration_id={0}&collapse_key={1}&data.message={2}", reg_Id, collapseKey, msg);
// ASCIIEncoding encoding = new ASCIIEncoding();
// byte[] buffer = encoding.GetBytes(data);
byte[] buffer = Encoding.UTF8.GetBytes(data);
req.Method = "POST";
req.ContentType = HTTPHeaderCT;
req.ContentLength = buffer.Length;
req.Headers.Add("Authorization", "GoogleLogin auth=" + auth);
// req.Proxy = new WebProxy(proxy, true);
// req.CookieContainer = new CookieContainer();
reqst = req.GetRequestStream(); // add form data to request stream
reqst.Write(buffer, 0, buffer.Length);
}
catch (Exception e)
{
Debug.Write("(PushMessageMsgOUT)Error: " + e);
throw;
}
HttpWebResponse res;
Stream resst;
try
{
res = (HttpWebResponse)req.GetResponse();
HttpStatusCode responseCode = ((HttpWebResponse)res).StatusCode;
if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
{
Debug.WriteLine("Unauthorized - need new token");
}
else if (!responseCode.Equals(HttpStatusCode.OK))
{
Debug.WriteLine("Response from web service not OK :");
Debug.WriteLine(((HttpWebResponse)res).StatusDescription);
}
resst = res.GetResponseStream();
StreamReader sr = new StreamReader(resst);
string response = sr.ReadToEnd();
}
catch (Exception e)
{
Debug.WriteLine("(pushMessageMsgIN) Error: "+e);
throw;
}
resst.Flush();
resst.Close();
reqst.Flush();
reqst.Close();
}
}
}
Handshake method works well! I get auth token without problem.
setRegId method is called by Android device (in my case is the Android+GoogleApi 2.2 emulator)
Error which comes out is always the same in pushMessage getResponse() ( and its strange because i implement connection exactly like its in handshake method :-/ ):
A first chance exception of type 'System.Net.WebException' occurred in System.dll
(pushMessageMsgIN) Error: System.Net.WebException: remote server error (401) Unauthorized in System.Net.HttpWebRequest.GetResponse()
2 days for searching something useful but.... NOTHING!!
Its very stressful...
I hope someone can help me.
I red something about Authentication in IIS, so i enabled Anonymous User and other unknown things just for trying. Nothing!
Solved: MY STUPIDITY !!! i made a mistake in private String source !! I specified a wrong package name! -.-

Android radio with song title

I am making the radio app.I have using the android media for playing radio working fine.
Can possible to know song title?
I have play same url in vlc player on desktop it show me the song title.
If there is anyway then please help me.
I also want to implement in 2.1
Thank you.
You'd use the MetaDataRetriever class for this. If you want the song title you'd use the METADATA_KEY_TITLE key. So for instance, you could write some code like this:
MetadataRetriever myRetriever = new MetadataRetriever();
myRetriever.setDataSource(/*specify you data source here*/);
String songName = myRetriever.extractMetadata(MetadataRetriever.METADATA_KEY_TITLE);
If you're developing for less than API level 10, you're going to have to use something else to get the metadata. The MyID3 library will probably do the trick in this case.
I have the solution for 2.2
protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;
public IcyStreamMeta(URL streamUrl) {
setStreamUrl(streamUrl);
isError = false;
}
/**
* Get artist using stream's title
*
* #return String
* #throws IOException
*/
public String getArtist() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String title = streamTitle.substring(0, streamTitle.indexOf("-"));
return title.trim();
}
/**
* Get title using stream's title
*
* #return String
* #throws IOException
*/
public String getTitle() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
return artist.trim();
}
public Map<String, String> getMetadata() throws IOException {
if (metadata == null) {
refreshMeta();
}
return metadata;
}
public void refreshMeta() throws IOException {
retreiveMetadata();
}
private void retreiveMetadata() throws IOException {
URLConnection con = streamUrl.openConnection();
con.setRequestProperty("Icy-MetaData", "1");
con.setRequestProperty("Connection", "close");
con.setRequestProperty("Accept", null);
con.connect();
int metaDataOffset = 0;
Map<String, List<String>> headers = con.getHeaderFields();
InputStream stream = con.getInputStream();
if (headers.containsKey("icy-metaint")) {
// Headers are sent via HTTP
metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
} else {
// Headers are sent within a stream
StringBuilder strHeaders = new StringBuilder();
char c;
while ((c = (char)stream.read()) != -1) {
strHeaders.append(c);
if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
// end of headers
break;
}
}
// Match headers to get metadata offset within a stream
Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
Matcher m = p.matcher(strHeaders.toString());
if (m.find()) {
metaDataOffset = Integer.parseInt(m.group(2));
}
}
// In case no data was sent
if (metaDataOffset == 0) {
isError = true;
return;
}
// Read metadata
int b;
int count = 0;
int metaDataLength = 4080; // 4080 is the max length
boolean inData = false;
StringBuilder metaData = new StringBuilder();
// Stream position should be either at the beginning or right after headers
while ((b = stream.read()) != -1) {
count++;
// Length of the metadata
if (count == metaDataOffset + 1) {
metaDataLength = b * 16;
}
if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
inData = true;
} else {
inData = false;
}
if (inData) {
if (b != 0) {
metaData.append((char)b);
}
}
if (count > (metaDataOffset + metaDataLength)) {
break;
}
}
// Set the data
metadata = IcyStreamMeta.parseMetadata(metaData.toString());
// Close
stream.close();
}
public boolean isError() {
return isError;
}
public URL getStreamUrl() {
return streamUrl;
}
public void setStreamUrl(URL streamUrl) {
this.metadata = null;
this.streamUrl = streamUrl;
this.isError = false;
}
public static Map<String, String> parseMetadata(String metaString) {
Map<String, String> metadata = new HashMap();
String[] metaParts = metaString.split(";");
Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
Matcher m;
for (int i = 0; i < metaParts.length; i++) {
m = p.matcher(metaParts[i]);
if (m.find()) {
metadata.put((String)m.group(1), (String)m.group(2));
}
}
return metadata;
}
Using the thread
public void startThread(){
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
URL url;
Message msg = handler.obtainMessage();
try {
url = new URL(URL);
IcyStreamMeta icy = new IcyStreamMeta(url);
Log.d("SONG",icy.getTitle());
msg.obj = icy.getTitle();
Log.d("ARTITSi",icy.getArtist());
handler.sendMessage(msg);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 10000);
}

Categories

Resources