eclipse创建Android项目利用jsoup用于获取网页信息(手把手教学)
1.下载Jsoup的jar包
Jsoup是一款Java的HTML解析器,主要用来对HTML解析。Jsoup1.7.2 我尝试过使用jsoup1.15.1,简单的Java小程序可以正常调用,在Android项目安装到真机上时会出现错误。如下:
Could not find method org.jsoup.Jsoup.parse, referenced from method com.example.gethtml.MainActivity.getneirong VFY: unable to resolve static method 10916: Lorg/jsoup/Jsoup;.parse (Ljava/lang/String;)Lorg/jsoup/nodes/Document;
2.导入Jsoup的jar包
一般来说,正常导入jar包即可。过程参考链接Eclipse时导入第三方jar包的简单方法。 以防万一,导入成功后,右击项目名,点击Properties–>java Build Path–>Order and Export,将所导入的Jsoup包置顶并选中。
3.MainActivity.java
public class MainActivity extends Activity {
private TextView info = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) super.findViewById(R.id.text_view_id);
MyThread thread = new MyThread(handler);
thread.start();
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
info.setText(msg.getData().getString("key"));
}
};
public class MyThread extends Thread {
private Handler handler = null;
protected MyThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
super.run();
try {
Document doc = Jsoup.connect("http://www.baidu.com/").get();
Element elements = doc.getElementById("ftCon");
System.out.println(elements.text());
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("key", elements.text());
msg.setData(bundle);
handler.sendMessage(msg);
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/text_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
AndroidManifest.xml(以防万一,大部分权限都打开)
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
然后接上真机,就可以运行了
|