Android obtains software and hardware information and uploads it to the server (Socket Implementation). Android software and hardware

Source: Internet
Author: User

Android obtains software and hardware information and uploads it to the server (Socket Implementation). Android software and hardware

First, the project structure is shown in figure -- A: client-side CheckInfo and server-side CheckInfo_Server. CheckInfo obtains the mobile phone information (Mac, Cpu, memory, installed software information, etc.) and uploads the information to the server. Then, check whether a software has been installed from the installed software information, if not, go to the software download page. CheckInfo_Server outputs the uploaded information.

Figure --

AndroidManifest. xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.xinab.checkinfo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="19" />    <uses-permission android:name="android.permission.INTERNET"/>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.xinab.checkinfo.CheckActivity"            android:label="@string/app_name" >            <intent-filter>                                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />                                      </intent-filter>        </activity>        <activity             android:name="com.xinab.checkinfo.MainActivity">                    </activity>        <activity             android:name="com.xinab.checkinfo.DsoftActivity">                    </activity>    </application></manifest>
To obtain the mac address and communicate with the network, add ACCESS_WIFI_STATE and INTERNET permissions;

The program entry is CheckActivity. java:

Package com. xinab. checkinfo; import java. io. bufferedReader; import java. io. dataOutputStream; import java. io. fileReader; import java. io. IOException; import java. io. inputStream; import java.net. socket; import java. util. list; import android. app. activity; import android. app. activityManager; import android. app. activityManager. memoryInfo; import android. content. context; import android. content. intent; import android. c Ontent. pm. applicationInfo; import android. content. pm. packageInfo; import android.net. wifi. wifiInfo; import android.net. wifi. wifiManager; import android. OS. bundle; import android. text. format. formatter; import android. util. log; import android. widget. toast; public class CheckActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); WifiManager Wifi = (WifiManager) getSystemService (Context. WIFI_SERVICE); WifiInfo = wifi. getConnectionInfo (); String mac = "", softinfo = "", pmac = "", pinfo = "", amem = "", tmem = "", ssid = "", cpu = "", str = ""; int a, B, c, d, e; mac = getMacAddress (pmac); amem = getAvailMemory (amem ); // available memory tmem = getTotalMemory (tmem); // total memory softinfo = getAllApp (pinfo); // install software information ssid = info. getSSID (); // wifi name cpu = getCpu (cpu); // cpustr = mac + ";" + "\ n" + "available memory:" + amem + "," + "Total memory:" + tmem + ";" + "\ n" + softinfo + ";" + "\ n" + "SSID:" + ssid + "; "+" \ n "+ cpu; UpToServer (str);/* If the software is installed, the indexOf (String str) method returns-1 (0 in Java, you can write an example for testing); */a = softinfo. indexOf ("IdsecSeat"); B = softinfo. indexOf ("Kingsoft mobile guard"); c = softinfo. indexOf ("QQ manager"); d = softinfo. indexOf ("Kingsoft mobile phone drug overlord"); e = softinfo. indexOf ("Haha"); if (! =-1 | B! =-1 | c! =-1 | d! =-1 | e! =-1) {Intent intent = new Intent (); intent. setClass (CheckActivity. this, MainActivity. class); startActivity (intent); finish ();} else {Toast. makeText (this, "anti-virus software is not installed on the mobile phone, please download", Toast. LENGTH_LONG ). show (); Intent intent = new Intent (); intent. setClass (CheckActivity. this, DsoftActivity. class); startActivity (intent); finish () ;}} private void UpToServer (String str) {try {Socket socket = new Socket ("192.168.2.63", 8888 ); // IP address of the computer Address; DataOutputStream dout = new DataOutputStream (socket. getOutputStream (); // get the output stream // String s = "This is a test case! "; Dout. writeUTF (str); // send the message dout to the server. close (); socket. close ();} catch (Exception e) {e. printStackTrace ();}}/***. obtain the MAC address of a mobile phone * the mac address can be obtained only when wifi is enabled on the mobile phone */private String getMacAddress (String mac) {String result = ""; WifiManager wifiManager = (WifiManager) getSystemService (Context. WIFI_SERVICE); WifiInfo wifiInfo = wifiManager. getConnectionInfo (); result = wifiInfo. getMacAddress (); Log. I ("text", "Mobile macAdd :" + Result); // return result; mac = "MAC:" + wifiInfo. getMacAddress (); return mac;}/*** get Installation Software Information **/private String getAllApp (String app) {String result = ""; list <PackageInfo> packages = getPackageManager (). getInstalledPackages (0); for (PackageInfo I: packages) {if (I. applicationInfo. flags & ApplicationInfo. FLAG_SYSTEM) = 0) {result + = I. applicationInfo. loadLabel (getPackageManager ()). toString () + "," ;}} App = "mobile phone installation software information:" + result. substring (0, result. length ()-1); return app;}/*** get the current available memory size of android **/private String getAvailMemory (String amem) {// get the current available memory size of android ActivityManager am = (ActivityManager) getSystemService (Context. ACTIVITY_SERVICE); MemoryInfo mi = new MemoryInfo (); am. getMemoryInfo (mi); // mi. availMem; available memory of the current system return amem = Formatter. formatFileSize (getBaseContext (), mi. AvailMem); // normalize the obtained memory size}/***** obtain the total system memory */private String getTotalMemory (String tmem) {String str1 = "/proc/meminfo"; // system memory information file String str2; String [] arrayOfString; long initial_memory = 0; try {FileReader localFileReader = new FileReader (str1); BufferedReader localBufferedReader = new BufferedReader (localFileReader, 8192); str2 = localBufferedReader. readLine (); // read the first line of meminfo, total memory size of the system arra YOfString = str2.split ("\ s +"); for (String num: arrayOfString) {Log. I (str2, num + "\ t");} initial_memory = Integer. valueOf (arrayOfString [1]). intValue () * 1024; // obtain the total system memory, in KB. Multiply by 1024 and convert it to Byte localBufferedReader. close ();} catch (IOException e) {} return tmem = Formatter. formatFileSize (getBaseContext (), initial_memory); // convert Byte to KB or MB, and normalize the memory size}/*** obtain Cpu **/private String getCpu (String cpu) {ProcessBuilder cmd; String result = ""; try {String [] args = {"/system/bin/cat", "/proc/cpuinfo "}; cmd = new ProcessBuilder (args); Process process = cmd. start (); InputStream in = process. getInputStream (); byte [] re = new byte [1024]; while (in. read (re )! =-1) {System. out. println (new String (re); result = result + new String (re); cpu = "cpu information:" + result. toString (); return cpu;} in. close ();} catch (IOException ex) {ex. printStackTrace ();} cpu = "cpu:" + result. toString (); return cpu;} // @ Override // public boolean onCreateOptionsMenu (Menu menu) {/// Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater (). inflate (R. menu. main, menu); // return true ;//}}

