Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Saturday, February 24, 2018

Linux : Access Linux machine using Android

To Connect linux (debian) with Android

1. Linux - sudo apt-get install openssh-client  (remember if u want to access a system then should run client server)
2. Linux - sudo service ssh start
3. Linux -sudo service ssh status
4. Find ip address of the using - sudo ifconfig
(find ip address - usually eth0 in 1st para , for rasp pi search for something like 192.168.1.34 or something like that)
5. Now in Linux
addnew user : sudo useradd -m deepak -G sudo
add password : sudo passwd fred

6. In Android install termux app
7. Open termux  run command - apt install openssh

8. optional(https://linuxconfig.org/ssh-into-linux-your-computer-from-android-with-termux
ssh-keygen -b 4096 -t rsa
ssh-copy-id -i ~/.ssh/id_rsa.pub username@192.168.1.1 )

9. ssh deepak@raspberry_ip
ex:ssh deepak"192.168.1.34

Monday, October 30, 2017

Python : Making REST Requests on Android Phone with Python

Making REST Requests on Android Phone with Python

Make sure the phone is connected to the network

1. Install Termux app on your Android phone
2. Open Termux 
3. Enter "apt install python"
4. Enter "y" when asked
5. After installation enter "python" to check the ver details .
6. Type "exit()"
7. Repeat same for python2 and python3

Once done 
8. Enter "pip install requests" in your termux prompt to install "requests" library for python
9. Repeat commands "pip install json"  and "pip install urllib3"
10. Open python using command python or python2
11. Run command :
>>import requests
 r=requests.get("http://www.google.com")
print(r)
<Response [200]>


Tuesday, November 29, 2016

Android : Create a Signed Apk using Android Studio

Create a Signed Apk using Android Studio


  1. open project in Android Studio
  2. Build > generate Signed APK >Create New
  3. Click on file path button in "Key store path"
  4. Select any folder or create new 
  5. Enter File name > OK button
  6.  Enter any Password and Confirm the same
  7. Key >Enter any Alias name
  8. Enter any Password and Confirm
  9. Under Certificate populate valid data
  10. Click on OK button
  11. Screen goes back to "Generate Signed APK" window >Enter Password and confirm the same
  12. Ck on Next
  13.  Click on Finish
  14. Gradle will take some time and after that user will get message "generated successfully"
  15. Click on "Show in explorer" to navigate to apk file


Monday, November 28, 2016

Android : Send SMS


Add below line in Manifest file
<uses-permission android:name="android.permission.SEND_SMS" />
 
 Eg Manifest File:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.dejayapr.test1">

    <!-- To auto-complete the email text field in the login form with the user's emails -->    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.SEND_SMS" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".new_Activity" />
        <activity android:name=".Allusers"></activity>
    </application>

</manifest>
 
 
 
Code below :
 
import android.Manifest;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
 
 
public void sendSMS_simple(String email,String password){
    try {
        PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, Object.class), 0);
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(this.phoneNo, null, email +"\n"+ password, null, null);
        Log.i("sms","SMS Sent - sendSMS_simple()"); //title - has to be in smaller case in Log.d,v,i,
    }catch(Exception e){
        Log.d("Exception Happened",e.getMessage());
    }
}

Thursday, November 24, 2016

Android : Rotating Progress Box

Rotating Progress Box

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;


public void progress_box()  {
    final ProgressDialog  progressDialog = new ProgressDialog(this);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage("Logging in ...");
    progressDialog.show();
    Runnable progressRunnable = new Runnable() {
        @Override        public void run() {
            progressDialog.cancel();
            new misc().alert_box("Error !","No Internet Connection Available",MainActivity.this);
        }
    };
    Handler pdCanceller = new Handler();
    pdCanceller.postDelayed(progressRunnable, 2000);

}
 
 
 
Make sure the following codes is present in build.gradle (Module:app) file :

