Friday, March 7, 2014

Android : Fetch all running process ,memory and Process ID

Fetch all running process ,memory and Process ID


import java.util.List;
//import android.R;
import android.os.Bundle;
import android.os.Debug;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
        TextView tv = (TextView) findViewById(R.id.textView);       
         ActivityManager activityManager = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
             
          List<RunningAppProcessInfo> procInfos = activityManager .getRunningAppProcesses();
         // List<RunningAppProcessInfo> procInfos2=activityManager.
         for (int idx = 0; idx < procInfos.size(); idx++)
         {
            tv.setText(tv.getText() + "" + (idx + 1) + "."  + procInfos.get(idx).processName +"(" +procInfos.get(idx).pid+")"+"\n");
         }

        
         ActivityManager localActivityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); // use Context.ACTIVITY_SERVICE not the literal "activity"
         List<ActivityManager.RunningAppProcessInfo> procsInfo = localActivityManager.getRunningAppProcesses();

         int[] pids = new int[procsInfo.size()];
         for (int i = 0; i < procsInfo.size(); i++) {
             ActivityManager.RunningAppProcessInfo info = procsInfo.get(i);
             pids[i] = info.pid;
         }

         Debug.MemoryInfo[] procsMemInfo = localActivityManager.getProcessMemoryInfo(pids);
         for (int idx = 0; idx < procsMemInfo.length; idx++)
         {
            tv.setText(tv.getText() + "" + (idx + 1) + "."  +procsMemInfo[idx].getTotalPss()+ "kb\n");
         }
    
}}

 activity_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"
    tools:context=".MainActivity" >
   
        <TextView
            android:id="@+id/textView"
        android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        android:text="Running Apps \n" />
   
</RelativeLayout>

Android : Fetch Application CPU , Memory Usage ,Running Process

Fetch Application CPU , Memory Usage ,Running Process


Below given generic functions can be used in your program without any major mod.

Reference sites :
http://android-test-tw.blogspot.in/2012/10/dumpsys-information-android-open-source.html
http://www.m2catalyst.com/tutorial-finding-cpu-usage-for-individual-android-apps/
http://stackoverflow.com/questions/15148193/how-to-get-higher-precision-of-cpu-than-that-from-top-command
http://stackoverflow.com/questions/11201659/whats-android-adb-shell-dumpsys-tool-and-its-benefits
http://codeseekah.com/2012/10/21/android-shell-tricks-ps/   -(Android shell tricks: ps)