If any detected software (such as Kingsoft drug overlord) is installed in the mobile phone software, go to MainActivity. java,


MainActivity. java:

Package com. xinab. checkinfo; import android. app. activity; import android. OS. bundle; import android. view. menu; import android. widget. textView; public class MainActivity extends Activity {TextView tx; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); tx = (TextView) findViewById (R. id. textView1); tx. setText ("Mobile Phone environment is normal") ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}

If software such as Kingsoft drug overlord is not installed, you can find a webpage for download (the webpage here is only used for testing), and the Activity also jumps to DsoftActivity. java:


DsoftActivity. java:

Package com. xinab. checkinfo; import android. OS. bundle; import android. app. activity; import android. view. menu; import android. webkit. webSettings; import android. webkit. webView; import android. widget. toast; public class DsoftActivity extends Activity {WebView wv; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. dsoft); wv = (WebView) findVie WById (R. id. wv); // set the page for loading the adaptive mobile phone screen WebSettings = wv. getSettings (); settings. setUseWideViewPort (true); settings. setLoadWithOverviewMode (true); try {wv. loadUrl ("http: // 192.168.2.15: 3000"); // wv. loadUrl ("http://m.baidu.com/s? St = 10a001 & tn = webmkt & word = % CA % D6 % BB % FA % C9 % B1 % B6 % BE % C8 % ED % BC % FE & f = web_alad_5 ") ;} catch (Exception e) {Toast. makeText (DsoftActivity. this, "error:" + e. getMessage (), Toast. LENGTH_LONG ). show () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}

Layout file:

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" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = ". mainActivity "> <TextView android: id =" @ + id/textView1 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignParentLeft =" true "android: layout_alignParentTop = "true" android: layout_marginLeft = "113dp" android: layout_marginTop = "127dp" android: text = "normal mobile phone environment"/> </RelativeLayout>

Dsoft.html:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <WebView        android:id="@+id/wv"        android:layout_width="match_parent"        android:layout_height="match_parent" /></LinearLayout>

CheckInfo_Server receives software information and outputs it on the console:



Server. java:

Package com. xinab. checkinfo_server; import java. io. dataInputStream; import java. io. dataOutputStream; import java.net. serverSocket; import java.net. socket; public class Server {public static void main (String aa []) {try {ServerSocket as = new ServerSocket (8888); System. out. print ("Listenning .... "+" \ n "); // print the prompt information on the console; while (true) {Socket socket =. accept (); // obtain the connected socket object System. out. print ("Client Connected ...... "+" \ n "); // print the prompt information on the console; DataInputStream din = new DataInputStream (socket. getInputStream (); // obtain the input stream String msg = din. readUTF (); // read the message System from the client. out. print (msg); // console output information} catch (Exception e) {e. printStackTrace ();}}}
I just got started with Android and recorded my own examples to accumulate experience.


References:

Explanation of Android core technologies and instances ---- Ouyang Zhihui

Http://blog.csdn.net/hytfly/article/details/8552483





How does Android develop transmit bitmap and string from the client to the server using socket?

Socket can transmit arbitrary data. The key core is to define the "conversation protocol" of data packets "!
Files or data must be transmitted in multiple parts, so they cannot be sent all at once. Therefore, the key technology is simple.
Dialog protocol.

Android/java uses Socket to push messages similar to QQ messages. How can I keep the connection when the program runs in the background? How does the server determine whether the connection is disconnected?

QQ messages are UDP packets. After you connect, even if you do not close the connection, the server cannot determine whether the connection is closed,
Only the client regularly sends a UDP packet, indicating that the packet is connected.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.