Android-版主到處收集的共用程式碼分享(2014/12/25)

Android-版主到處收集的共用程式碼分享(2014/12/25)

Android-版主到處收集的共用程式碼分享(2014/12/25)

 

package com;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.showtime.MainActivity;
import com.example.showtime.R;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Process;
public class CommonModule
{
private int m_intStep;//狀態控制變數
///////////////////////////////////
//主頁變數紀錄_start
private MainActivity m_MA;
private Context m_context;
private int m_tid;
//主頁變數紀錄_end
///////////////////////////////////
//抓取午5TV韌體資訊_start
public static String Get5TVROMVer()
{
String softpath = "/fc/vpd/ROMVer.conf";
String softversion = "";
try
{
String soft_temp = "";
FileReader fr = new FileReader(softpath);
BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
while ((soft_temp = localBufferedReader.readLine()) != null)
{
softversion = softversion + soft_temp;
}
localBufferedReader.close();
}
catch (Exception e)
{
e.printStackTrace();
}
softversion = softversion.replace("softver!", "");
return softversion;
}
//抓取午5TV韌體資訊_end
///////////////////////////////////
//取得系統上安裝APK清單_start
List<PackageInfo> m_AppPakList;
String [] m_StrAllAppPacName;
int m_intAllAppCount;
public void GetSystemAPKList()
{
PackageManager pManager =  m_MA.getPackageManager();
String StrAppName;
String StrPacName;
m_AppPakList = pManager.getInstalledPackages(0);
m_StrAllAppPacName=new String[m_AppPakList.size()];
m_intAllAppCount=m_AppPakList.size();
for (int i = 0; i < m_intAllAppCount; i++)
{
PackageInfo pak = (PackageInfo) m_AppPakList.get(i);
//判断��否为非系统预装的应用程序
if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0)
{
// customs applications
/*
				//set Icon 
				Drawable icon =pManager.getApplicationIcon(pak.applicationInfo);
				ImageView.setImageDrawable(icon);
				*/
StrAppName=pManager.getApplicationLabel(pak.applicationInfo).toString();//set Application Name 
StrPacName=pak.applicationInfo.packageName;//set Package Name
m_StrAllAppPacName[i]=StrPacName;//把packageName放到陣咧中
WriteAppLog("ShowTime","Application Name: "+StrAppName+"\t Package Name: "+StrPacName);//紀錄到Log中
}
}
}
//取得系統上安裝APK清單_end
///////////////////////////////////
//刪除背景程式_start
public void KillBackgroundProcess()//刪除背景程式,自己除外
{
ActivityManager mActivityManager = (ActivityManager)m_context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> ListRunAppInfo = ((ActivityManager) mActivityManager).getRunningAppProcesses();
int whoru_pid = 0;
for (int i = 0; i < ListRunAppInfo.size(); i++)
{
if( ListRunAppInfo.get(i).processName.equals( m_context.getPackageName() ) )
{
whoru_pid = ListRunAppInfo.get(i).pid;
}
else
{
// // kill all exclude urself
try
{
//android.os.Process.sendSignal( activityes.get(i).pid, 9 );
mActivityManager.killBackgroundProcesses( ListRunAppInfo.get(i).processName );
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
/*
	    // kill yourself
	    if( whoru_pid > 0 )
	    {
			try
			{
				android.os.Process.sendSignal( whoru_pid, 9 );				
			} catch(Exception e)
			{
				e.printStackTrace();
			}	    	
	    }
	    */
}
//刪除背景程式_start
//////////////////////////////////
//利用TIMER掃描偵測特定USB設備_start
boolean m_DVBT_USB_EXIST;
UsbDevice m_UsbDevice;
void GetUsbDevices()
{
UsbManager manager = (UsbManager) m_context.getSystemService(m_context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
m_UsbDevice = deviceIterator.next();
if(m_UsbDevice.getVendorId()==1165||m_UsbDevice.getVendorId()==4460){
m_DVBT_USB_EXIST = true;
break;
}else{
m_DVBT_USB_EXIST = false;
}
}
}
//利用TIMER掃描偵測特定USB設備_end
///////////////////////////////////
//等帶時動畫_start
public ProgressDialog m_progressDialog=null;
public static int progress_dialog=0x7f070002;
public Thread m_ThreadAnimation;
public void ShowWaitAnimation(){
m_ThreadAnimation=new Thread
(
new Runnable()
{
public void run()
{
android.os.Process.setThreadPriority(0);
Looper.prepare();
m_progressDialog = ProgressDialog.show(m_context, "", "", false, false);
m_progressDialog.setContentView(R.layout.progress_loader);
Looper.loop();
}
}
);
m_ThreadAnimation.start();
}
public void HideWaitAnimation(){
m_progressDialog.dismiss();
m_progressDialog=null;
m_ThreadAnimation.interrupt();
m_ThreadAnimation=null;
}
//等帶時動畫_end
///////////////////////////////////
//清除APP暫��_start
public boolean [] m_blnDelTempCheck={false,false,false,false};
public void ClearTempFile()
{
for(int i=0;i<4;i++)
{
m_blnDelTempCheck[i]=false;
}
m_blnDelTempCheck[0]=deleteFile( m_context.getCacheDir() );
m_blnDelTempCheck[1]=deleteFile( m_context.getFilesDir() );
m_blnDelTempCheck[2]=deleteFile( m_context.getExternalCacheDir() );
m_blnDelTempCheck[3]=deleteFile( m_context.getExternalFilesDir(null) );
}
public boolean deleteFile( File fileDir )//刪除資料夾內檔案
{
boolean blnAns=false;
try
{
if (fileDir != null)
{
if (fileDir.listFiles() != null && fileDir.listFiles().length > 0){
// recursively delete files in dir
for (File file : fileDir.listFiles()){
blnAns=deleteFile(file);//遞迴
if(blnAns==false)
{
break;
}
}
}
else
{
// file delete
blnAns=fileDir.delete();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return blnAns;
}
public boolean deleteDir(File dir) throws Exception//刪除資料夾
{
try {
if (dir != null && dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
boolean success = deleteDir(new File(dir, children[i]));//遞迴
if (!success)
{
return false;
}
}
}
// <uses-permission
// android:name="android.permission.CLEAR_APP_CACHE"></uses-permission>
// The directory is now empty so delete it
//Log.w(Config.LogcatTag, "deleteDir:" + dir);
return dir.delete();
}
catch (Exception e)
{
throw e;
}
}
//清除APP暫��_end
///////////////////////////////////
///////////////////////////////////
//寫文字檔Log_start
public boolean m_blnDubegflag = true;
public void WriteAppLog(String StrDir,String StrMsg)//
{
File sd=Environment.getExternalStorageDirectory();
String Dir=StrDir;
String logpath=sd.getPath()+"/"+Dir+"/"+Dir+".log";
try
{
if(m_blnDubegflag)
{
FileWriter out = new FileWriter(logpath,true);
out.write((StrMsg+"\n"));
out.close();
}
}
catch(IOException ioe){
System.out.print(ioe);
}
}
public static void CreateAppFloder(String StrDir) // 建立APP 資料夾
{
File sd=Environment.getExternalStorageDirectory();
String path=sd.getPath()+"/"+StrDir;
File floder=new File(path);
String logpath=sd.getPath()+"/"+StrDir+"/"+StrDir+".log";
File logfile=new File(logpath);
if(!floder.exists())
{
floder.mkdir();
}
else
{
if(logfile.exists())
{
logfile.delete();
}
}
}
//寫文字檔Log_end
///////////////////////////////////
//Http DownLoad_start
public int m_intDownLoadAmount=0;//數量
public boolean m_blnDownLoadFinish=false;
public ArrayList<String> m_ListDownLoadFileName = new ArrayList<String>();
public ArrayList<String> m_ListDownLoadUrlPath = new ArrayList<String>();
public String m_StrDownLoadFileName;
public String m_StrDownLoadUrlPath;
public String m_StrFloderPath;
//add(s);.size();get(int index);clear();
Thread m_threadDownload;
public void DownLoadFile(String StrDir,String [] StrUrl,String [] StrFileName,int Amount)
{
m_blnDownLoadFinish=false;
File sd=Environment.getExternalStorageDirectory();
m_StrFloderPath=sd.getPath()+"/"+StrDir+"/";
m_ListDownLoadFileName.clear();
m_ListDownLoadUrlPath.clear();
m_intDownLoadAmount=Amount;
for(int i=0;i<Amount;i++)
{
m_ListDownLoadFileName.add((m_StrFloderPath+StrFileName[i]));
m_ListDownLoadUrlPath.add(StrUrl[i]);
}
m_threadDownload =new Thread(mDownloadList);
m_threadDownload.start();
}
public Runnable mDownloadList = new Runnable()
{
@Override
public void run()
{
int BUFFER = 1024;
long lngFileSize;
long lngDownloadSize;
for(int i=0;i<m_intDownLoadAmount;i++)
{
lngFileSize=0;
lngDownloadSize=0;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(m_ListDownLoadUrlPath.get(i));
try
{
HttpResponse response = httpClient.execute(httpGet);
InputStream in = response.getEntity().getContent();
lngFileSize=response.getEntity().getContentLength();
FileOutputStream out;
out = new FileOutputStream(new File(m_ListDownLoadFileName.get(i)));
byte[] b = new byte[BUFFER];
int len = 0;
lngDownloadSize=0;
while((len=in.read(b))!= -1)
{
lngDownloadSize+=len;
out.write(b,0,len);
}
in.close();
out.close();
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
//httpGet.releaseConnection();
httpClient.getConnectionManager().shutdown();
}
}
m_blnDownLoadFinish=true;
//m_threadDownload.interrupt();
//m_threadDownload=null;
}
};
public void DownLoadFile(String StrDir,String StrUrl,String StrFileName)
{
m_blnDownLoadFinish=false;
File sd=Environment.getExternalStorageDirectory();
m_StrFloderPath=sd.getPath()+"/"+StrDir+"/";
m_StrDownLoadFileName=m_StrFloderPath+StrFileName;
m_StrDownLoadUrlPath=StrUrl;
m_threadDownload =new Thread(mDownload);
m_threadDownload.start();
}
public Runnable mDownload = new Runnable()
{
@Override
public void run()
{
int BUFFER = 1024;
long lngFileSize;
long lngDownloadSize;
lngFileSize=0;
lngDownloadSize=0;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(m_StrDownLoadUrlPath);
try
{
HttpResponse response = httpClient.execute(httpGet);
InputStream in = response.getEntity().getContent();
lngFileSize=response.getEntity().getContentLength();
FileOutputStream out;
out = new FileOutputStream(new File(m_StrDownLoadFileName));
byte[] b = new byte[BUFFER];
int len = 0;
lngDownloadSize=0;
while((len=in.read(b))!= -1)
{
lngDownloadSize+=len;
out.write(b,0,len);
}
in.close();
out.close();
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
//httpGet.releaseConnection();
httpClient.getConnectionManager().shutdown();
}
m_blnDownLoadFinish=true;
//m_threadDownload.interrupt();
//m_threadDownload=null;
}
};
//Http DownLoad_end
///////////////////////////////////
//Read JSON_start
public String m_StrJSONData;
public void ReadJSON(String StrDir,String StrFileName)
{
File sd=Environment.getExternalStorageDirectory();
String StrJSONFilePath=sd.getPath()+"/"+StrDir+"/"+StrFileName;
m_MA.m_TextView1.append(StrJSONFilePath+"\n");
try
{
BufferedReader in = new BufferedReader(new FileReader(StrJSONFilePath));
String s;
StringBuilder sb = new StringBuilder();
while ((s = in.readLine()) != null)
{
sb.append(s);//sb.append(s + "\n");
}
in.close();
m_StrJSONData=sb.toString();
m_MA.m_TextView1.append(m_StrJSONData+"\n");
//m_StrJSONData=m_StrJSONData.substring(8, (m_StrJSONData.length()-1));
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void ParserOttJSON()
{
int intJsonAmount=0;
String []StrUrlArray;
String []StrPackageNameArray;
m_StrJSONData=m_StrJSONData.substring(8, (m_StrJSONData.length()-1));//剪去一開始{"data":和尾巴的}
try
{
JSONArray jsonArray = new JSONArray(m_StrJSONData);
intJsonAmount=jsonArray.length();
StrUrlArray=new String[intJsonAmount];
StrPackageNameArray=new String[intJsonAmount];
for(int i=0;i<intJsonAmount;i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
StrUrlArray[i]=new String();
StrPackageNameArray[i]=new String();
StrUrlArray[i] = jsonObject.getString("appicon");
StrPackageNameArray[i] = jsonObject.getString("apkname")+".png";
}
DownLoadFile("ShowTime",StrUrlArray,StrPackageNameArray,intJsonAmount);
}
catch (JSONException e)
{
throw new RuntimeException(e);
}
}
//Read JSON_end
///////////////////////////////////
//Http post_start
public String m_StrCookie="";
public String m_StrHttpResult="";
public String m_StrHttpPostConnectUrl="";
public Boolean m_blnHttpPostConnectCookie=true;
public int m_intHttpPostConnectTimeOut=3000;
public void HttpPostConnect(String StrUrl,Boolean blnCookie)//可設定��否使用Cookie
{
m_blnDownLoadFinish=false;
m_StrHttpPostConnectUrl=StrUrl;
m_blnHttpPostConnectCookie=blnCookie;
m_threadDownload =new Thread(mPostConnect);
m_threadDownload.start();
}
public Runnable mPostConnect = new Runnable()
{
@Override
public void run()
{
DefaultHttpClient httpClient = new DefaultHttpClient();
try
{
HttpGet httpGet = new HttpGet(m_StrHttpPostConnectUrl);
if(m_blnHttpPostConnectCookie==true)
{
httpGet.setHeader("Cookie", m_StrCookie);
}
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
m_StrHttpResult = EntityUtils.toString(entity, HTTP.UTF_8);
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
//httpGet.releaseConnection();
httpClient.getConnectionManager().shutdown();
}
m_blnDownLoadFinish=true;
//m_threadDownload.interrupt();
//m_threadDownload=null;
}
};
public void HttpPostConnect(String StrUrl)//可設定intTimeOut,並回傳Cookie
{
m_blnDownLoadFinish=false;
m_StrHttpPostConnectUrl=StrUrl;
m_threadDownload =new Thread(mPostConnect1);
m_threadDownload.start();
}
public Runnable mPostConnect1 = new Runnable()
{
@Override
public void run()
{
String StrCookie="";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(m_StrHttpPostConnectUrl);
try
{
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
m_StrHttpResult = EntityUtils.toString(entity, HTTP.UTF_8);
//獲得Cookie
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
if (!cookies.isEmpty())
{
for (int i = 0; i < cookies.size(); i++)
{
Cookie cookie = cookies.get(i);
StrCookie = cookie.getName() + "=" + cookie.getValue() + ";domain=" + cookie.getDomain();
}
}
else
{
StrCookie="get cookie error";
}
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
//httpGet.releaseConnection();
httpClient.getConnectionManager().shutdown();
}
m_StrCookie=StrCookie;
m_blnDownLoadFinish=true;
//m_threadDownload.interrupt();
//m_threadDownload=null;
}
};
public void HttpPostConnect(String StrUrl,Boolean blnCookie,int intTimeOut)//可設定intTimeOut,並回傳Cookie
{
m_blnDownLoadFinish=false;
m_StrHttpPostConnectUrl=StrUrl;
m_blnHttpPostConnectCookie=blnCookie;
m_intHttpPostConnectTimeOut=intTimeOut;
m_threadDownload =new Thread(mPostConnect2);
m_threadDownload.start();
}
public Runnable mPostConnect2 = new Runnable()
{
@Override
public void run()
{
try
{
HttpURLConnection huc = null;
if(m_StrHttpPostConnectUrl.contains("http://"))
{
huc = (HttpURLConnection) (new URL(m_StrHttpPostConnectUrl).openConnection());
}
else
{
huc = (HttpURLConnection) (new URL("http://" + m_StrHttpPostConnectUrl).openConnection());
}
huc.setConnectTimeout(m_intHttpPostConnectTimeOut);
if(m_blnHttpPostConnectCookie)
{
huc.setRequestProperty("Cookie", m_StrCookie);
}
huc.connect();
BufferedReader reader = new BufferedReader( new InputStreamReader( huc.getInputStream(), "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line=null;
while( ((line = reader.readLine()) != null) )
{
buffer.append(line + "\n");
}
if(buffer.length() > 0)
{
m_StrHttpResult =buffer.toString();
}
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
m_blnDownLoadFinish=true;
//m_threadDownload.interrupt();
//m_threadDownload=null;
}
};
//Http post_end
///////////////////////////////////
//關閉程式提示_start
public void CloseAlertDialog(){
new AlertDialog.Builder(m_MA)//
.setTitle("詢問��否要關閉程式...")
//.setIcon("图示")//
.setMessage("��否要關閉程式")//
.setPositiveButton("確定",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog,int which)
{
System.exit(0);//关闭程序语法
// 或使用Process.killProcess(Process.myPid());
}
})//
.setNeutralButton("不離開", null)//
.show();
}
//關閉程式提示_start
///////////////////////////////////
//啟動外部程式_start
public void RunApp(String PackageName){
Intent intent = m_MA.getPackageManager().getLaunchIntentForPackage(PackageName);
m_MA.startActivity(intent);
//this.finish();//結束自己
}
//啟動外部程式_end
///////////////////////////////////
//GUI提示訊息_start
public void ShowMessage(String str)
{
Toast toast = Toast.makeText(m_MA, str, Toast.LENGTH_SHORT);
toast.show();
}
public Toast toast_RT = null;
public void ShowMessage_RT(final String Strmsg,final int inttxtSize,final String StrColor) {
((Activity) m_context).runOnUiThread( new Runnable() {
public void run() {
// 要改變介面的程式寫在這裡
try {
if (toast_RT == null) {
toast_RT = Toast.makeText(m_context, Strmsg, Toast.LENGTH_SHORT);
} else {
toast_RT.setText(Strmsg);
}
toast_RT.setGravity(Gravity.RIGHT | Gravity.TOP, 0, 0); //設定顯示在右上                
toast_RT.setMargin(0.05F, 0.05F);//設定框邊
LinearLayout linearLayout = (LinearLayout) toast_RT.getView();//將Toast強制轉換成LinearLayout+TextView
TextView messageTextView = (TextView) linearLayout.getChildAt(0);
messageTextView.setTextSize(inttxtSize);//設定字型大小 先前為51
messageTextView.setBackgroundColor(Color.parseColor(StrColor));//"#00000000"
toast_RT.show();
} catch(Exception e) {}
}});
}
//GUI提示訊息_end
///////////////////////////////////
//紀錄��活時間_start
public int m_intLifeCycle;
void initLifeCycle()
{
m_intLifeCycle=0;
}
void CountLifeCycle(int TimeDelay)
{
m_intLifeCycle+=(TimeDelay)/1000;
}
//紀錄��活時間_end
///////////////////////////////////
//判斷網路正常與否_start
public boolean CheckNetWork()
{
ConnectivityManager cm =(ConnectivityManager) m_context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
//判斷網路正常與否_end
///////////////////////////////////
//呼叫系統設定UI_start
public void CallSystemSettings()
{
Intent i = new Intent();
ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings");
i.setComponent(comp);
m_context.startActivity(i);
}
//呼叫系統設定UI_end
///////////////////////////////////
//抓取CPU使用率_start
public static String getCpuRate()//測試結果無法和Toast一起使用
{
String Result,StrOut;
ProcessBuilder cmd;
StrOut="";
try
{
java.lang.Process p = Runtime.getRuntime().exec("top -n 1");
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream ()));
while((Result=br.readLine())!=null)
{
if(Result.trim().length()<1)
{
continue;
}
else
{
String[] CPUusr = Result.split("%");
StrOut+="USER:"+CPUusr[0]+"\n";
String[] CPUusage = CPUusr[0].split("User");
String[] SYSusage = CPUusr[1].split("System");
StrOut+="CPU:"+CPUusage[1].trim()+" length:"+CPUusage[1].trim().length()+"\n";
StrOut+="SYS:"+SYSusage[1].trim()+" length:"+SYSusage[1].trim().length()+"\n";
StrOut+=Result+"\n";
break;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return StrOut;
}
//計算某個時間段內AppCpuTime與TotalCpuTime的變化,然後按照比例換算成該應用的Cpu使用率
public static float getProcessCpuRate()
{
float totalCpuTime1 = getTotalCpuTime();
float processCpuTime1 = getAppCpuTime();
try
{
Thread.sleep(360);
}
catch (Exception e)
{
}
float totalCpuTime2 = getTotalCpuTime();
float processCpuTime2 = getAppCpuTime();
float cpuRate = 100 * (processCpuTime2 - processCpuTime1)
/ (totalCpuTime2 - totalCpuTime1);
return cpuRate;
}
public static long getAppCpuTime()
{ // 獲取應用佔用的CPU時間
String[] cpuInfos = null;
try
{
int pid = android.os.Process.myPid();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream("/proc/" + pid + "/stat")), 1000);
String load = reader.readLine();
reader.close();
cpuInfos = load.split(" ");
}
catch (IOException ex)
{
ex.printStackTrace();
}
long appCpuTime = Long.parseLong(cpuInfos[13])
+ Long.parseLong(cpuInfos[14]) + Long.parseLong(cpuInfos[15])
+ Long.parseLong(cpuInfos[16]);
return appCpuTime;
}
public static long getTotalCpuTime()
{ // 獲取系統總CPU使用時間
String[] cpuInfos = null;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/stat")), 1000);
String load = reader.readLine();
reader.close();
cpuInfos = load.split(" ");
}
catch (IOException ex)
{
ex.printStackTrace();
}
long totalCpu = Long.parseLong(cpuInfos[2])
+ Long.parseLong(cpuInfos[3]) + Long.parseLong(cpuInfos[4])
+ Long.parseLong(cpuInfos[6]) + Long.parseLong(cpuInfos[5])
+ Long.parseLong(cpuInfos[7]) + Long.parseLong(cpuInfos[8]);
return totalCpu;
}
//抓取CPU使用率_end
///////////////////////////////////
//畫面相關變數與函數_start	
public long m_lngDispalyWidth,m_lngDispalyHeight;
public long m_lngDispalyGCD;//最大公因數
public long m_lngDispalyX,m_lngDispalyY;//計算後實際畫面的畫布大小
public long m_lngBackgroundWidth,m_lngBackgroundHeight;//底圖或者其它要貼圖實際寬��
public long m_lngBackgroundGCD;//最大公因數
public long m_lngBackgroundX,m_lngBackgroundY;
public long m_lngBlankWidth,m_lngBlankHeight;
public float m_fltProportion;
public void CalculateBackground(long D_Width,long D_Height,long B_Width,long B_Height)//計算畫面參數
{
m_lngDispalyWidth=D_Width;
m_lngDispalyHeight=D_Height;
m_lngBackgroundWidth=B_Width;
m_lngBackgroundHeight=B_Height;
m_lngDispalyGCD=GCDfun(m_lngDispalyWidth,m_lngDispalyHeight);
m_lngDispalyX=m_lngDispalyWidth/m_lngDispalyGCD;
m_lngDispalyY=m_lngDispalyHeight/m_lngDispalyGCD;
m_lngBackgroundGCD=GCDfun(m_lngBackgroundWidth,m_lngBackgroundHeight);
m_lngBackgroundX=m_lngBackgroundWidth/m_lngBackgroundGCD;
m_lngBackgroundY=m_lngBackgroundHeight/m_lngBackgroundGCD;
if((m_lngDispalyX==m_lngBackgroundX)&&(m_lngDispalyY==m_lngBackgroundY))
{
m_lngBlankWidth=0;m_lngBlankWidth=0;
m_fltProportion=(float)m_lngDispalyWidth/(float)m_lngBackgroundWidth;
}
else
{
m_fltProportion=(float)m_lngDispalyWidth/(float)m_lngBackgroundWidth;
if((m_fltProportion*m_lngBackgroundHeight)<=((float)m_lngDispalyHeight))
{
m_lngBlankWidth=m_lngDispalyWidth-(long)(m_lngBackgroundWidth*m_fltProportion);
m_lngBlankHeight=m_lngDispalyHeight-(long)(m_lngBackgroundHeight*m_fltProportion);
}
else
{
m_fltProportion=(float)m_lngDispalyHeight/(float)m_lngBackgroundHeight;
m_lngBlankWidth=m_lngDispalyWidth-(long)(m_lngBackgroundWidth*m_fltProportion);
m_lngBlankHeight=m_lngDispalyHeight-(long)(m_lngBackgroundHeight*m_fltProportion);
}
}
}
//畫面相關變數與函數_end
///////////////////////////
//Timer相關變數與函數_start
Handler m_HandlerTimer;
private final Runnable TimerRun = new Runnable()
{
public void run()
{
//將MainActivity的權限提升_start
android.os.Process.setThreadPriority(m_tid, -10);	//A Linux priority level, from -20 for highest scheduling priority to 19 for lowest scheduling priority.
//將MainActivity的權限提升_end
/////////////////////
//Timer的動作內容_start
SimpleDateFormat FormatTime = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis()) ; // 獲取當前時間
m_MA.m_TextView1.setText("螢幕解析度:"+m_MA.m_metrics.widthPixels+"x"+m_MA.m_metrics.heightPixels+"\n");
m_MA.m_TextView1.append(FormatTime.format(curDate)+"\n");
CountLifeCycle(1000);
m_MA.m_TextView1.append("判斷網路狀態: "+CheckNetWork());
//CallSystemSettings();
//m_MA.m_TextView1.append("5TV韌體版本: "+Get5TVROMVer()+"\n");
//m_MA.m_TextView1.append("CPU使用率: \n"+getCpuRate()+"\n");
//m_MA.m_TextView1.append("CPU使用總時間: "+getTotalCpuTime()+"\n");
//m_MA.m_TextView1.append("APP使用總時間: "+getAppCpuTime()+"\n");
//m_MA.m_TextView1.append("本程式CPU使用率: "+getProcessCpuRate()+"%\n");
///*
ShowMessage_RT("目前已��活: "+m_intLifeCycle+" 秒",20,"#00000000");
m_HandlerTimer.postDelayed(TimerRun, 1000);//重新啟動Timer
//*/
/*
			if(m_intStep==1)
			{
				m_MA.m_TextView1.append("顯示動畫"+"\n");
				ShowWaitAnimation();
				m_intStep++;
			}
			else
			{
				m_MA.m_TextView1.append("隱藏動畫"+"\n");
				HideWaitAnimation();
				m_intStep--;
			}
			//*/
/*
			GetUsbDevices();
			if(m_DVBT_USB_EXIST)
			{
				m_MA.m_TextView1.append("偵測到DVBT的USB"+"\n");
			}
			else
			{
				m_MA.m_TextView1.append("請插入DVBT的USB"+"\n");
			}
			m_HandlerTimer.postDelayed(TimerRun, 1000);//重新啟動Timer
			//*/
/*
			switch(m_intStep)
			{
			case 1:
				curDate = new Date(System.currentTimeMillis()) ; // 獲取當前時間
				WriteAppLog("ShowTime",FormatTime.format(curDate));
				GetSystemAPKList();//將系統內USER裝的APP紀錄起來
				curDate = new Date(System.currentTimeMillis()) ; // 獲取當前時間
				WriteAppLog("ShowTime",FormatTime.format(curDate));
				m_intStep=2;
				break;
			case 2:
				if( (m_threadDownload==null) && (m_blnDownLoadFinish==false) )
				{
					 DownLoadFile("ShowTime","http://apk.ottclub.info/t.sx.php?fmt=json","ottclub.json");
				}
				if( (m_threadDownload!=null) && (m_blnDownLoadFinish==true) )
				{
					m_threadDownload.interrupt();
					m_threadDownload=null;
					m_blnDownLoadFinish=false;
					m_intStep=4;
				}
				break;
			case 4:
				m_MA.m_TextView1.append("下載清單完成"+"\n");
				if( (m_threadDownload==null) && (m_blnDownLoadFinish==false) )
				{
					ReadJSON("ShowTime","ottclub.json");
					ParserOttJSON();					
				}
				if( (m_threadDownload!=null) && (m_blnDownLoadFinish==true) )
				{
					m_threadDownload.interrupt();
					m_threadDownload=null;
					m_blnDownLoadFinish=false;
					m_intStep=8;
				}
				break;
			case 8:
				m_MA.m_TextView1.append("下載ICONS完成"+"\n");
				if( (m_threadDownload==null) && (m_blnDownLoadFinish==false) )
				{
					HttpPostConnect("http://develop.tw-airnet.net/sessions/develop/usb/jl200001");
				}
				if( (m_threadDownload!=null) && (m_blnDownLoadFinish==true) )
				{
					m_threadDownload.interrupt();
					m_threadDownload=null;
					m_blnDownLoadFinish=false;
					m_intStep=16;
				}
				break;
			case 16:
				m_MA.m_TextView1.append("Cookie="+m_StrCookie+"\n");
				if( (m_threadDownload==null) && (m_blnDownLoadFinish==false) )
				{
					HttpPostConnect("http://develop.tw-airnet.net/tw/my_channel_ktv/main",true,3000);
				}
				if( (m_threadDownload!=null) && (m_blnDownLoadFinish==true) )
				{
					m_threadDownload.interrupt();
					m_threadDownload=null;
					m_blnDownLoadFinish=false;
					m_intStep=32;
				}
			case 32:
				m_MA.m_TextView1.append("Cookie="+m_StrCookie+"\n");
				m_MA.m_TextView1.append("HttpResult="+m_StrHttpResult+"\n");
				break;
			}
			//Timer的動作內容_end
			/////////////////////
			m_HandlerTimer.postDelayed(TimerRun, 100);//重新啟動Timer
			// */
}
};
//Timer相關變數與函數_end
///////////////////////////
public long GCDfun(long a,long b)//求最大公因子_2_以辗转相除法
{
int c=0;
c=(int)(a%b);
if(c==0)
return b;
return GCDfun(b,c);
}
public CommonModule(MainActivity ma, Context context,int tid)//建構子
{
//函數參數接收_start
m_MA = ma;
m_context = context;
m_tid=tid;
//函數參數接收_end
//將MainActivity的權限提升_start
android.os.Process.setThreadPriority(m_tid, -10);	//A Linux priority level, from -20 for highest scheduling priority to 19 for lowest scheduling priority.
//將MainActivity的權限提升_end
//畫面相關變數初始化_start
m_lngDispalyWidth=0;m_lngDispalyHeight=0;
m_lngDispalyGCD=0;
m_lngDispalyX=0;m_lngDispalyY=0;
m_lngBackgroundWidth=0;m_lngBackgroundHeight=0;
m_lngBackgroundGCD=0;
m_lngBackgroundX=0;m_lngBackgroundY=0;
m_lngBlankWidth=0;m_lngBlankHeight=0;
m_fltProportion=0;
//畫面相關變數初始化_end
m_intStep=1;//狀態控制變數初始化
m_blnDubegflag = true;
CreateAppFloder("ShowTime") ;//建立APP對應目錄
//Timer變數初始化_start
m_HandlerTimer= new Handler();//建立Timer物件
m_HandlerTimer.postDelayed(TimerRun, 100);//啟動Timer
//Timer變數初始化_end
initLifeCycle();//初始計算��活時間
}
}


 
 

 




發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *