All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.eg.agent.android.sample.eGSampler Maven / Gradle / Ivy

There is a newer version: 2.1.3
Show newest version
package com.eg.agent.android.sample;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.TrafficStats;
import android.os.Debug;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

import com.eg.agent.android.ResourceInforamtion;

public class eGSampler extends TimerTask {
	   private static ResourceInforamtion resourceInforamtion=ResourceInforamtion.getInstance();
	 protected static final long SAMPLE_FREQ_MS = 100L;
	  protected static final long SAMPLE_FREQ_MS_MAX = 250L;
	  private static final int[] PID = { android.os.Process.myPid() };
	  protected static eGSampler sampler;
	
	  private final ActivityManager activityManager;
	  protected final AtomicBoolean isRunning = new AtomicBoolean(false);
	  protected long sampleFreqMs = 100L;
	  private static Long lastCpuTime;
	  private static Long lastAppCpuTime;
	  private static RandomAccessFile procStatFile;
	  private  static RandomAccessFile appStatFile;
	  
	  private static Context context;
	  public eGSampler(Context context)
	  {
		  Log.e("eG","Threads Reunnung");
	    this.activityManager = ((ActivityManager)context.getSystemService("activity"));
	    eGSampler.context=context; 
	  
	  }	
	  public void init(Context contex){
		  this.context=contex;		 
	  }
	 
