Tuesday 26 July 2011

Article About Avoiding Memory Leaks in Android


Android applications are, at least on the T-Mobile G1, limited to 16 MB of heap. It's both a lot of memory for a phone and yet very little for what some developers want to achieve. Even if you do not plan on using all of this memory, you should use as little as possible to let other applications run without getting them killed. The more applications Android can keep in memory, the faster it will be for the user to switch between his apps. As part of my job, I ran into memory leaks issues in Android applications and they are most of the time due to the same mistake: keeping a long-lived reference to a Context.


On Android, a Context is used for many operations but mostly to load and access resources. This is why all the widgets receive a Context parameter in their constructor. In a regular Android application, you usually have two kinds of Context, Activity  and  Application. It's usually the first one that the developer passes to classes and methods that need a Context:
Lets’ See Some Code First:
@Override
protected void onCreate(Bundle state) {
 
super.onCreate(state);
 
 
TextView label = new TextView(this);
  label
.setText("Leaks are bad");
 
  setContentView
(label);
}
This is Simple Activity in Which we Display Text in Screen
This means that views have a reference to the entire activity and therefore to anything your activity is holding onto; usually the entire View hierarchy and all its resources. Therefore, if you leak the Context ("leak" meaning you keep a reference to it thus preventing the GC from collecting it), you leak a lot of memory. Leaking an entire activity can be really easy if you're not careful.
Now Let’s Think About Below Thing
When the screen orientation changes the system will, by default, destroy the current activity and create a new one while preserving its state. In doing so, Android will reload the application's UI from the resources. Now imagine you wrote an application with a large bitmap that you don't want to load on every rotation. The easiest way to keep it around and not having to reload it on every rotation is to keep in a static field:
private static Drawable sBackground;
 
@Override
protected void onCreate(Bundle state) {
  super.onCreate(state);
 
  TextView label = new TextView(this);
  label.setText("Leaks are bad");
 
  if (sBackground == null) {
    sBackground = getDrawable(R.drawable.large_bitmap);
  }
  label.setBackgroundDrawable(sBackground);
 
  setContentView(label);
}
This code is very fast and also very wrong; it leaks the first activity created upon the first screen orientation change. When a Drawable is attached to a view, the view is set as acallback on the drawable. In the code snippet above, this means the drawable has a reference to the TextView which itself has a reference to the activity (the Context) which in turns has references to pretty much anything (depending on your code.)
This example is one of the simplest cases of leaking the Context and you can see how we worked around it in the Home screen's source code (look for theunbindDrawables() method) by setting the stored drawables' callbacks to null when the activity is destroyed. Interestingly enough, there are cases where you can create a chain of leaked contexts, and they are bad. They make you run out of memory rather quickly.
There are two easy ways to avoid context-related memory leaks. The most obvious one is to avoid escaping the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. The second solution is to use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().
In summary, to avoid context-related memory leaks, remember the following:
  • Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
  • Try using the context-application instead of a context-activity
  • Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance
  • A garbage collector is not an insurance against memory leaks

Wednesday 20 July 2011

Awesome Android Phone Secret Codes

DISCLAIMER: This information is intended for experienced users. It is not intended for basic users, hackers, or mobile thieves. Please do not try any of following methods if you are not familiar with mobile phones. We'll not be responsible for the use or misuse of this information, including loss of data or hardware damage. So use it at your own risk.

Awesome Android Phone Secret Codes:

had listed some secret codes of Android phone, these information will be more helpful for you, for using this you should need the Android software. The following are the secret codes...

This code can be used to get some interesting information about your phone and battery. It shows following 4 menus on screen:                                                                                                                                   

  • Phone information
  • Battery information
  • Battery history
  • Usage statistics

Android Phone Information Secret Code: *#*#4636#*#*

To get the information of your phone and battery. including Phone information, Battery information, Battery history, and Usage statistics.



Android Phone Reset Secret Code: *#*#7780#*#*


To reset your Android phone back to factory data. It will delete the things including Google account settings stored in your phone, System and application data and settings, and Downloaded applications too. I wont delete, including current system software, bundled applications, SD card files e.g. photos, music files.