apply plugin: 'com.android.application'
android {
    compileSdkVersion 24    buildToolsVersion "24.0.3"    defaultConfig {
        applicationId "com.example.dejayapr.test1"        minSdkVersion 15        targetSdkVersion 24        versionCode 1        versionName "1.0"        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"    }
    buildTypes {
        release {
            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }
    }
    repositories {
        maven { url 'http://repo1.maven.org/maven2' }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'    })
    compile 'com.android.support:appcompat-v7:24.2.1'    compile 'com.android.support:design:24.2.1'    testCompile 'junit:junit:4.12'}

Tuesday, November 15, 2016

Android : Context

Context 

Context = Current Screen

Assuming MainActivity is currently being displayed on the screen it will hold the context.If any other method require context ,  than needs to be passed as an argument as "MainActivity.this" and receiving method receives as (Context c)

Synatx:
Method_name(ParentClass.this); // assuming ParentClass holding the context

public void Method_name(Context c){
}

Eg : 
public class MainActivity extends AppCompatActivity {

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

       DBOperations oDBOperations=new DBOperations(MainActivity.this);
       oDBOperations.get_db_location(MainActivity.this);

    }
}

public class DBOperations {

    SQLiteOpenHelper sql_helper;
    DBOperations(Context context){
        sql_helper=new sqllitehelperclass(context);
    }
 
 public void get_db_location(Context c){
        String dbname = "mydb.db";
        Log.d("db path",c.getDatabasePath(dbname).toString());
    }
}

Tuesday, November 8, 2016

Android :make Android Studio work faster Offline

Make Android Studio work faster Offline


  1. File >Settings >Build,execution,Deployment>Compiler>In Command-line Options enter "--offline" without quotes
  2. File >Settings >Build,execution,Deployment>Gradle>Check "Offline Work" checkbox
  3. Press Apply and Ok
  4. In your Project>gradle Scripts>gradle.properties>add lines
org.gradle.daemon=trueorg.gradle.parallel=true

Saturday, March 7, 2015

Android :Unable to instantiate activity ComponentInfo

Unable to instantiate activity ComponentInfo





You may be trying to find the view before onCreate() which is incorrect.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect

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

Sunday, March 1, 2015

Android : Creating a new Activity (new screen)

Creating a new Activity


Creating new activity and navigating onclick button (Explicit Activity)
    1. goto res/layout > rt ck > select "new xml file" and "new_layout"
    2. Add objects,make modifications to new layout xml file in graphical view
    3. Manifest file : add below code  inside "<application> </application>"
   
            <activity android:name=".new_Activity">
 
       
    4. Goto src/package > rt ck and select new>Class
    5. give name as "new_Activity" ,ck OK and add below code in "new_Activity"
   
   
        import android.app.Activity;
        public class  new_Activity extends Activity
        {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.new_layout);
                }
        }


    6. Goto activity_main.xml ,create a button and in properties>view>On click-"method_name" and save
    7. Goto Mainactivity>add below method inside the class :
        public void method_name(View V)
        {
            Intent intent=new Intent(this,new_Activity.class);
            startActivity(intent);
        }

Saturday, February 28, 2015

Android :How to auto import the necessary classes in Android Studio with shortcut?

Android :How to auto import the necessary classes in Android Studio with shortcut?


Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:
Select Insert imports on paste value to All
Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*


 Screenshot

Tuesday, January 27, 2015

Android :Working with DB

Android :Working with DB


You will be needing 3 user defined class files.
  1. File A which extends sqlitehelper (compulsory)
  2. File B which contains all methods like - create table,Insert data,Select etc.,
  3. File C , for Getter and Setter Class which is more for making your code more classy.

Let File A =sqllitehelperclass
Let File B = DBOperations
Let File C= Persons


sqllitehelperclass.java