	public static void sampleMemory(ActivityManager activityManager)
	  {
		Log.e("eG","Memoru CALS");
	    try
	    {
	    	//App memory
	      Debug.MemoryInfo[] memInfo = activityManager.getProcessMemoryInfo(PID);
	      
	      if (memInfo.length > 0)
	      {
	        int totalPss = memInfo[0].getTotalPss();
	        if (totalPss >= 0)
	        {
	          double memory = totalPss / 1024.0D;
	          Log.e("eG App memory",String.valueOf(memory)+" MB");
	          resourceInforamtion.setMemoryUsage(String.valueOf(memory)+" MB");
	         
	        }
	      }
	    
	      try {
	    	  
			long freeBytesInternal = new File(context.getFilesDir().getAbsoluteFile().toString()).getFreeSpace();
	    	 Log.e("eG",String.valueOf(freeBytesInternal)+"bytes");
	          resourceInforamtion.setPhoneAppMemory(String.valueOf(freeBytesInternal));
	      } catch (Exception e) {
	          e.printStackTrace();
	      }
	    }
	    catch (Exception e)
	    {
	    	System.out.println("Sample memory failed: " + e.getMessage());
	   
	    }
		
	    //Phone Disk available
	    File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        long size=totalBlocks * blockSize;
        Log.e("eG Size",String.valueOf(size));
        String suffix = null;

        if (size >= 1024) {
            suffix = "KB";
            size /= 1024;
            if (size >= 1024) {
                suffix = " MB";
                size /= 1024;
            }
        }

        StringBuilder resultBuffer = new StringBuilder(Long.toString(size));

        int commaOffset = resultBuffer.length() - 3;
        while (commaOffset > 0) {
            resultBuffer.insert(commaOffset, ',');
            commaOffset -= 3;
        }

        if (suffix != null) resultBuffer.append(suffix);
        Log.e("eG Phone Disk",resultBuffer.toString());
       resourceInforamtion.setPhoneDiskavailable(resultBuffer.toString());
        
	   
	    
	  }
	  public static void sampleCpu()
	  {
		 Log.e("eG","CPU CALS");
		    try
		    {
		      if ((procStatFile == null) || (appStatFile == null))
		      {
		        procStatFile = new RandomAccessFile("/proc/stat", "r");
		        appStatFile = new RandomAccessFile("/proc/" + PID[0] + "/stat", "r");
		      }
		      else
		      {
		        procStatFile.seek(0L);
		        appStatFile.seek(0L);
		      }
		      String procStatString = procStatFile.readLine();
		      String appStatString = appStatFile.readLine();
		      
		      String[] procStats = procStatString.split(" ");
		      String[] appStats = appStatString.split(" ");
		      
		      long cpuTime = Long.parseLong(procStats[2]) + Long.parseLong(procStats[3]) + Long.parseLong(procStats[4]) + Long.parseLong(procStats[5]) + Long.parseLong(procStats[6]) + Long.parseLong(procStats[7]) + Long.parseLong(procStats[8]);
		      
		      long appTime = Long.parseLong(appStats[13]) + Long.parseLong(appStats[14]);
		      if ((lastCpuTime == null) && (lastAppCpuTime == null))
		      {
		        lastCpuTime = Long.valueOf(cpuTime);
		        lastAppCpuTime = Long.valueOf(appTime);
		        
		      
		      }
		      
		      
		      lastCpuTime = Long.valueOf(cpuTime);
		      lastAppCpuTime = Long.valueOf(appTime);
		      Log.e("eG lastCpuTime",String.valueOf(lastCpuTime/60)+" minute");
		      Log.e("eG lastAppCpuTime",String.valueOf(lastAppCpuTime/60)+"minute");
		      resourceInforamtion.setCputime(String.valueOf(lastCpuTime/60)+" minute");
		      resourceInforamtion.setAppcputime(String.valueOf(lastAppCpuTime/60)+" minute");
		      
		    }
		    catch (Exception e)
		    {
		      
		      System.out.println("Exception hit while CPU sampling: " + e.getMessage());
		      Log.e("eG",e.getMessage());
		    }
		  
		  }
	  //sample data usage 
	  public static void sampleDataUsage(){
	      Log.e("eG","Sample data uasgae");
	      
		 /* final PackageManager pm =context.getPackageManager();
          List packages = pm.getInstalledApplications(0);
          for (ApplicationInfo packageInfo : packages)
          {
              String package_name = packageInfo.packageName;
              ApplicationInfo app = null;
              try {
                  app = pm.getApplicationInfo(package_name, 0);
                       if(app.uid==android.os.Process.myUid()){
                          double recei=(double)TrafficStats.getUidRxBytes(android.os.Process.myUid()) / (1024 * 1024);
                          double se=(double)TrafficStats.getUidRxBytes(android.os.Process.myUid()) / (1024 * 1024);
                          double to=recei+se;
                          String memoryUsage=String.format( "%.2f", to )+" MB";
                          resourceInforamtion.setMemoryUsage(memoryUsage);
                      }

              } catch (PackageManager.NameNotFoundException e) {
            	  Log.e("eG test",e.getMessage());
                  e.printStackTrace();
    		     
              }
          }*/
	      int UID;
	      final PackageManager pm = context.getPackageManager();
          String thisPk=context.getApplicationContext().getPackageName();

          List packages = pm.getInstalledApplications(0);
          for (ApplicationInfo packageInfo : packages)
          {
              UID = packageInfo.uid;
              int myid=android.os.Process.myUid();
              String package_name = packageInfo.packageName;
              ApplicationInfo app = null;
              try {
                  app = pm.getApplicationInfo(package_name, 0);
                  if(app.uid==UID)
                      if(app.uid==android.os.Process.myUid()){

                         // Toast.makeText(getApplicationContext(),"My application j"+String.valueOf(app.uid),Toast.LENGTH_SHORT).show();
                          String name = (String) pm.getApplicationLabel(app);
                          //Toast.makeText(getApplicationContext(),"NNNNAME  "+name,Toast.LENGTH_LONG).show();
                          double recei=(double) TrafficStats.getUidRxBytes(android.os.Process.myUid()) / (1024 * 1024);
                          double se=(double) TrafficStats.getUidRxBytes(android.os.Process.myUid()) / (1024 * 1024);
                          double to=recei+se;
                          String s=String.format( "%.2f", to )+" MB";
                          Log.e("eG data",s);
                          resourceInforamtion.setMemoryUsage(s);
                         // Toast.makeText(getApplicationContext(),"Reveicev s"+s,Toast.LENGTH_LONG).show();
                      }

              } catch (PackageManager.NameNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
	  }
	@Override
	public void run() {
		sampleMemory(activityManager);
		sampleCpu();
		sampleDataUsage();
		
	}
	  

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy