開發本身的監控系統1、email篇
開發本身的監控系統2、web篇 php
移動篇(android)
關鍵字:java、android、json、php html
互聯網已經進入大數據時代,若是沒有給本身的產品開發手機端的應用程序,出門都很差意思跟別人打招呼了~~
爲了隨時隨地掌握服務器的運行狀態,固然,也爲了裝ability,下面就來爲咱們的監控系統開發一個手機端(android)的應用。 java
原理:
首先編寫一個web接口,讀取數據庫服務器數據,返回json對象數組。android應用程序解析json數據,經過listvie控件顯示。
如下是web接口,php編寫,pdo方式鏈接數據庫,使用json_encode將字符串轉換爲json對象格式,代碼以下: mysql
<?php $dbms='mysql'; //數據庫類型 oracle 用ODI,對於開發者來講,使用不一樣的數據庫,只要改這個,不用記住那麼多的函數了 $host='localhost'; //數據庫主機名 $dbName='monitor'; //使用的數據庫 $user='user1'; //數據庫鏈接用戶名 $pass='Root123'; //對應的密碼 $dsn="$dbms:host=$host;dbname=$dbName"; try { $dbh=new PDO($dsn,$user,$pass);//初始化一個PDO對象,就是建立了數據庫鏈接對象$dbh $jsonString=json_encode($dbh->query('select * from servers')->fetchAll(PDO::FETCH_ASSOC)); print_r($jsonString); } catch (PDOException $e) { die("Error!:".$e->getMessage()); } ?>
注:接口能夠使用任何語言編寫,只要能返回json對象數組就行。 android
使用瀏覽器訪問該接口,返回json對象數組:
web
接下來就是應用的開發了。
大致思路:使用HttpClient接口向web接口提交get請求,取回json數據,而後解析json數據並顯示在listview構造的表格中。
eclipse項目結構以下:
sql
AndroidManifest.xml: 數據庫
<?xml version= "1.0" encoding ="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cszhi.mymonitor" android:versionCode= "1" android:versionName= "1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /><!-- 網路鏈接權限--> <uses-permission android:name= "android.permission.ACCESS_NETWORK_STATE" /><!-- 容許訪問網絡狀態--> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:screenOrientation="landscape" android:name="com.cszhi.mymonitor.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application > </manifest>server_list.xml:
<?xml version= "1.0" encoding ="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width= "wrap_content" android:layout_height= "20dp" android:orientation= "horizontal" > <TableLayout android:id="@+id/table" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TableRow > <View android:layout_width="1dip" android:background= "#FF909090" /> <TextView android:id="@+id/id" android:layout_width="20dp" android:gravity="center" android:layout_height="wrap_content" /> <View android:layout_width="1dip" android:background= "#FF909090" /> <TextView android:id="@+id/hostname" android:layout_width="70dp" android:gravity="center" android:layout_height="wrap_content" /> <View android:layout_width="1dip" android:background= "#FF909090" /> <TextView android:id="@+id/ip" android:layout_width="100dp" android:gravity="center" android:layout_height="wrap_content" /> <View android:layout_width="1dip" android:background= "#FF909090" /> <TextView android:id="@+id/rootpartion" android:layout_width="100dp" android:gravity="center" android:layout_height="wrap_content" /> <View android:layout_width="1dip" android:background= "#FF909090" /> <TextView android:id="@+id/uptime" android:layout_width="100dp" android:gravity="center" android:layout_height="wrap_content" /> <View android:layout_width="1dip" android:background= "#FF909090" /> <TextView android:id="@+id/time" android:layout_width="85dp" android:gravity="center" android:layout_height="wrap_content" /> <View android:layout_width="1dip" android:background= "#FF909090" /> </TableRow> </TableLayout> </LinearLayout>activity_main.xml:
<LinearLayout 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" android:orientation= "vertical" android:paddingBottom= "@dimen/activity_vertical_margin" android:paddingLeft= "@dimen/activity_horizontal_margin" android:paddingRight= "@dimen/activity_horizontal_margin" android:paddingTop= "@dimen/activity_vertical_margin" tools:context= ".MainActivity" > <Button android:id="@+id/bn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:text="刷新" /> <ListView android:id="@+id/lvTitle" android:background="#bfe1f2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ListView android:id="@+id/lv" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>MyHttp.java:
package com.cszhi.mymonitor; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class MyHttp { public String httpGet(String url){ String response= null; HttpClient httpClient= new DefaultHttpClient(); HttpGet httpGet= new HttpGet(url); HttpResponse httpResponse; try{ httpResponse=httpClient.execute(httpGet); int statusCode=httpResponse.getStatusLine().getStatusCode(); if(statusCode==HttpStatus.SC_OK){ response=EntityUtils. toString(httpResponse.getEntity()); } } catch(ClientProtocolException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } return response; } }MainActivity.java
package com.cszhi.mymonitor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; public class MainActivity extends Activity { //jsonstring 字符串,用於存放經過url獲取的json數據 String jsonstring=null ; //接口地址 String url= "http://60.191.231.17/get.php" ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //用於等待圖標 requestWindowFeature(Window. FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout. activity_main); Button bn=(Button) findViewById(R.id. bn); //處理線程傳遞來的消息 final Handler myhandler =new Handler(){ public void handleMessage(Message msg){ ListView lv=(ListView) findViewById(R.id. lv); String[] from={"id","hostname" ,"ip" ,"rootpartion" ,"uptime" ,"time" }; int[] to={R.id.id,R.id.hostname ,R.id.ip,R.id.rootpartion,R.id. uptime,R.id.time }; List<Map<String,?>> listb= new ArrayList<Map<String,?>>(); Map<String,String> b= new HashMap<String, String>(); b.put( "id", "id" ); b.put( "hostname", "hostname" ); b.put( "ip", "ip" ); b.put( "rootpartion","rootpartion" ); b.put( "uptime","uptime" ); b.put( "time", "time" ); listb.add(b); ListView lvtitle=(ListView) findViewById(R.id.lvTitle ); SimpleAdapter adapterb= new SimpleAdapter(MainActivity.this ,listb,R.layout.server_list,from,to); lvtitle.setAdapter(adapterb); List<Map<String,?>> list= new ArrayList<Map<String,?>>(); try{ JSONArray jsonArray= new JSONArray(jsonstring ); //解析json對象,並放入hashmap中 for(int i=0;i<jsonArray.length();i++){ JSONObject item=jsonArray.getJSONObject(i); Map<String,String> m=new HashMap<String, String>(); m.put( "id", item.getString("id" )); m.put( "hostname", item.getString("hostname" )); m.put( "ip", item.getString("ip" )); m.put( "rootpartion",item.getString("rootpartion" )); m.put( "uptime", item.getString("uptime" )); m.put( "time", item.getString("time" )); list.add(m); } } catch(Exception e){ e.printStackTrace(); } //這裏的this是Handler,由於這個方法是在放在Handler裏的,因此這裏不該該使用this,而應該使用MainActivity.this(MainActivity是類名) SimpleAdapter adapter= new SimpleAdapter(MainActivity.this ,list,R.layout.server_list,from,to); lv.setAdapter(adapter); //關閉等待圖標(右上角的轉圈) setProgressBarIndeterminateVisibility( false); } }; //Runnable接口 final Runnable st=new Runnable() { @Override public void run() { data( url); myhandler.sendEmptyMessage(0); } }; //檢查是否有網絡鏈接 if(!checkNet( this)){ Toast. makeText(this, "網絡鏈接失敗,請檢查網絡" ,Toast.LENGTH_LONG).show(); } else{ new Thread(st).start(); setProgressBarIndeterminateVisibility( true); } //單擊按鈕 bn.setOnClickListener( new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub //若是有網路鏈接,建立新線程,傳入 st接口,並啓動該線程 if(!checkNet(MainActivity. this)){ Toast. makeText(MainActivity.this, "網絡鏈接失敗,請檢查網絡" ,Toast.LENGTH_LONG).show(); return; } else{ new Thread(st).start(); //顯示等待圖標(右上角的轉圈) setProgressBarIndeterminateVisibility( true); } } }); } //獲取url數據,並賦值給jsonstring private void data(String url){ MyHttp myHttp= new MyHttp(); jsonstring= myHttp.httpGet(url); } //檢查是否有網絡的函數 public static boolean checkNet(Context context) { try { NetworkInfo networkInfo = (( ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE )).getActiveNetworkInfo(); if (networkInfo != null) { Log. d("httpjson", "true"); return true ; } else { Log. d("httpjson", "false"); return false ; } } catch (Exception e) { e.printStackTrace(); return false ; } } }
編譯,傳到手機上安裝運行:
apache
能夠根據本身需求添加其它功能,如定時刷新,聲音報警等。
以下截圖是我爲部門運維服務器開發的手機端監控程序,支持按管理員監控服務器,支持按不一樣監控項目排序:
json
參考:
尚學堂科技.馬士兵.JAVA視頻教程
瘋狂android講義
http://developer.android.com/training/index.html