安卓获取软硬件信息并上传给server(Socket实现)

Posted gccbuaa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓获取软硬件信息并上传给server(Socket实现)相关的知识,希望对你有一定的参考价值。

首先,项目结构如图--A:分为client部分CheckInfo和server端CheckInfo_Server。CheckInfo获取手机信息(Mac,Cpu,内存,已安装软件信息等)并上传到server端,然后从已安装软件信息中查找有没有安装某一款软件,没有则定位到该软件下载页面。CheckInfo_Server将上传的信息输出。

技术分享

图--A

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>

由于要获取mac地址,和网络通信,增加ACCESS_WIFI_STATE和INTERNET权限;

程序入口是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.content.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 {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
		WifiInfo info = wifi.getConnectionInfo(); 
		String mac="",softinfo="",pmac="",pinfo="",amem="",tmem="",ssid="",cpu="",str="";
		int a,b,c,d,e;
		mac=getMacAddress(pmac);
		amem=getAvailMemory(amem);//可用内存
		tmem=getTotalMemory(tmem);//总内存
		softinfo=getAllApp(pinfo);//安装软件信息
		ssid=info.getSSID();//wifi名
		cpu=getCpu(cpu);//cpu
		str=mac+";"+"\n"+"可用内存:"+amem+","+"总内存:"+tmem+";"+"\n"+softinfo+";"+"\n"+"SSID:"+ssid+";"+"\n"+cpu;
		UpToServer(str);
		/*
		 若软件安装了,则indexOf(String str)方法返回-1(在Java中是0,能够写个样例測试); 
		 */
		a=softinfo.indexOf("IdsecSeat");
		b=softinfo.indexOf("金山手机卫士");
		c=softinfo.indexOf("QQ管家");
		d=softinfo.indexOf("金山手机毒霸");
		e=softinfo.indexOf("哈哈");
			if(a!=-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, "手机未安装杀毒软件,请下载" , 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地址;
				DataOutputStream dout=new DataOutputStream(socket.getOutputStream());//获得输出流
//				String s="This is a test case!";
				dout.writeUTF(str);//向server发送信息
				dout.close();
				socket.close();
			}
		
		catch(Exception e){
			e.printStackTrace();
		}
		
	}			
	
	 /** 
	  * .获取手机MAC地址 
	  * 仅仅有手机开启wifi才干获取到mac地址 
	  */  
	private String getMacAddress(String mac){  
	        String result = "";  
	        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
	        WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
	        result = wifiInfo.getMacAddress();  
	        Log.i("text", "手机macAdd:" + result);  
	        //return result;  
	         mac="MAC:"+wifiInfo.getMacAddress();
	         return mac;
	    }  
	  /**
	   * 获取安装软件信息
	   *
	   */
	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="手机安装软件信息:"+result.substring(0, result.length() - 1);  
	          return app;
	 }  
	 
	 /** 
	  *  获取android当前可用内存大小  
	  *
	  */  
	private String getAvailMemory(String amem) {// 获取android当前可用内存大小     
		        
		        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);    
		        MemoryInfo mi = new MemoryInfo();    
		        am.getMemoryInfo(mi);    
		        //mi.availMem; 当前系统的可用内存     
		    
		        return amem=Formatter.formatFileSize(getBaseContext(), mi.availMem);// 将获取的内存大小规格化     
		    }    
		 
	/** 
	 * 
	 * 获得系统总内存 
	 */  
	private String getTotalMemory(String tmem) {  
		     String str1 = "/proc/meminfo";// 系统内存信息文件   
		     String str2;  
		     String[] arrayOfString;  
		     long initial_memory = 0; 
		     try {  
		     FileReader localFileReader = new FileReader(str1);  
		     BufferedReader localBufferedReader = new BufferedReader(  
		     localFileReader, 8192);  
		     str2 = localBufferedReader.readLine();// 读取meminfo第一行。系统总内存大小   
		   
		     arrayOfString = str2.split("\\s+");  
		     for (String num : arrayOfString) {  
		     Log.i(str2, num + "\t");  
		     } 		   
		     initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存。单位是KB。乘以1024转换为Byte   
		     localBufferedReader.close();  
		     } 
		     catch (IOException e) {  
		     }  
		     return  tmem= Formatter.formatFileSize(getBaseContext(), initial_memory);// Byte转换为KB或者MB,内存大小规格化   
		     }  
		 
	/**
	 * 获取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信息:"+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;
//	}

}

若安装的手机软件中有检測的软件(如金山毒霸)。则转到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;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		tx=(TextView)findViewById(R.id.textView1);
		tx.setText("手机环境正常");
	}

	@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;
	}

}

若没安装金山毒霸等软件。则定位到某一网页进行下载(这里的网页仅仅是測试所用),Activity也跳转到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;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dsoft);
		wv =(WebView)findViewById(R.id.wv);
		//设置载入的页面自适应手机屏幕
		WebSettings settings = 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, "错误:"+e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	@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;
	}

}

布局文件:

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/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    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="手机环境正常" />

</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接收软件信息并在控制台输出:

技术分享


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");//在控制台打印提示信息;
			while(true){
				Socket socket=as.accept();//获取连接的socket对象
				System.out.print("Client Connected......"+"\n");//在控制台打印提示信息;
			DataInputStream din=new DataInputStream(socket.getInputStream());//获得输入流
			String msg=din.readUTF();//读取client发来的消息
			System.out.print(msg);//控制台输出信息
		}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
	}
}
刚接触安卓不久,把自己写的样例记录下来,以便积累经验。


參考资料:

《Android核心技术与实例具体解释》----欧阳零  

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




















以上是关于安卓获取软硬件信息并上传给server(Socket实现)的主要内容,如果未能解决你的问题,请参考以下文章

shell脚本整合json数值输出从而获取硬件信息

安卓虚拟机,如何重置硬件设备信息

CMDB硬件信息管理系统开发

如何查看安卓手机硬件ID

识别浏览器信息,判断是否安卓或者苹果手机

安卓手机怎么查看详细信息?