public class sqllitehelperclass extends SQLiteOpenHelper
 {

    public sqllitehelperclass(Context context)
    {
        super(context, "test_db", null, 1);
    }
   
    @Override 
// onCreate() is only run when the database file did not exist and was just created    
 public void onCreate(SQLiteDatabase db)
    {
        db.execSQL("CREATE TABLE Persons( PersonID INTEGER PRIMARY KEY AUTOINCREMENT,FirstName TEXT, Age INT)");
    }

    @Override 
//    onUpgrade() is only called when the database file exists but the stored version number is lower than requested in //constructor.    
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}


DBOperations.java

public class DBOperations {
  
    SQLiteOpenHelper sql_helper;
  
    DBOperations(Context context){  
        sql_helper=new sqllitehelperclass(context);
        //Downcasting SQLiteOpenHelper instance with the user defined class "SQLiteOpenHelperclass"
    }
  
    void create_table(){
        sql_helper.getWritableDatabase().execSQL("CREATE TABLE Persons( PersonID INTEGER PRIMARY KEY AUTOINCREMENT,FirstName TEXT, Age INT)");      
        Log.d("db","New db created");
        sql_helper.getWritableDatabase().close();
    }
  
    void delete_table(){
        sql_helper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS Persons");  
        Log.i("db", "database deleted");
        sql_helper.getWritableDatabase().close();
    }

    void insert(){
   //     sql_helper.getWritableDatabase().rawQuery("INSERT INTO Persons (FirstName,Age) VALUES ('Deepak','100');", null);


sql_helper.getWritableDatabase().execSQL("INSERT INTO Persons (FirstName,Age) VALUES ('Deepak','100');");
        sql_helper.getWritableDatabase().close();
    }
  
    List<persons> db_getall_data()
    {  
        int record_count;
        List<persons> query_res=new ArrayList<persons>();

        String[] args={"5P"};
        Cursor resultSet=sql_helper.getReadableDatabase().rawQuery("SELECT * FROM Persons", args);
        Log.d("db", "No of Records present="+String.valueOf(resultSet.getCount()));
        record_count=resultSet.getCount();
        resultSet.moveToFirst();
       
        if(record_count>0){
            while (record_count!=0)
            {
                persons Persons=new persons();
                Persons.put_age(resultSet.getInt(resultSet.getColumnIndex("Age")));
                Persons.put_name(resultSet.getString(resultSet.getColumnIndex("FirstName")));
                query_res.add(Persons);  
                resultSet.moveToNext();
                record_count=record_count-1;
            }
        }      
        sql_helper.getReadableDatabase().close();
        return query_res;
    }
  
  
    public boolean isTableExists()
    {
        try{
            Cursor cursor = sql_helper.getReadableDatabase().rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+"Persons"+"'", null);
            Log.d("DB","rows="+cursor.getCount());
            cursor.close();
        }catch(Exception e){
            sql_helper.getReadableDatabase().close();
            Log.d("Db","Table does not exist ");
            return false;
        }
       
        sql_helper.getReadableDatabase().close();
       return true;
    }
  
  }


person.java

public class persons {
   
    int age;
    String name;
   
    int get_age(){
        return age;
    }
   
    String get_name(){
        return this.name;
       
    }
   
    void put_name(String name){
        this.name=name;
       
    }
   
    void put_age(int age){
        this.age=age;
    }
}
 


Tuesday, January 6, 2015

Android : To Animate a picture file

To Animate a picture file


1.Create a new folder "anim" inside res folder
2.Goto folder res\anim and rt ck , select "Android XML File"
3.Give a resource ="Tween Animation" and File name="rotator" , root element ="rotate"
4.Open rotator.xml , delete all its contents and copy paste the below code inside :
************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:interpolator="@android:anim/linear_interpolator" >

    <!-- Use startOffset to give delay between animations -->


    <!-- Move -->
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromXDelta="0%p"
        android:startOffset="300"
        android:toXDelta="75%p" />
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromYDelta="0%p"
        android:startOffset="1100"
        android:toYDelta="70%p" />
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromXDelta="0%p"
        android:startOffset="1900"
        android:toXDelta="-75%p" />
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromYDelta="0%p"
        android:startOffset="2700"
        android:toYDelta="-70%p" />

    <!-- Rotate 360 degrees -->
    <rotate
        android:duration="1000"
        android:fromDegrees="0"
        android:interpolator="@android:anim/cycle_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:startOffset="3000"
        android:repeatCount="infinite"
        android:repeatMode="restart"
        android:toDegrees="360" />

