可以读取手机的cpu 内存 键盘类型 导航方式 以及安装的软件列表等
附带流量查询方法
这个方法对手机的负荷较大 可以考虑放在后台执行
public class PhoneInfoUtil {
Context context;
PhoneInfo pInfo;
WindowManager wm;
Activity activity;
final public String DEV_FILE = "/proc/self/net/dev";// 系统流量文件
final String GPRSLINE = "rmnet0";
String[] gprsdata = { "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0" };
public PhoneInfoUtil(Activity activity,PhoneInfo pinfo){
this.context=activity.getApplicationContext();
this.wm=activity.getWindowManager();
this.activity=activity;
fetch_info(pinfo);//linux方式获得
fetch_tel_status(pinfo);//android API方式获得
}
/**
* linux版本 cpu信息 mem信息
* @param pInfo
*/
public void fetch_info(PhoneInfo pInfo) {
String linuxInfo = null;
String memInfo = null;
String cpuInfo = null;
CMDExecute cmdexe = new CMDExecute ( );
try {
String[ ] linuxargs = {"/system/bin/cat", "/proc/version" };
linuxInfo = cmdexe.run(linuxargs, "system/bin/");
String[] cpuargs = {"/system/bin/cat", "/proc/cpuinfo"};
cpuInfo = cmdexe.run(cpuargs, "/system/bin/");
String[] memargs = {"/system/bin/cat", "/proc/meminfo"};
memInfo = cmdexe.run(cpuargs, "/system/bin/");
} catch (IOException ex) {
ex.printStackTrace( );
}
pInfo.setLinuxInfo(linuxInfo);
pInfo.setCpuInfo(cpuInfo);
pInfo.setMemInfo(memInfo);
}
public void fetch_tel_status(PhoneInfo pInfo) {
String result = null;
String networktype = null;
String phoneType = null;
String keyType = null;
String navigationType = null;
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);//
String str = " ";
//串号IMEI
pInfo.setIMEI(tm.getDeviceId());
//串号版本
pInfo.setIMEI_ver(tm.getDeviceSoftwareVersion());
//联网类型
switch(tm.getNetworkType()){
case TelephonyManager.NETWORK_TYPE_EDGE:
networktype="EDGE";break;
case TelephonyManager.NETWORK_TYPE_GPRS:
networktype="GPRS";
case TelephonyManager.NETWORK_TYPE_UMTS:
networktype="UMTS";
default :
networktype="UNKNOWN";break;
}
pInfo.setNetworktype(networktype);
//手机网络类型
switch(tm.getPhoneType()){
case TelephonyManager.PHONE_TYPE_GSM:
phoneType="GSM";break;
case TelephonyManager.PHONE_TYPE_NONE:
phoneType="NONE";break;
default:
phoneType="UNKNOWN";break;
}
pInfo.setPhoneType(phoneType);
//键盘类型
switch(context.getResources().getConfiguration().keyboard){
case 0:
keyType="KEYBOARD_UNDEFINED";break;
case 1:
keyType="KEYBOARD_NOKEYS";break;
case 2:
keyType="KEYBOARD_QWERTY";break;
case 3:
keyType="KEYBOARD_12KEY";break;
}
pInfo.setKeyType(keyType);
//导航方式
switch(context.getResources().getConfiguration().navigation){
case 0:
navigationType="NAVIGATION_UNDEFINED";break;
case 1:
navigationType="NAVIGATION_NONAV";break;
case 2:
navigationType="NAVIGATION_DPAD";break;
case 3:
navigationType="NAVIGATION_TRACKBALL";break;
}
pInfo.setNavigationType(navigationType);
//系统版本
int version = 0;
try{
version = Integer.valueOf(android.os.Build.VERSION.SDK);
}catch(NumberFormatException e){
e.printStackTrace();
}
switch(version){
case 1:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"1.0");break;
case 2:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"1.1");break;
case 3:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"1.5");break;
case 4:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"1.6");break;
case 5:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"2.0");break;
case 6:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"2.0.1");break;
case 7:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"2.1");break;
case 8:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"2.2");break;
case 9:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"2.3");break;
case 10:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"2.3.3");break;
case 11:
pInfo.setSystemInfo(android.os.Build.MODEL+" : "+"3.0");break;
}
//屏幕信息 包括密度 分辨率
DisplayMetrics dm=new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
String screenInfo="density = "+dm.density;
screenInfo+=" heightPixels = "+dm.heightPixels;
screenInfo+=" widthPixels = "+dm.widthPixels;
pInfo.setScreenInfo(screenInfo);
//获取手机内安装的应用列表
String appsInfo="";
for(int i=0;i<activity.getPackageManager().getInstalledApplications(0).size();i++){
ApplicationInfo info=(ApplicationInfo) activity.getPackageManager().getInstalledApplications(0).get(i);
if(info.packageName.equals("com.android")||info.packageName.equals("com.android")){
}
else{
appsInfo+=info.className+",";
}
}
pInfo.setAppsInfo(appsInfo);
}
/**
* linux命令的执行封装类
* @author chaos
*
*/
class CMDExecute {
public synchronized String run(String [] cmd, String workdirectory) throws IOException {
String result = "";
try {
ProcessBuilder builder = new ProcessBuilder(cmd);
InputStream in = null;
//设置一个路径
if (workdirectory != null) {
builder.directory(new File(workdirectory));
builder.redirectErrorStream(true);
Process process = builder.start();
in = process.getInputStream();
byte[] re = new byte[1024];
while (in.read(re) != -1)
result = result + new String(re);
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
/**
* 统计GPRS流量
* 注1:还可以统计wifi usb流量 注2:关机后该文件内容清空
* @return
*/
public long countGPRS()
{
FileReader fstream = null;
try {
fstream = new FileReader(DEV_FILE);
}
catch (FileNotFoundException e) {
}
BufferedReader in = new BufferedReader(fstream, 500);
String line;
String[] segs;
String[] netdata;
int k;
int j;
try {
while ((line = in.readLine()) != null) {
segs = line.trim().split(":");
if (line.startsWith(GPRSLINE))
{
netdata = segs[1].trim().split(" ");
for (k = 0, j = 0; k < netdata.length; k++)
{
if (netdata[k].length() > 0)
{
gprsdata[j] = netdata[k];
j++;
}
}
}
}
fstream.close();
}
catch (IOException e) {
}
long result = +Long.parseLong(gprsdata[0])+Long.parseLong(gprsdata[1])+Long.parseLong(gprsdata[8])+Long.parseLong(gprsdata[9]);
return result;
}
}
在做一个小的电子书程序,要求电子书具有放大缩小的功能,所以肯定的要用到TextView的滚动效果。同样的还要求TextView在水平方向和垂直方向上都可以滚动。刚做的时候,也是没有头绪,后来想到了,TextView有一个ScrollTo或者ScrollBy方法,何不如此一用呢!
1.前期找资料
因为刚开始,不知道怎么能够滚动,所以先去网上查找资料,垂直滚动很容易实现,直接使用TextView的
setMovementMethod(ScrollingMovementMethod.getInstance());
方法就可以了。可是水平滚动如何实现?晚上说在TextView的前面在套一层HorizontalScrollView,这个我也做了尝试,效果不佳,因为你有可能要在程序中动态的改变TextView的布局,这样子程序中就会出错;在者如果你设定了你的TextView为500px,而你的内容一行要有700px,这时你的内容不会自动的切为两行;第三,在添加一个HorizontalScrollView感觉很不舒服,起码界面是这样。所以综合这几点,我放弃了使用这种方法。接着就想到用ScrollTo方法,首先需要声明的是,采用这种方法,你的程序中是没有水平和垂直滚动条的,这个你可以自己去优化实现,理论上是绝对可行的。我现在说的是我能保证文本可以水平和垂直滚动,但没有保证有滚动条。好,接下来,King就以一个实例做一下简单的使用。
2.我的实现。(里面注释很详细,就不过多说了)
public class Test_ScrollingText extends Activity implements OnTouchListener, OnGestureListener { // 实现触摸和手势的接口 private TextView mContent; private DisplayMetrics metrics; private int mScreenWidth, mScreenHeight;// 屏幕分辨率 private GestureDetector mDetector;// 手势监听者 private String mDisplayTxt = ""; private int mCurrentX = 0, mCurrentY = 0;// TextView左上角的像素值 /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 全屏 metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); mScreenWidth = metrics.widthPixels; mScreenHeight = metrics.heightPixels;// 获得屏幕分辨率 setContentView(R.layout.main);// 指定布局 mContent = (TextView) findViewById(R.id.content); resetTextView(); loadFile(); mDetector = new GestureDetector(this); mContent.setOnTouchListener(this); mContent.setLongClickable(true);// 初始化,注意这三步是必不可少的,但没顺序的限制 mContent.setText(mDisplayTxt);// 显示文件内容 } // 加载文件 private void loadFile() { // TODO Auto-generated method stub String mTemp; try { InputStream mInputStream = getAssets().open("jinju.txt"); BufferedReader mBufferedInputStream = new BufferedReader( new InputStreamReader(mInputStream)); while ((mTemp = mBufferedInputStream.readLine()) != null) { mDisplayTxt += mTemp; } mDisplayTxt = mDisplayTxt.replace(' ', '\n'); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 重置TextView的大小 private void resetTextView() { // TODO Auto-generated method stub LinearLayout.LayoutParams mParams = (LayoutParams) mContent .getLayoutParams(); mParams.width = mScreenWidth + 300; mParams.height = mScreenHeight + 500; mContent.setLayoutParams(mParams); } // 触摸TextView @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return mDetector.onTouchEvent(event);// 工作交给手势监听者 } // 下面的各个函数是OnGestureListener的实现,具体动作这里不做赘述 @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub return false; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub int mLayoutWidth = mContent.getLayoutParams().width; // 获得TextView的宽度 int mLayoutHeight = mContent.getLineCount() * mContent.getLineHeight(); // 获得TextView的实际高度 if (mCurrentX + distanceX >= 0) { if (mCurrentX + distanceX > mLayoutWidth - mScreenWidth) { mCurrentX = mLayoutWidth - mScreenWidth; } else { mCurrentX = (int) (mCurrentX + distanceX); } } else { mCurrentX = 0; } if (mCurrentY + distanceY >= 0) { if (mCurrentY + distanceY > mLayoutHeight - mScreenHeight) { mCurrentY = mLayoutHeight - mScreenHeight; } else { mCurrentY = (int) (mCurrentY + distanceY); } } else { mCurrentY = 0; } mContent.scrollTo(mCurrentX, mCurrentY); // 使文本滚动到指定的地方 return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } }
3.后续
我的文件是jinju.txt,是放在assets文件夹下面的,当然你可以放在其他的位置,指定你自己的路径就可以了,main.xml里面只有一个TextView,所以也没贴出来,下面看几张效果图:
http://hi.baidu.com/ljlkings/blog/item/ffe87e6cc51843cf80cb4a55.html
设置带滚动条的TextView
本来是想做一个显示文字信息的,当文字很多时View的高度不能超过一个固定的值,当文字很少时View的高度小于那个固定值时,按View的高度显示。因为ScrollView没有maxHeight,无法满足需求,只好另找方法了。
View本身是可以设置ScrollBar,这样就不一定需要依赖ScrollView了。TextView有个属性maxLine,这样也就满足了需求了,只要设置一个TextView带ScrollBar的,然后设置maxLine就可以了。
<TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="false" android:maxLines="10" android:scrollbars="vertical" />
还需要在代码了设置TextView可以滚动。
TextView textView = (TextView)findViewById(R.id.text_view); textView.setMovementMethod(ScrollingMovementMethod.getInstance());
Android中计算一个文件在TextView中的显示
http://hi.baidu.com/ljlkings/blog/item/47f1afdb8874c9fd39012fdd.html
Message Events 研究!
Description
In order to receive event notifications for a given message you first have to specify which events are you interested in. Each message that you send has to request its own event notifications. Therefore, every message that you send as part of a chat should request its own event notifications.
Usage
The class MessageEventManager provides an easy way for requesting event notifications. All you have to do is specify the message that requires the event notifications and the events that you are interested in.
Use the static method MessageEventManager.addNotificationsRequests(Message message, boolean offline, boolean delivered, boolean displayed, boolean composing) for requesting event notifications.
Example
Below you can find an example that logs in a user to the server, creates a message, adds the requests for notifications and sends the message.
// Connect to the server and log in conn1 = new XMPPConnection(host); conn1.login(server_user1, pass1); // Create a chat with user2 Chat chat1 = conn1.createChat(user2); // Create a message to send Message msg = chat1.createMessage(); msg.setSubject("Any subject you want" ); msg.setBody("An interesting body comes here..." ); // Add to the message all the notifications requests (offline, delivered, displayed, // composing) MessageEventManager.addNotificationsRequests(msg, true , true , true , true ); // Send the message that contains the notifications request chat1.sendMessage(msg);
Description
You can receive notification requests for the following events: delivered, displayed, composing and offline. You must listen for these requests and react accordingly.
Usage
The general idea is to create a new DefaultMessageEventRequestListener that will listen to the event notifications requests and react with custom logic. Then you will have to add the listener to the MessageEventManager that works on the desired XMPPConnection .
Note that DefaultMessageEventRequestListener is a default implementation of the MessageEventRequestListener interface. The class DefaultMessageEventRequestListener automatically sends a delivered notification to the sender of the message if the sender has requested to be notified when the message is delivered. If you decide to create a new class that implements the MessageEventRequestListener interface, please remember to send the delivered notification.
- To create a new MessageEventManager use the MessageEventManager(XMPPConnection) constructor.
- To create an event notification requests listener create a subclass of DefaultMessageEventRequestListener or create a class that implements the MessageEventRequestListener interface.
- To add a listener to the messageEventManager use the MessageEventManager's message addMessageEventRequestListener(MessageEventRequestListener) .
Example
Below you can find an example that connects two users to the server. One user will create a message, add the requests for notifications and will send the message to the other user. The other user will add a DefaultMessageEventRequestListener to a MessageEventManager that will listen and react to the event notification requested by the other user.
// Connect to the server and log in the users conn1 = new XMPPConnection(host); conn1.login(server_user1, pass1); conn2 = new XMPPConnection(host); conn2.login(server_user2, pass2); // User2 creates a MessageEventManager MessageEventManager messageEventManager = new MessageEventManager(conn2); // User2 adds the listener that will react to the event notifications requests messageEventManager.addMessageEventRequestListener(new DefaultMessageEventRequestListener() { public void deliveredNotificationRequested( String from, String packetID, MessageEventManager messageEventManager) { super.deliveredNotificationRequested(from, packetID, messageEventManager); // DefaultMessageEventRequestListener automatically responds that the message was delivered when receives this request System.out.println("Delivered Notification Requested (" + from + ", " + packetID + ")" ); } public void displayedNotificationRequested( String from, String packetID, MessageEventManager messageEventManager) { super.displayedNotificationRequested(from, packetID, messageEventManager); // Send to the message's sender that the message was displayed messageEventManager.sendDisplayedNotification(from, packetID); } public void composingNotificationRequested( String from, String packetID, MessageEventManager messageEventManager) { super.composingNotificationRequested(from, packetID, messageEventManager); // Send to the message's sender that the message's receiver is composing a reply messageEventManager.sendComposingNotification(from, packetID); } public void offlineNotificationRequested( String from, String packetID, MessageEventManager messageEventManager) { super.offlineNotificationRequested(from, packetID, messageEventManager); // The XMPP server should take care of this request. Do nothing. System.out.println("Offline Notification Requested (" + from + ", " + packetID + ")" ); } }); // User1 creates a chat with user2 Chat chat1 = conn1.createChat(user2); // User1 creates a message to send to user2 Message msg = chat1.createMessage(); msg.setSubject("Any subject you want" ); msg.setBody("An interesting body comes here..." ); // User1 adds to the message all the notifications requests (offline, delivered, displayed, // composing) MessageEventManager.addNotificationsRequests(msg, true , true , true , true ); // User1 sends the message that contains the notifications request chat1.sendMessage(msg); Thread.sleep(500); // User2 sends to the message's sender that the message's receiver cancelled composing a reply messageEventManager.sendCancelledNotification(user1, msg.getPacketID());
Description
Once you have requested for event notifications you will start to receive notifications of events. You can receive notifications of the following events: delivered, displayed, composing, offline and cancelled. You will probably want to react to some or all of these events.
Usage
The general idea is to create a new MessageEventNotificationListener that will listen to the event notifications and react with custom logic. Then you will have to add the listener to the MessageEventManager that works on the desired XMPPConnection .
- To create a new MessageEventManager use the MessageEventManager(XMPPConnection) constructor.
- To create an event notifications listener create a class that implements the MessageEventNotificationListener interface.
- To add a listener to the messageEventManager use the MessageEventManager's message addMessageEventNotificationListener(MessageEventNotificationListener) .
Example
Below you can find an example that logs in a user to the server, adds a MessageEventNotificationListener to a MessageEventManager that will listen and react to the event notifications, creates a message, adds the requests for notifications and sends the message.
// Connect to the server and log in conn1 = new XMPPConnection(host); conn1.login(server_user1, pass1); // Create a MessageEventManager MessageEventManager messageEventManager = new MessageEventManager(conn1); // Add the listener that will react to the event notifications messageEventManager.addMessageEventNotificationListener(new MessageEventNotificationListener() { public void deliveredNotification(String from, String packetID) { System.out.println("The message has been delivered (" + from + ", " + packetID + ")" ); } public void displayedNotification(String from, String packetID) { System.out.println("The message has been displayed (" + from + ", " + packetID + ")" ); } public void composingNotification(String from, String packetID) { System.out.println("The message's receiver is composing a reply (" + from + ", " + packetID + ")" ); } public void offlineNotification(String from, String packetID) { System.out.println("The message's receiver is offline (" + from + ", " + packetID + ")" ); } public void cancelledNotification(String from, String packetID) { System.out.println("The message's receiver cancelled composing a reply (" + from + ", " + packetID + ")" ); } }); // Create a chat with user2 Chat chat1 = conn1.createChat(user2); // Create a message to send Message msg = chat1.createMessage(); msg.setSubject("Any subject you want" ); msg.setBody("An interesting body comes here..." ); // Add to the message all the notifications requests (offline, delivered, displayed, // composing) MessageEventManager.addNotificationsRequests(msg, true , true , true , true ); // Send the message that contains the notifications request chat1.sendMessage(msg);