This code can be used for a factory data reset. It'll remove following things:
  • Google account settings stored in your phone
  • System and application data and settings
  • Downloaded applications
It'll NOT remove:
  • Current system software and bundled applications
  • SD card files e.g. photos, music files, etc.
PS: Once you give this code, you get a prompt screen asking you to click on "Reset phone" button. So you get a chance to cancel your operation.



Android Phone Factory Format Secret Code: *2767*3855#


It is used for factory format, which will delete all files and settings, including the internal memory storage. It will also reinstall the firmware.




PS: Once you give this code, there is no way to cancel the operation unless you remove the battery from the phone. So think twice before giving this code.

Android Phone Camera Information Secret Code: *#*#34971539#*#*


It is used to get information about the camera. It includes following 4 menus: Update camera firmware in image, Update camera firmware in SD card, Get camera firmware version, and Get firmware update count. You should never use the first option otherwise your phone camera may stop working, and there is really no reason to update the camera firmware anyway.




WARNING: Never use the first option otherwise your phone camera will stop working and you'll need to take your phone to service center to reinstall camera firmware.

Android Phone Secret Code: *#*#7594#*#*


It will change the "End Call / Power" button action on your phone. By default, if you long press the button, it shows a screen asking you to select any option from Silent mode, Airplane mode and Power off. You can change this action using this code. You can enable direct power off on this button so you don't need to waste your time in selecting the option.

Android Phone Backup Secret Code: *#*#273283*255*663282*#*#*


It opens a File copy screen where you can backup your media files e.g. Images, Sound, Video and Voice memo.

Android Phone Service mode Secret Code: *#*#197328640#*#*


It can be used to enter into Service mode. You can run various tests and change settings in the service mode.

Android Phone WLAN, GPS and Bluetooth Test Secret Codes:


*#*#232339#*#* OR *#*#526#*#* OR *#*#528#*#* ¨C WLAN test (Use "Menu" button to start various tests)

*#*#232338#*#* ¨C Shows WiFi MAC address

*#*#1472365#*#* ¨C GPS test

*#*#1575#*#* ¨C Another GPS test

*#*#232331#*#* ¨C Bluetooth test

*#*#232337#*# ¨C Shows Bluetooth device address

Android Phone GTalk Secret Codes: *#*#8255#*#*


It can be used to launch GTalk Service Monitor.

Android Phone Firmware version information Secret Codes:


*#*#4986*2650468#*#* ¨C PDA, Phone, H/W, RFCallDate

*#*#1234#*#* ¨C PDA and Phone

*#*#1111#*#* ¨C FTA SW Version

*#*#2222#*#* ¨C FTA HW Version

*#*#44336#*#* - PDA, Phone, CSC, Build Time, Changelist number

Android Phone Factory Tests Secret Codes:


*#*#0283#*#* ¨C Packet Loopback

*#*#0*#*#* ¨C LCD test

*#*#0673#*#* OR *#*#0289#*#* ¨C Melody test

*#*#0842#*#* ¨C Device test (Vibration test and BackLight test)

*#*#2663#*#* ¨C Touch screen version

*#*#2664#*#* ¨C Touch screen test

*#*#0588#*#* ¨C Proximity sensor test

*#*#3264#*#* ¨C RAM version


NOTE: All above codes have been checked on Google Android phone Samsung Galaxy I7500 only but they should also work in other Google Android phones.

Wednesday 13 July 2011

How to Hide Soft Key Board Manually in Android

If you want to hide Force fully Soft Keyboard that open from any Edit Text in android than you can use following code to do .

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
mm.hideSoftInputFromWindow(edit_text.getWindowToken(), 0);

here edit_text is EdiText object from android android.widget.EditText .

Wednesday 6 July 2011

Simple ListView with ListActivity in Android


Android and Lists

Here is the tutorial for how to make ListView using ListView Activity in android.
Let's Discuss About what we can achieve using ListView Activity in android.
      You can directly use the "ListView" in your layout as any other UI component. In case your Activity is primary showing a list you can extend the activity "ListActivity" which simplifies the handling of a "ListView". "ListActivity" extends "Activity" and provides simplified handling of lists. For example you have a predefine method if someone clicks on a list element.