</set>

***************************************************************************

5.Click next ...next and Finish
6.Copy paste method in your MainActivity

        public void rotateit(View v){
        final ImageView myImage = (ImageView)findViewById(R.id.imageView2);
                final Animation myRotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotator);
                myImage.startAnimation(myRotation);
    }

7.Copy Paste any image inside your res/drawable-hdpi
8.Goto layout xml (ex: layout/activity_main.xml)
9.Select tab - Graphical Layout
10.Drag and Drop Image View  , Select the the image you pasted in "res/drawable-hdpi"
11. Select the image ,goto properties
12.Make On Click ="rotateit"
13.Save and Run



more animations in http://www.androidhive.info/2013/06/android-working-with-xml-animations/

Monday, January 5, 2015

Android: Gif animations part 2

Gif animations part 2

1.Addthis in your Manifest file inside activity "android:hardwareAccelerated="false"
Example :
        <activity
                    android:hardwareAccelerated="false"
                    android:name="foo.GifActivity"
                    android:label="The state of computer animation 2014">
        </activity>

2.Code for Main_Activity

        public class GifActivity extends Activity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(new GifView(this));
            }
       
            static class GifView extends View {
                Movie movie;
       
                GifView(Context context)
                {
                    super(context);
                    movie = Movie.decodeStream(context.getResources().openRawResource(R.drawable.some_gif));
                }
                              
                // inHeriting onDraw of View Class
                @Override
                protected void onDraw(Canvas canvas) {  
                    if (movie != null) {
                        movie.setTime((int) SystemClock.uptimeMillis() % movie.duration());
                        canvas.scale((this.getWidth()/movie.width()), (this.getHeight()/movie.height()));// Size
                        movie.draw(canvas, 0, 0);//Location
                        invalidate();
                    }
                }
            }
        }

       
3.Paste the gif file in "res/hdpi or res/xhdpi"
4.Run the Code

Android:Creating Gif Animation in Android

Creating Gif Animation in Android


1. Create a new Android Project.
2. Add the below code in your Main_activity

//******************Main_activity*************************
public class Your_Class extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Gif_loading_View view = new Gif_loading_View(this);
        setContentView(view);
    }

}

//Adding the webView
public class Gif_loading_View extends WebView{

    public Gif_loading_View(Context context) {

        super(context);    
        loadUrl("file:///android_asset/loading_position.html");

        }
}
//**************************************************************


3.Create a file "loading_position.html" and add the below code inside and svae it.

<html>
<body bgcolor="white">
    <table width="100%" height="100%">
        <tr>
            <td align="center" valign="center">               
                <br/>
                <br/>
                <br/>
                <font size="6">Please wait...</font>
                <br/>
                <br/>
                <img src="your_gif_filename.gif" />

            </td>
        </tr>
    </table>
</body>

4. Copy paste the html file inside "assets" folder in your project.
5. Copy paste any gif file from the internet and rename it as "your_gif_filename"
6. Paste it inside the same assets folder
7.Run the project

Saturday, November 15, 2014

Android : Cannot resolve android (Android Studio error)

Cannot resolve android  (Android Studio error)


Make sure you have Andoid SDK in your system :

1- press ctrl+alt+shift+s
2-in the Modules bar click on your project name
3-change the compile sdk version to the newest one
4-click apply and ok then sync your project
5-done , i hope the best for you

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>