Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

安卓Android使用入門(十二):製作校園招聘信息爬蟲

編輯:關於 Android 程式設計

本篇示範如何打造一個抓取校園招聘信息的手機App,重點在於使用Jsoup解析網頁、透過Handler與子線程協作更新UI,並搭配Navigation Drawer側邊選單、PopupWindow分頁選單與網路狀態檢查等常見技巧。以下提供完整程式碼。

MainActivity.java

 package siso.mycrawler; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.BitmapDrawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.ArrayMap; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.jsoup.Jsoup; import org.jsoup.Connection; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks { private NavigationDrawerFragment mNavigationDrawerFragment; private CharSequence mTitle; private ListView infoListView; private List> list = new ArrayList<>(); private String url_first_half = "https://xjh.haitou.cc/wh/uni-"; private String url_second_half = "/after/hold/page-"; private String next_page_url = ""; private int currentPage = 1; private int currentPosition; private String url; private ProgressDialog dialog; // popupWindow private PopupWindow popupWindow; private ListView menuListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); // 顯示宣講會資訊的ListView infoListView = (ListView) findViewById(R.id.info_list_view); // 初始化popupWindow initPopupWindow(); } // 將資料填入ListView中 private void show() { if(list.isEmpty()) { TextView message = (TextView)findViewById(R.id.message); message.setText(R.string.message); } else { SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.my_list_item, new String[]{"company", "time", "address"}, new int[]{R.id.company, R.id.time, R.id.address}); infoListView.setAdapter(adapter); } dialog.dismiss(); // 關閉視窗 } Runnable runnable = new Runnable() { @Override public void run() { Connection conn = Jsoup.connect(url); // 修改http包中的header,偽裝成瀏覽器進行抓取 conn.header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:32.0) Gecko/ 20100101 Firefox/32.0"); Document doc = null; try { doc = conn.get(); } catch (IOException e) { e.printStackTrace(); } // 取得下一頁的鏈接 Elements link = doc.select("li.paginate_button").select("li.next"); next_page_url = link.select("a").attr("href"); // 取得tbody元素下的所有tr元素 Elements elements = doc.select("tbody tr"); for(Element element : elements) { String companyName = element.getElementsByClass("text-success").text(); String time = element.getElementsByClass("cxxt-holdtime").text(); String address = element.getElementsByClass("text-ellipsis").text(); Map map = new HashMap<>(); map.put("company", companyName); map.put("time", time); map.put("address", address); list.add(map); } // 執行完畢後給handler發送一個空消息 handler.sendEmptyMessage(0); } }; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); // 收到消息後執行handler show(); } }; // 判斷是否有可用的網路連接 public boolean isNetworkAvailable(Activity activity) { Context context = activity.getApplicationContext(); ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; else { // 取得所有NetworkInfo物件 NetworkInfo[] networkInfo = cm.getAllNetworkInfo(); if (networkInfo != null && networkInfo.length > 0) { for (int i = 0; i < networkInfo.length; i++) if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) return true; // 存在可用的網路連接 } } return false; } // 重新抓取 public void switchOver(final int position) { if(isNetworkAvailable(MainActivity.this)) { // 顯示"正在加載"視窗 dialog = new ProgressDialog(this); dialog.setMessage("正在抓取數據..."); dialog.setCancelable(false); dialog.show(); // 初始時,抓取並顯示;切換學校時,重新抓取並顯示 url = url_first_half + (position+1) + url_second_half + currentPage + "/"; list.clear(); new Thread(runnable).start(); // 子線程 } else { // 彈出提示框 new AlertDialog.Builder(this) .setTitle("提示") .setMessage("當前沒有網路連接!") .setPositiveButton("重試",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switchOver(position); } }).setNegativeButton("退出",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); // 退出程序 } }).show(); } } @Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, PlaceholderFragment.newInstance(position + 1)) .commit(); currentPosition = position; // 保存當前位置(學校) // 切換學校 currentPage = 1; // 重置1 switchOver(position); } public void onSectionAttached(int number) { switch (number) { case 1: mTitle = getString(R.string.title_section1); break; case 2: mTitle = getString(R.string.title_section2); break; case 3: mTitle = getString(R.string.title_section3); break; } } public void restoreActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { getMenuInflater().inflate(R.menu.main, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } // 刷新 public void refresh() { if(isNetworkAvailable(MainActivity.this)) { // 顯示"正在刷新"視窗 dialog = new ProgressDialog(this); dialog.setMessage("正在刷新..."); dialog.setCancelable(false); dialog.show(); // 重新抓取 list.clear(); new Thread(runnable).start(); // 子線程 } else { // 彈出提示框 new AlertDialog.Builder(this) .setTitle("刷新") .setMessage("當前沒有網路連接!") .setPositiveButton("重試",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { refresh(); } }).setNegativeButton("退出",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); // 退出程序 } }).show(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.refresh: refresh(); return true; case R.id.more: if(popupWindow.isShowing()) popupWindow.dismiss(); else popUp(); return true; } return super.onOptionsItemSelected(item); } //實例化PopupWindow創建菜單 private void initPopupWindow(){ View view = getLayoutInflater().inflate(R.layout.popup_window, null); menuListView = (ListView)view.findViewById(R.id.popup_list_view); popupWindow = new PopupWindow(view, 160,WindowManager.LayoutParams.WRAP_CONTENT); // 數據 List> data = new ArrayList<>(); Map map = new HashMap<>(); map.put("menu_text", "上一頁"); data.add(map); map = new HashMap<>(); map.put("menu_text", "下一頁"); data.add(map); // 創建適配器 SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.menu_list_item, new String[]{"menu_text"}, new int[]{R.id.menu_text}); menuListView.setAdapter(adapter); // 添加Item點擊響應 menuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { switch (position) { case 0: prePage(); // 上一頁 break; case 1: nextPage(); // 下一頁 } } }); // 在popupWindow以外的區域點擊後關閉popupWindow popupWindow.setFocusable(true); popupWindow.setTouchable(true); popupWindow.setBackgroundDrawable(new BitmapDrawable()); } //顯示PopupWindow菜單 private void popUp(){ //設置位置 popupWindow.showAsDropDown(this.findViewById(R.id.more), 0, 2); } // 上一頁 public void prePage() { if(isNetworkAvailable(MainActivity.this)) { if(currentPage == 1) Toast.makeText(MainActivity.this, "已經是第一頁了", Toast.LENGTH_SHORT).show(); else { --currentPage; switchOver(currentPosition); } } else { // 彈出提示框 new AlertDialog.Builder(this) .setTitle("上一頁") .setMessage("當前沒有網路連接!") .setPositiveButton("重試",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { prePage(); } }).setNegativeButton("退出",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); // 退出程序 } }).show(); } } // 下一頁 public void nextPage() { if(isNetworkAvailable(MainActivity.this)) { if(next_page_url.equals("#")) Toast.makeText(MainActivity.this, "已經是最後一頁了", Toast.LENGTH_SHORT).show(); else { ++currentPage; switchOver(currentPosition); } } else { // 彈出提示框 new AlertDialog.Builder(this) .setTitle("下一頁") .setMessage("當前沒有網路連接!") .setPositiveButton("重試",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { nextPage(); } }).setNegativeButton("退出",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); // 退出程序 } }).show(); } } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } } }

NavigationDrawerFragment.java

 package siso.mycrawler; import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class NavigationDrawerFragment extends Fragment { private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; private NavigationDrawerCallbacks mCallbacks; private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private int mCurrentSelectedPosition = 0; private boolean mFromSavedInstanceState; private boolean mUserLearnedDrawer; public NavigationDrawerFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstanceState = true; } selectItem(mCurrentSelectedPosition); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate( R.layout.fragment_navigation_drawer, container, false); mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { selectItem(position); } }); mDrawerListView.setAdapter(new ArrayAdapter( getActionBar().getThemedContext(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, new String[]{ getString(R.string.title_section1), getString(R.string.title_section2), getString(R.string.title_section3), })); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); return mDrawerListView; } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); mDrawerToggle = new ActionBarDrawerToggle( getActivity(), mDrawerLayout, R.drawable.ic_drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } getActivity().supportInvalidateOptionsMenu(); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) { return; } if (!mUserLearnedDrawer) { mUserLearnedDrawer = true; SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); } getActivity().supportInvalidateOptionsMenu(); } }; if (!mUserLearnedDrawer && !mFromSavedInstanceState) { mDrawerLayout.openDrawer(mFragmentContainerView); } mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void selectItem(int position) { mCurrentSelectedPosition = position; if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (mDrawerLayout != null && isDrawerOpen()) { inflater.inflate(R.menu.global, menu); showGlobalContextActionBar(); } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.app_name); } private ActionBar getActionBar() { return ((ActionBarActivity) getActivity()).getSupportActionBar(); } public static interface NavigationDrawerCallbacks { void onNavigationDrawerItemSelected(int position); } } 

AndroidManifest.xml

       

activity_main.xml

 <framelayout android:id="@+id/container" android:layout_height="match_parent" android:layout_width="match_parent">  </framelayout>  

其餘版面配置檔

本範例另包含fragment_main.xml、fragment_navigation_drawer.xml、menu_list_item.xml、my_list_item.xml、popup_window.xml,以及menu資料夾下的global.xml與main.xml,並在colors.xml中定義了大量Material Design色票(如orange_500、teal_500、grey_900等)。這些版面與資源檔共同支撐了側邊選單、列表呈現與分頁選單的畫面。

運行效果

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved