Archive
Taking a screenshot of current Activity in Android
In this post I’ll show how you can take a screenshot of your current Activity and save the resulting image on /sdcard.
The idea behind taking a screenshot actually is pretty simple: what we need to do is to get a reference of the root view and generate a bitmap copy of this view.
Considering that we want to take the screenshot when a button is clicked, the code will look like this:
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
First of all we should retrieve the topmost view in the current view hierarchy, then enable the drawing cache, and after that call getDrawingCache().
Calling getDrawingCache(); will return the bitmap representing the view or null if cache is disabled, that’s why setDrawingCacheEnabled(true); should be set to true prior invoking getDrawingCache().
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
And the method that saves the bitmap image to external storage:
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
Since the image is saved on external storage, the WRITE_EXTERNAL_STORAGE permission should be added AndroidManifest to file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Using Custom Fonts in Android
By default Android comes with three standard fonts: Droid Sans (default font), Droid Serif, and Droid Sans Mono. They all can be applied to any view that supports styling, such as TextView, Button, by specifying the “android:typeface” attribute in the XML declaration with any of these values: sans, serif, monospace.
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sans" android:typeface="sans" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Serif" android:typeface="serif" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Monospace" android:typeface="monospace" />
Using custom fonts in Android is pretty straightforward. First find a free font and put it in the assets/fonts directory. (It’s not mandatory to have a /fonts directory, but if I have a lot of stuff in the /assets directory I organize them in separate directories). Then get a reference to your TextView and create a Typeface object specifying the font path. Lastly, apply the typeface to the TextView.
In this particular example I used the font: christmaseve.ttf
TextView textView = (TextView) findViewById(R.id.textView); Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/christmaseve.ttf"); textView.setTypeface(tf);
RuntimeException: Native typeface cannot be made
If you get this exception while trying to integrate the custom font into your application, make sure the path to the font file is correct, and the font name is spelled correctly. I noticed I was getting this exception when my font path was misspelled, for example writing “.tff” instead of “.ttf”, or forgetting to add the “fonts/” prefix to the path.
Custom font used in this example provided by: http://bythebutterfly.com
Integrating Google Analytics SDK (V2) with Android
The Google Analytics SDK for Android makes it easy for developers to collect valuable statics about how the users are using their app.
Here are some features that Android Google Analytics SDK offers:
- The number of active users that are using the application
- Usage of specific features
- The number and type of application crashes
- From where in the world the application is used
- And many other useful metrics.
Just to illustrate the integration process lets create a simple proof of concept application with 2 activities: MainActivity and AboutActivity, and 2 buttons: Rate and Share.
Our mission is to integrate Google Analytics SDK with the application, to:
- track activity views, (MainActivity and About)
- track events (how many times the buttons “Rate”, and “Share” are clicked)
If you are searching for Google Analytics I’m assuming you are already pretty familiar with Android and could create the proof of concept application yourself, so I will skip this step and concentrate solely on integration.
1. Downloading the SDK
Go to downloads page and download GoogleAnalyticsAndroid.zip Version 2.0. Extract the archive and add libGoogleAnalyticsV2.jar to your project’s /libs directory.
At the moment of writing this post, Google provides two versions: version 1.5.1 (legacy), and version 2.0 beta. Still if the Version 2 of SDK is beta, I highly suggest you choose this version, over the 1.5.1 (legacy).
The reason not to choose SDK 1.5.1 is that it uses a tracking model that is designed to track visitors to traditional websites and interaction with widgets in traditional web pages.
The new “App” profiles and reports will only accept data from version 2 or higher of the SDK.
2. Creating a Google Analytics account
Before starting to use the SDK you first must create an account at: http://www.google.com/analytics/
- Sign in to your account.
- Click Admin.
- Click Account list (just below the menu bar)
- Click +New Account
- When asked what you would like to track, select App property.

- Enter all the necessary information and click Get Tracking ID.
Now that you have a Tracking ID, you can begin the integration with the application. The first step is to update the AndroidManifest file.
3. Updating AndroidManifest file.
Add folowing permissions to the AndroidManifest file:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
4. Creating the analytics.xml file
In version 2 of Google Analytics SDK for Android, the tracking settings are managed from an xml resource file called: analytics.xml. You will need to create this file in res/values directory, and add your tracking ID as well as other settings here.
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- Replace placeholder ID with your tracking ID --> <string name="ga_trackingId">UA-00000000-0</string> <!-- Enable Activity tracking --> <bool name="ga_autoActivityTracking">true</bool> <!-- Enable debug --> <bool name="ga_debug">true</bool> <!-- The screen names that will appear in your reporting --> <string name="com.testgoogleanalytics.MainActivity">MainActivity</string> <string name="com.testgoogleanalytics.About">About</string> <!-- The inverval of time after all the collected data should be sent to the server, in seconds. --> <integer name="ga_dispatchPeriod">30</integer> </resources>
5. Tracking activities.
To track activities add the tracking methods to the onStart() and onStop() of each of your activities.
// Example of tracking MainActivity
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this); // Add this method
}
@Override
protected void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this); // Add this method
}
}
One thing to note here is that EasyTraker requires a context before you can use it. If you attempt to call any of its methods but did not pass first a context, you may end up with an IllegalStateException.
In the above example, in the onStart() and onStop() methods the context is passed as an argument to activityStart() and activityStop(), but if you need to make EasyTracker calls in other classes or methods, you’ll need to call EasyTracker’s setContext(Context context) method first:
Context context= this; // Get current context. EasyTracker.getInstance().setContext(context); // Set context // EasyTracker is now ready for use.
6. Tracking events
Tracking events is just as easy as tracking activities, you just need a Tracker object and call the trackEvent(String category, String action, String label, int value) method.
public class MainActivity extends Activity {
private Tracker tracker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set context
EasyTracker.getInstance().setContext(getApplicationContext());
// Instantiate the Tracker
tracker = EasyTracker.getTracker();
// Add tracking functionality to "Rate" button
Button rate = (Button) findViewById(R.id.rate);
rate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// The rest of your code
tracker.trackEvent("Buttons Category", "Rate", "", 0L);
}
});
// Add tracking functionality to "Share" button....
}
}
In this particular example I don’t need a label nor a value, that is why I set for the last 2 parameters of trackEvent() method, an empty string a 0 (zero), but depending of your needs you may populate them with some data.
7. Debugging
Debugging helps you deal with troubleshooting, and make you sure that the data actually is sent to the server. To set the Google Analytics in debug mode, add the following setting in the analytics.xml
<bool name="ga_debug">true</bool>
Once your are in debug mode, you can watch the log information in LogCat:
Waiting for the big moment!
If everything is configured correctly, the reports should appear on live. Usually it takes about 24 hours to see the data in your account.
What happens if my application is used when no network is available?
Just in case you asked this yourself…, all the events are persisted in a local storage, and they will be sent the next time your app is running and dispatch is called.
Last but not least
One important thing not to be forgotten: you must indicate to your users, either in the application itself or in your terms of service, that you reserve the right to anonymously track and report a user’s activity inside of your app.
Android Google Analytics SDK offers more than tracking activities and events, see: https://developers.google.com/analytics/devguides/collection/android/v2/ to get the most out of it.
Please visit the Android Tutorials page for more tutorials.
Android Asset Studio – The easiest way to create icons for your android apps!
Android Asset Studio is an online utility that lets you generate all kind of icons you may need for your android applications, starting with launcher icons, action bar and tab icons, notification icons, and menu icons. It even includes a simple 9-patch generator allowing you to create 9-patch images.
One of the trickier parts when creating the icons is that you should create them for all kinds of resolutions: ldpi, mdpi, hdpi, and xhdpi. With Android Asset Studio this is as simple as uploading an image. The tool generates automatically for you all the versions of the icon under all resolutions, and make them available as a downloadable zip archive.
The icons may be generated from an image uploaded, or from a clipart library, or from text. It’s a very convenient tool and I highly recommend using it if you want to have professional, good looking icons on all resolutions.
Android – [APP] Amazing Drunk Detection Scanner
Ready to go to party? Then don’t forget to put Amazing Drunk Detection Scanner in your pocket!
Drunk Detection Scanner is a simple application that helps you make fun with your friends. Make fun of your best friends by scanning their eye, and determine how drunk are they!
Here is how the prank works:
1. Just in the middle of the party open the Drunk Detection Scanner and say something like “Alright gentlemen, time to do some analysis!”
2. Invite one of your friends and tell him that this app will reveal how drunk he is.
3. Aim the camera close to your friend’s eye
4. Focus
5. Press “Start Scanning”
6. Wait till the result is calculated
7. Have fun!
DISCLAIMER:
Amazing Drunk Detection Scanner is a simple application designed for entertainment purposes only. It does not encourage the consumption of alcohol, and it does not take any legal responsibility.
GAG Pictures – Have Fun! Spread The Fun!
Hello everyone, I would like to introduce you my second Android application published on Google Play – GAG Pictures. Compared with the first one, this application is intended to bring you much fun.
GAG Pictures is your daily set of funny images! Every time the application is launched it downloads a set of new funny images from the famous site 9gag.com. Every image has a Share button so you can share that hilarious image with your friends. The current version allows you to share only the direct link to image, but in the upcoming releases the ability to send the image itself will be provided.
Have fun!
Drawing Shapes in Android
In this post I would like to share my findings about defining and using shapes. A shape is an XML file that defines a geometric shape, including strokes, colors and gradients
To define a shape:
1. Create a new Android XML file in the folder res/drawable
2. Make sure the root element of the file is <shape >. (If it’s not, then change it manually)
3. Inside the <shape> element, press CTRL + Space to reveal all the available elements you can use to define a shape:
As you can see, the elements are pretty self explanatory. To reveal the attributes of an element, put the cursor inside that element and press CTRL + Space:
4. Once the shape is defined, you can specify it as a background resource to any view: android:background=”@drawable/myshape”
res/drawable/boxbg.xml:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <stroke android:width="2dp" android:color="#FFFFFF" /> <corners android:radius="5dp" /> <gradient android:angle="270" android:centerColor="#6E7FFF" android:endColor="#142FFC" android:startColor="#BAC2FF" /> </shape>
res/drawable/box2bg.xml:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="#4D9611" /> <stroke android:width="4dp" android:color="#FFFB00" /> </shape>
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- First box, boxbg.xml -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_margin="20dp"
android:background="@drawable/boxbg"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textColor="#000"
android:textSize="20dp" />
</LinearLayout>
<!-- Second box, box2bg.xml -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_margin="20dp"
android:background="@drawable/box2bg"
android:orientation="vertical"
android:padding="7dp" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textColor="#FFF"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
The final output should look like this:
Defining Global Variables in Android
At some point in your development process you may need to have several variables across application.
In this post I want to describe 2 ways through you can define global variables in Android: using a singleton class, and by extending the Android’s Application class.
One of the simplest ways (it does not mean that is one of the best) to have global variables is to declare a singleton class:
public class Globals{
private static Globals instance;
// Global variable
private int data;
// Restrict the constructor from being instantiated
private Globals(){}
public void setData(int d){
this.data=d;
}
public int getData(){
return this.data;
}
public static synchronized Globals getInstance(){
if(instance==null){
instance=new Globals();
}
return instance;
}
}
To use this class you get an instance first, and then do what you want with data:
Globals g = Globals.getInstance(); g.setData(100); .... int data=g.getData();
Notice that we do not instantiate the object by calling “new”, in fact this wouldn’t be allowed as we declared the constructor private, so its not visible. Instead we call the getInstance() method and return our static object.
The second way to define global variables is by extending the Application class. This is the base class for maintaining global application state.
a) Create a new class that extends Application.
public class Globals extends Application{
private int data=200;
public int getData(){
return this.data;
}
public void setData(int d){
this.data=d;
}
}
b) Add the class to the AndroidManifest file as an attribute of <application> tag:
<application android:name=".Globals" .... />
c) Then you can access your global data from any Activity by calling getApplication()
Globals g = (Globals)getApplication(); int data=g.getData();
I said that using the Singleton pattern it’s one of the simplest ways to define global variables, but I mentioned also that it does not mean that it’s one of the best ways to do it. In fact this is quite a controversial subject.
You may believe that when a static variable is initialized it stays so for the entire life of the application, however this does not seem to be true everytime. Sometimes, there are situations when some static variables bound to activities happens to be uninitialized even they have been initialized.
This makes the static singleton approach not one of the best for keeping global variables, though the official Android documentation seems to encourage using them: “There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way.”
Understanding AsyncTask – Once and Forever
This article describes the usage of AsyncTask class in Android.
Android modifies the user interface via one thread, the so called UI Thread. If you perform a long running operation directly on the UI Thread, for example downloading a file from the internet, the user interface of your application will “freeze” until the corresponding task is finished. When this happens it is very easy for the user to perceive your application as slow.
As a concrete example of a bad implementation and what happens when a long running operation is done on the UI Thread, I want to refer to one of my previous tutorials: Creating A Simple RSS Application in Android. Well, that application is working fine, and it does what it is supposed to do – parse an XML feed and display the headlines in a ListView. The “vulnerability” of that application is that the network access is done directly on the UI Thread which makes the application to “freeze” while the XML feed is downloaded (take a look at point number 5 to see).
When I created that tutorial I wanted to make it as simple as possible without dealing with more advanced topics like asynchronous tasks. The intent of tutorial was to show the working process with feeds on a high level. But I promise you, by the end of this article you will be able to fix it and have a Cool Rss App that runs smoothly!
To provide a good user experience all long running operations in an Android application should run asynchronously. To achieve this we will be using the AsyncTask class.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
In order to use the AsyncTask class, you must extend it and override at least the doInBackground() method.
The most common methods you will need to implement are these:
1. onPreExecute() – called on the UI thread before the thread starts running. This method is usually used to setup the task, for example by displaying a progress bar.
2. doInBackground(Params…) – this is the method that runs on the background thread. In this method you should put all the code you want the application to perform in background. Referring to our Simple RSS Aplication, you would put here the code that downloads the XML feed and does the parsing. The doInBackground() is called immediately after onPreExecute(). When it finishes, it sends the result to the onPostExecute().
3. onProgressUpdate() - called when you invoke publishProgress() in the doInBackground().
4. onPostExecute(Result) – called on the UI thread after the background thread finishes. It takes as parameter the result received from doInBackground().
AsyncTask is a generic class, it uses 3 types: AsyncTask<Params, Progress, Result>.
Params– the input. what you pass to the AsyncTaskProgress– if you have any updates, passed to onProgressUpdate()Result– the output. what returns doInBackground()
Once a task is created, it can be executed like this:
new DownloadTast().execute(url1, url2, urln);
This is a simple skeleton of an AsyncTask implementation.
public class AsyncTaskTestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Starting the task. Pass an url as the parameter.
new PostTask().execute("http://feeds.pcworld.com/pcworld/latestnews");
}
// The definition of our task class
private class PostTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
displayProgressBar("Downloading...");
}
@Override
protected String doInBackground(String... params) {
String url=params[0];
// Dummy code
for (int i = 0; i <= 100; i += 5) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return "All Done!";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
updateProgressBar(values[0]);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dismissProgressBar();
}
}
}
AsyncTasks are great for performing tasks in a separate thread, they have however one weakness. While the AsyncTask is in the middle of the work and the screen of device is rotated, you’ll notice that the application crashes. This happens because when rotating the device screen a configuration change occurs, which will trigger the Activity to restart. The AsyncTask reference to the Activity is invalid, an onPostExecute() will have no effect on the new Activity. How to handle this sort of issues is described in: Dealing with AsyncTask and Screen Orientation, which I highly recommend reading it if you are concerned to deliver stable Android applications.
How to simulate an incoming call in Android
1. Start the Android Emulator
2. Open up the windows console by going to Start -> Run (or Windows + R shortcut) and type in “cmd”. Press Enter. This should open the dos console.
3. Type in “telnet” and press enter. This should open the Telnet Console.
(At this stage you may experience some problems, the console may display the error: ‘telnet’ is not recognized as an internal or external command, operable program or batch file. If this is the case, scroll down to see how to fix it, then return and continue the process)
4. Telnet Console being displayed, type in “o localhost 5554″. This will establish a connection with the emulator on port 5554 and open the Android Console. 5554 is the port number and you can see it on the title bar of the emulator window.
5. To simulate the call, type in “gsm call 099062274″
6. To cancel the call, type “gsm cancel 099062274″
7. Use “exit” to exit the Android Console, and “quit” to quit the Telnet client.
That’s it!
*How to fix the: ‘telnet’ is not recognized as an internal or external command, operable program or batch file error.
When trying to invoke the telnet program you may experience the above error. The cause of this could be that the Telnet Client is turned off on your computer.
To turn it on, follow these steps:
1. Go to Control Panel
2. Click on Programs
3. Under Programs and Features section, click on Turn Windows features on or off. This should bring you the Windows Features pop-up.
4. Find the Telnet Client, select it, click OK.










![get_it_on_play_logo_large[1] Get it on Google Play - GAG Pictures](http://androidresearch.files.wordpress.com/2012/04/get_it_on_play_logo_large1.png?w=595)