//Fetches the CPU usage of the given Process - Currently all process @ 0%

   private String process_name_cpu(String Process_name)
   {
          try{   
                 ArrayList<String> list2 = new ArrayList<String>();     


  //adb shell dumpsys cpuinfo
        //(adb shell ps | grep com.android.phone | awk '{ system("adb shell cat /proc/" $2 "/stat");}' | awk '{print $14+$15;}')
        //ps -eo pcpu,pid,user,args | sort -r -k1 | less
        //ps -t -x -P -p -c
        //ps -t -x -P -p -c [pid|name]
        //com.android.calculator2|2302
        //Process p2 = Runtime.getRuntime().exec("ps -t -x -P -p -c ["+2302+"]",null,null);

 
                 Process p2 = Runtime.getRuntime().exec("top -m 150  -d 1 -n 1",null,null);//top -m 150  -d 1 -n 1",null,null);
                 BufferedReader reader2 = new BufferedReader(new InputStreamReader(p2.getInputStream()));
                 int i2 = 0;
                 String line2 = reader2.readLine();
                 String a[]={""};          
                // System.out.println(line2);
                 while (line2 != null) {
                       // Log.e("Output "  + i2, line2);
                        list2.add(line2);
                        line2 = reader2.readLine();      
                        i2++ ;
                 }
                 p2.waitFor();
                 for (int i=0 ;i<=list2.size();i++)
                 {     
                        if(list2.get(i).contains(Process_name)==true)
                        {
                              a=list2.get(i).toString().split(" ");
                              break;
                        }
                 }
                
                 for(int i=0;i<=a.length;i++)
                 {
                        if(a[i].contains("%")==true){                            
                        System.out.println("cpu utilization" + a[i]);                      
                        return a[i];
                        }
                 }
                       
          }catch (Throwable t)
                 {
                 System.out.println("Unable to fetch cpu data ---\n"+t.fillInStackTrace());
                 }
         
          return null;
   }



   //---------------------------------------------------------------

   //Description: Retrieves the process name from the application

   //Arguements required : application_name  -- String Type---Input
                        //Ex: app_to_process_name("system")

                        //returns cpu usage --String Type (ex:com.android.system)

   private String app_to_process_name(String application_name)
   {
          try{
                 ArrayList<AppActivity> res = new ArrayList<AppActivity>();       
         
       List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);   
       String sApp_name,sProcess_name;
      
       for(int i=0;i<packs.size();i++)
       {
           PackageInfo p = packs.get(i);
           if ((p.versionName == null))
           {
               continue ;
           }    
          
           sApp_name = p.applicationInfo.loadLabel(getPackageManager()).toString();
           sProcess_name=p.applicationInfo.processName.toString();
          
           if(sApp_name.contentEquals(application_name))
           {
                //System.out.println("gotcha"+ sProcess_name );
               
              
               return sProcess_name;             //break;
                
                
           }      
       }
          }catch (Throwable t)
          {
                 System.out.println("Unable to fetch the process name from the app\n"+t.getMessage());
          }
       return null;
   }


   //Description: Retreives the memory consumed by the particular process

   //Arguements required : sProcess -- String Type---Input
                        //Ex: process_memory("com.android.system")

                        //returns memory usage --integer Type (ex: 22845) /// in kb

   // NOTE: Fetchs the PSS memory of the process
   private int process_memory(String sProcess)
   {
          try{
                 ActivityManager localActivityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); // use Context.ACTIVITY_SERVICE not the literal "activity"        
               List<ActivityManager.RunningAppProcessInfo> procsInfo = localActivityManager.getRunningAppProcesses();
         
               int[] pids = new int[procsInfo.size()];
               for (int i = 0; i < procsInfo.size(); i++)
               {
                   ActivityManager.RunningAppProcessInfo info = procsInfo.get(i);
                   pids[i] = info.pid;
               }
         
               Debug.MemoryInfo[] procsMemInfo = localActivityManager.getProcessMemoryInfo(pids);
               for (int idx = 0; idx < procsMemInfo.length; idx++)
               {
                  if(procsInfo.get(idx).processName.toString().equalsIgnoreCase(sProcess))
                  {
                     
                      System.out.println("memory" + procsMemInfo[idx].getTotalPss());
                         return procsMemInfo[idx].getTotalPss();               
                  }
               }
          }catch (Throwable t)
          {
                 Log.v("process missing","Unable to find the process");
                 System.out.println("Process not found---\n"+t.getMessage());
          //     return 0;
          }
          return 0;            
          }
  
  

Tuesday, March 4, 2014

Android : Implement an Image as Toggle button

 Implement an Image as Toggle button




Step 1 .


Step 2  : activity_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"
    android:background="@drawable/backg">

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="105dp"
    android:background="@drawable/off"
    android:button="@drawable/button_xml"
    android:minHeight="1dip"
    android:minWidth="2dip"
    android:textOff=" "
    android:textOn=" " />

</RelativeLayout>


Step 3 : MainActivity.java