"ListActivity" contains a "ListAdapter" which is responsible for managing the data. This adapter must be set in the onCreate() method of your Activity via the method setListAdapter().
If the user select in the list a list entry the method onListItemClick() will be called. This method allows to access the selected element.
Android provides already some default layouts which you can use in your Adapter, e.g. "android.R.layout.simple_list_item1". In case you don't want to use one of the pre-defined layouts your own layout must have an element with the id "@android:id/list" which is the ListView. You can also use a view with the id "@android:id/empty". This view is displayed if the list is empty. For example you could display here an error message.

ListViews and performance:
Showing a big dataset must be with efficiency implemented on a mobile device. Therefore the ListView solitary creates views (widget) if needed and attach them to the view hierarchy. The default Adapter implementation for a ListView will recycle views, e.g. if a row is not displayed anymore it will be recycled and only its content will change. If you implement your own adapter for a view you also should do this to avoid performance problems.

Let's Begin
For the simple ListView we don't require to put <ListView/> in activity so here is the code for main Activity.


public class SimpleListActivityActivity extends ListActivity {

/** Called when the activity is first created. */
/** When we are using ListActivity we don't need to find the ListView in xml by Id*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
this.setListAdapter(new ArrayAdapter<String>(SimpleListActivityActivity.this, android.R.layout.simple_list_item_1, COUNTRIES));
}
String[] COUNTRIES = new String[] {
"Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
"Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
"Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
"Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
"Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
"Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
"British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
"Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
"Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
"Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
"Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
"Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
"East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
"Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
"Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
"French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
"Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
"Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
"Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
"Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
"Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
"Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
"Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
"Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
"Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
"Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
"Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
"Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
"Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
"Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
"Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
"Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
"Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
"Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
"The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
"Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
"Ukraine", "United Arab Emirates", "United Kingdom",
"United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
"Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
"Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
};

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
    Object o=this.getListAdapter().getItem(position);
    String name=o.toString();
    Toast.makeText(SimpleListActivityActivity.this, name, 2000).show();
  }
}

here is the screen which you will get from Android AVD:




For any thing missing and if you use eclipse than press ctrl+shift+O it will automatic import require java classes from android.

Tuesday 5 July 2011

How to Get Your Eclipse-Integrated NDK On Here are the few steps


Sooner or future in your Android game development attempt you may find the need to have some code that runs faster. It turns out that Android code written in C runs 10-100 times as fast as its Java counterpart. I can verify this, as I've already moved a few major components in my newest 3D game engine into native land. That's quite a boost but let's face it - C is a pain in the ass and while Eclipse is great for Java, it's not for C, right? Wrong. 

Here's how to set up a super speedy NDK development environment.
First of all, Eclipse can do way more than just Java. Java is what it's great at and what it was designed for but the architecture makes it so that it can handle any language effectively, including C. There is a component called CDT that allows for C/C++ Development in Eclipse. I'm getting ahead of myself, though. Here's what you need:





If you're in Windows, you'll need Cygwin with the develop packages installed (Especially GCC and Make)


Here's what you need to do:
Install all 3 of those things. I like to install my NDK to c:\Android_NDK. I'll refer to that dir for the rest of this article.
Get acquainted with the NDK. You need to configure each project as an "app" in the c:\Android_NDK\apps dir. Just take a look at the examples. They work and are thorough.
How to test your NDK:
Run cygwin
cd /cygdrive/c/Android_NDK
make APP=hello-jni


It should roll up without errors. If you are lacking GCC or Make or any other develop packages, you will want to run your Cygwin setup again and check to make sure that all of the development packages are installed. If you have strange errors, I suggest reporting them in the NDK user's group.
Once your NDK is running, you can add an app for your project and set up the basic native framework for your project. Please refer to the examples for this part. You will need a specific build file that tells the compiler what sources to compile. JNI code is usually located in your Android project's jni folder. A file called Android.mk will need to be in there which instructs the compiler on what to compile.
After you get the basic configuration done, you will want to start writing some C. NDK uses Java's standard JNI bindings to work. All of the existing documentation on JNI should apply from this point forward. What to code is beyond the scope of this article.


Now for the good part :
If you've done any NDK work, you're probably used to using a text editor or vim or some other editor to edit your C/CPP then running make APP=myapp every time to build, then clicking refresh on your project in Eclipse and then hoping that the shared object library file that gets deployed is current. What a pain in the ass! There's a much, much better way.
Now that you have CDT installed, you can edit all of your C/C++ right from Eclipse. If you right click on a C/CPP source file, just pick Open With--C/C++ Editor and it will use the CDT editor. Much nicer! It won't be able to figure out what the code is doing because it's not compiling it, but it will make editing nice and all in one spot.
Building is a snap as well. Ever used builders in Eclipse? They are configurable triggers that will execute what you configure and refresh resources for you. Make sure you know if you're on the old r3 NDK (upgrade if you are - you should be on r4) and if so, I put different instructions in this list for the different versions. Here's how I set mine up:



Right click on your project, pick properties.
Select "builders" from the left-hand list.
Click "New..." on the right side.
Select "Program" as the configuration type.
I name mine "Native Builder"
Location - c:\cygwin\bin\bash.exe
Working Directory - c:\cygwin\bin
Arguments -
(for NDK r3):
--login -c "cd /cygdrive/c/Android_NDK && make APP=myapp"
(for NDK r4):
--login -c "cd /cygdrive/c/<myapp_project_dir> && /cygdrive/c/Android_NDK/ndk-build"
Make sure you have the two hyphens before login and the quotes after the hyphen-c
Now go to the refresh tab
Check "Refresh resources upon completion"
Select "Specific resources"
Click on the "Specify resources" button and select your project's lib directory.
Check "Recursively include sub-folders"
Now go to the build options tab
Check "Allocate Console"
Check "Launch in background"
Check "Run the builder After a Clean"
Check "Run the builder During manual builds"
Check "Run the builder During auto builds"
Check "Specify working set of relevant resources"
Click on "Specify Resources"
Select your project's JNI directory and all files within.
Now click OK on the bottom.
The assumption here is that cygwin is installed to c:\cygwin, NDK is in c:\Android_NDK and your project is called "myapp". Change where appropriate.
What did you just do?! You made it so that any time you edit any files within your JNI directory and you save them, Eclipse will run the NDK Builder for you via CygwinADT to compile a new APK for you and YOU ARE GOOD TO GO!
This gravely fasted me up while working on my current project. I hope you can all benefit from it!

Simple Android Animation Application

Here is the example for simple android animation using <animation-list/> in  Drawable Folder in android.

Here is the java code for Simple Animation
<!----------------------------    --------------------------------------------->

public class AnimationSimpleActivity extends Activity {
    ImageView mImageView;
    
    private AnimationDrawable introDrawable;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mImageView=(ImageView)findViewById(R.id.animation);
        mImageView.setBackgroundResource(R.drawable.myanimation);
        introDrawable=(AnimationDrawable)mImageView.getBackground();
        mImageView.post(new Animator());
    }
    private long starttime,endtime;
    private class Animator implements Runnable {

    public void run() {
starttime=System.currentTimeMillis();
introDrawable.start();
Timer mTimer=new Timer();
mTimer.schedule(new ActivityChanger(), 3000);
}
}
    
    public class ActivityChanger extends TimerTask{


@Override
public void run() {
endtime = System.currentTimeMillis();
if(endtime-starttime >=1800){
AnimationSimpleActivity.this.finish();
Intent mIntent=new Intent(AnimationSimpleActivity.this, Activity2.class);
startActivity(mIntent);
}
}
   
    }

}

Below is the xml file for animation-list res/drawable/myanimation.xml


<?xml version="1.0" encoding="utf-8"?>
<animation-list
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:oneshot="true">
 <item  android:drawable="@drawable/f1" android:duration="200"/>
 <item  android:drawable="@drawable/f2" android:duration="200"/>
 <item  android:drawable="@drawable/f3" android:duration="200"/>
 <item  android:drawable="@drawable/f4" android:duration="200"/>
 <item  android:drawable="@drawable/f5" android:duration="200"/>
 <item  android:drawable="@drawable/f6" android:duration="200"/>
 <item  android:drawable="@drawable/f7" android:duration="200"/>
 <item  android:drawable="@drawable/f8" android:duration="200"/>
 <item  android:drawable="@drawable/f9" android:duration="200"/>  
   
</animation-list>

Here is the output: