新线程上的Android Run类

时间:2013-08-20 02:30:59

标签: android

我正在尝试解析.pls文件以获取网址。我使用了以下代码,但它提供了networkonmainthread异常。我之前从未做过线程应用程序;如何在新线程上运行此类?

public class GetStreamingUrl {
private static String LOGTAG = "GetStreamingUrl";
private Context mContext;
public String url1;
public LinkedList<String> url2; 

public GetStreamingUrl(Context context) {
Log.i(LOGTAG, "call to constructor");
this.mContext = context;

}

public LinkedList<String>  getStreamingUrl(String url) {

Log.i(LOGTAG, "get streaming url");
final BufferedReader br;
String murl = null;
LinkedList<String> murls = null;
try {
    URLConnection mUrl = new URL(url).openConnection();
    br = new BufferedReader(
            new InputStreamReader(mUrl.getInputStream()));
    murls = new LinkedList<String>();
    while (true) {
        try {
            String line = br.readLine();

            if (line == null) {
                break;
            }
            murl = parseLine(line);
            if (murl != null && !murl.equals("")) {
                murls.add(murl);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Log.i(LOGTAG, "url to stream :" + murl);
return murls;
}

private String parseLine(String line) {
if (line == null) {
    return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
    return trimmed.substring(trimmed.indexOf("http"));
}
return "";
    }



}

我正在尝试解析.pls文件以获取网址。我使用了以下代码,但它提供了networkonmainthread异常。我之前从未做过线程应用程序;如何在新线程上运行此类?

2 个答案:

答案 0 :(得分:3)

这样做:

new Thread(new Runnable() {

            @Override
            public void run() {
                // DO YOUR STUFFS HERE

            }
        }).start();

希望这有帮助。

答案 1 :(得分:0)

您可以使用AsyncTask并在其中完成工作。请点击以下链接了解更多详情:

  

http://developer.android.com/reference/android/os/AsyncTask.html