public class MainActivity extends Activity {
public String result ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        final ToggleButton  tb = (ToggleButton) findViewById(R.id.toggleButton1);
         tb.setOnClickListener(new OnClickListener() {
             public void onClick(View v)
             {
                 String s;
                 if(tb.isChecked())
                     
                 {
                     s="ON";
                     Toast.makeText(getBaseContext(),"Button is ON",Toast.LENGTH_SHORT).show();         
                 }
                 else
                 {
                     s="OFF";
                     Toast.makeText(getBaseContext(),"Button is OFF",Toast.LENGTH_SHORT).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;
    }

}

Friday, February 21, 2014

Android : Hide Title Bar and Making full screen

Hide Title Bar and Making full screen



CODE HERE :

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
     
    requestWindowFeature(Window.FEATURE_NO_TITLE);  

    //code that displays the content in full screen mode  


    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

     
    setContentView(R.layout.activity_main); 
   

Thursday, February 20, 2014

Android : Simple Application for Android


Simple Application in Android

Application which prints a message when the button is pressed :


Code Here

package com.example.sample;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {   
        Button oButton;
        TextView txt;
        String message="some data";
       
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           
                /*--------ABOVE IS AUTO CREATED BY PROJECT , CODE STARTS FROM HERE ---*/   
           
            oButton = (Button) findViewById(R.id.button1);
            oButton.setOnClickListener(new Button.OnClickListener() {
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Alert Dialog");
                    builder.setMessage("Welcome to Android Application");
                    builder.setPositiveButton("OK", null);
                    builder.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;
    }
}















activity_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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="108dp"
        android:text="@string/press_me" />
</RelativeLayout>







Android :Creating a Alert Message Box (Toast)

Creating a Alert Message Box

Code Here : 

               AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Alert Dialog");
                builder.setMessage("Welcome to Android Application");
                builder.setPositiveButton("OK", null);
                builder.show();




Code to Display Toast when OK button is pressed
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Alert Dialog");
                builder.setMessage("Welcome to Android Application");
               
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                     public void onClick(DialogInterface dialog,int which)
                     {
              Toast.makeText(getApplicationContext(),"You clicked on OK",   Toast.LENGTH_SHORT).show();        
                     }



example 2:

 Add a button to activity_main.xml

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button oButton=(Button)findViewById(R.id.button);
        oButton.setOnClickListener(
                new Button.OnClickListener(){
                    public void onClick(View v){
                        new misc().alert_box("hi","hi",MainActivity.this);
                    }
                }
        );
    }
} 
----------------------------------------- 
package com.example.dejayapr.test1;
import android.app.AlertDialog;
import android.content.Context;

class misc {

    public void alert_box(String title,String message,Context c){
        AlertDialog alertDialog = new AlertDialog.Builder(c).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.show();
    }
} 
-----------
 

Java : Add Action Listener for GUI

Android : Action listener for button


Action listener for button in Android


Code Below


Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
            //Do stuff here
    }
});

Monday, February 17, 2014

Java : Add Browse button to GUI

Add Browse button to GUI

 

 Before starting :

  1. WindowBuilder Pro - should have been added to eclipse
  2. Create a new project
  3. Inside your package  , Rt ck >New >Other>WindowBuilder-Swing Designer-(Select) Application window.
  4. Once the workspace is created , at the bottom a new tab "Design" will be created. Select that.
  5. Now in the Layout select "Spring Layout" or "Mig Layout"  - this would place the relative and child properties close .
  6. Now in  components > click JButton and click on UI panel where you want it to be placed.
  7. Now right click on the placed element and select Add>Event handler>Mouse >Mouse clicked.
  8. Once done you will be taken to the code, an Anonymous class will be created on JButton.
  9. Come back to design .
  10. In components >select JFile Chooser and place it on the panel.
  11. Once done go back to the source and find JFile Chooser code and put it inside the anonymous inner class of JButton created before.
  12. Now add JFileChoose_object.showOpenDialog(class_name.this);
  13. Now run the same

 

Code Here :

JButton btnBrowse = new JButton("Browse");
        btnBrowse.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser Filechoose=new JFileChooser();
                int retval=Filechoose.showOpenDialog(GUI2.this);

                if (retval == JFileChooser.APPROVE_OPTION) {
                    //... The user selected a file, get it, use it.
                    File file = Filechoose.getSelectedFile();
                    System.out.println(file.getPath());
                }
            }
        });

Java : GUI Design

 GUI Design in Eclipse using Window Builder Pro


Steps below : 
  1.  Open Eclipse 
  2. Open Webpage "https://www.eclipse.org/windowbuilder/download.php"
  3. Click on the suitable link depending on the version of Eclipse.
  4. Once the page has opened >Copy the URL of the new page
  5. Goto Eclipse > Help >Install New Software >  and paste it in "work with" field  
  6. Click on next 

Friday, February 14, 2014

Selenium : Compare 2 images and give percentage similarity

 Compare 2 images and give percentage similarity


visit here: http://www.cse.iitk.ac.in/users/abhik/pixel.java


CODE HERE :

//THIS IS THE SOURCE CODE FOR PIXEL WISE COMPARISON OF TWO IMAGES AND SHOWING PERCENTAGE SIMILARITY.

import java.io.*;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
class spe
{
  public static void main(String args[]) throws IOException{
long start = System.currentTimeMillis();
    File file= new File("p1.png");
    BufferedImage image = ImageIO.read(file);
 int width = image.getWidth(null);
    int height = image.getHeight(null);
int[][] clr=  new int[width][height];
File files= new File("p2.png");
    BufferedImage images = ImageIO.read(files);
 int widthe = images.getWidth(null);
    int heighte = images.getHeight(null);
int[][] clre=  new int[widthe][heighte];
int smw=0;
int smh=0;
int p=0;
//CALUCLATING THE SMALLEST VALUE AMONG WIDTH AND HEIGHT
if(width>widthe){ smw =widthe;}
else {smw=width;}
if(height>heighte){smh=heighte;}
else {smh=height;}
//CHECKING NUMBER OF PIXELS SIMILARITY
for(int a=0;a<smw;a++){
for(int b=0;b<smh;b++){
clre[a][b]=images.getRGB(a,b);
clr[a][b]=image.getRGB(a,b);
if(clr[a][b]==clre[a][b]) {p=p+1;}
}}

float w,h=0;
if(width>widthe) {w=width;}
else {w=widthe;}
if(height>heighte){ h = height;}
else{h = heighte;}
float s = (smw*smh);
//CALUCLATING PERCENTAGE
float x =(100*p)/s;

System.out.println("THE PERCENTAGE SIMILARITY IS APPROXIMATELY ="+x+"%");
long stop = System.currentTimeMillis();
System.out.println("TIME TAKEN IS ="+(stop-start));
  }
}

Thursday, February 13, 2014

Selenium : TakeScreenshot of only Particular element

TakeScreenshot of only Particular element


CODE HERE :
 
/* sPath - Path where the screenshot needs to be saved
oElement - Element object contains the element which is under consideration    */

public static void element_screenshot(WebDriver driver,WebElement oElement,String sPath){
        try{
            File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            BufferedImage  fullImg = ImageIO.read(screenshot);
                    //Get the location of element on the page
            Point point = oElement.getLocation();
                    //Get width and height of the element
            int eleWidth = oElement.getSize().getWidth();
            int eleHeight = oElement.getSize().getHeight();
                    //Crop the entire page screenshot to get only element screenshot
            BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
            ImageIO.write(eleScreenshot, "png", screenshot);
                    //Copy the element screenshot to disk
            FileUtils.copyFile(screenshot, new File(sPath));
        }catch(Throwable t)
        {
            System.out.println("Webelement not found :"+t.getMessage());
        }            
    }

Friday, February 7, 2014

Selenium : Compare 2 Images in Java

Compare 2 Images in Java

CODE HERE  (Simple method to compare 2 images )


 public static boolean Compareimages(String file1,String file2) {
           
            try{
                    File file_1 = new File(file1);
                    File file_2 = new File(file2);
       
                    BufferedImage bufile_1 = ImageIO.read(file_1);
                    DataBuffer dafile_1 = bufile_1.getData().getDataBuffer();
                    int sizefile_1 = dafile_1.getSize();           
                   
                   
                    BufferedImage bufile_2 = ImageIO.read(file_2);
                    DataBuffer dafile_2 = bufile_2.getData().getDataBuffer();
                    int sizefile_2 = dafile_2.getSize();
                   
                    Boolean bFlag = true;
                    System.out.println(bFlag);
                    if(sizefile_1 == sizefile_2) {
                        System.out.println("Size match successfull");
                       for(int j=0; j<sizefile_1; j++) {
                             if(dafile_1.getElem(j) != dafile_2.getElem(j)) {
                                   bFlag = false;
                                   System.out.println("Image comparsion fail !!  :-(");
                                   break;
                             }
                        }
                    }
                    if (bFlag==true)
                        System.out.println("Image comparsion success !! :-) ");      
                        return bFlag;
                       
            }catch(Throwable t){
                    System.out.println("File not found\n"+t.getMessage());
                    Assert.assertTrue(false);
                    return false;
            }
           
        }
    

Wednesday, February 5, 2014

Selenium : Parallel Execution

Parallel Execution

 

In the below screen shot , there is Xml file with "parallel" command which creates threads =Number of tests <classes> <class> .

Here is the screen of the output
 xml file (Note xml file should be outside the package but inside the project meaning testng.xml file have only 1 parent ie., the project where it is placed )


Selenium :ClassNotFoundException: SaxonLiaison

ClassNotFoundException: SaxonLiaison


Error found while generating XSLT report , which requires - saxon.jar, SaxonLiaison.jar  files to be added  to your library.

 

Saxsion Error