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.

android drunk detection scanner

Android – Scheduling an application to start later.

Recently I have been working on a simple application that should have the ability to start itself after a period of time, after the application is closed. Hopefully, it turned out that this is quite simple to implement, and to achieve this, the AlarmManager in conjuction with a BroadcastReceiver can be used.

The basic idea is as follows: the AlarmManger registers an intent, when the alarm goes off, the intent that had been registered automatically will start the target application if it is not already running. The BroadcastReceiver will be listening for that intent, and when the intent is received, it will start the desired activity from the application.

The broadcast receiver implementation looks like this:


public class OnAlarmReceive extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {

     Log.d(Globals.TAG, "BroadcastReceiver, in onReceive:");

     // Start the MainActivity
     Intent i = new Intent(context, MainActivity.class);
     i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     context.startActivity(i);
  }
}

Register the OnAlarmReceive in the AndroidManifest file:


<application
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name" >

   // ......

   <receiver
      android:name=".OnAlarmReceive" />

</application>

And finally, here’s how to setup the alarm:

/**
* Sets up the alarm
*
* @param seconds
*            - after how many seconds from now the alarm should go off
*/
private void setupAlarm(int seconds) {
  AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  Intent intent = new Intent(getBaseContext(), OnAlarmReceive.class);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(
     MainActivity.this, 0, intent,
     PendingIntent.FLAG_UPDATE_CURRENT);

  Log.d(Globals.TAG, "Setup the alarm");

  // Getting current time and add the seconds in it
  Calendar cal = Calendar.getInstance();
  cal.add(Calendar.SECOND, seconds);

  alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

  // Finish the currently running activity
  MainActivity.this.finish();
}

The last line from the code – finishing the current activity – is optional of course, but in case you need to finish the activity, here’s how to do.

For a live demo of the code, download the Amazing Cracked Screen application and see how it works. There you have the possibility to set up the delay in seconds when the application should start later and show the “broken” screen.

Amazing Cracked Screen

Hello everyone,

In this weekend I made a simple application just for fun – Amazing  Cracked Screen, the main purpose being to trick your friends and make fun of them! Basically, what does the application is to simulate a broken phone screen.
The application includes 6 different broken screens, and provides the ability to set up a delay time when the app should start, so you can manage to give the phone to your friend.

Just start the application, select the desired broken screen and have fun!

 

Amazing Cracked Screen

Creating and Displaying a Custom Dialog in Android

In this post I would like to describe the process of creating and displaying a custom dialog. Though the Android documentation describes pretty well the topic, I faced some problems implementing it, and I would like to share my findings.

The final output should look like this:

Android Custom Dialog

1. The first issue I have encountered was that I was getting a BadTokenException in the onCreateDialog() method where I was instantiating the Dialog: android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application, 

Context context=getApplicationContext();
Dialog dialog=new Dialog(context);

Well, though the Android documentation suggests to use getApplicationContext(); actually it turns out that this is not the proper way to do it and most likely it will throw an exception. The correct way is to use this, or “ActivityName”.this instead of getApplicationContext(). For example:

Context context=MainActivity.this;
Dialog dialog=new Dialog(context);

 

2. The second issue I was facing was that I wanted to get rid off the standard dialog title.
Normally you would set the Dialog title with this:

dialog.setTitle("Dialog Title");

However, if you don’t want to display a standard title for your dialog, not calling the above line most probably won’t meet your expectations, because it will leave an empty space where the title should be.

Hopefully, this is an easy fix. Just call requestWindowFeature(Window.FEATURE_NO_TITLE); and you are done.

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

 

To sum up with a concrete working example, below I presented an implementation of a simple custom dialog.

custom_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="250dp"
   android:layout_height="match_parent"
   android:background="#8F1A3B"
   android:orientation="vertical" >

<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_marginBottom="20dp"
   android:text="Custom Dialog"
   android:textSize="18dp" />

<Button
   android:id="@+id/restart"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Restart Game" />

</LinearLayout>

 

MainActivity:


public class MainActivity extends Activity {

Dialog dialog;
int DIALOG_GAME_RESTART=100;

@Override
public void onCreate(Bundle savedInstanceState) {
   // ............
}

@Override
protected Dialog onCreateDialog(int id) {
   switch (id) {
   case DIALOG_GAME_RESTART:
     Context context=MainActivity.this;
     dialog=new Dialog(context);
     dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

     dialog.setContentView(R.layout.custom_dialog);

     Button restart=(Button)dialog.findViewById(R.id.restart);

     restart.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
        dialog.dismiss();

        //whatever code you want to execute on restart
     }
     });
   break;

   default: break;
   }
   return dialog;
}
}

Writing and Reading from SharedPreferences

SharedPreferences class allows you to save and retrieve primitive data types in key-value pairs. The data saved using SharedPreferences will be available even after your application is killed. This capability makes SharedPreferences suitable in different situations when user settings needs to be saved for example, or store data that can be used in different activities.
The data types that can be saved are booleans, floats, ints, longs, and strings.

To get an instance of SharedPreferences use the getSharedPreferences(String, int) method. The method takes 2 parameters: the name of the preference settings and the mode. (0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions)

To write values:

  1. Call edit() to get a SharedPreferences.Editor instance
  2. Add values with methods such as putInt() and putString().
  3. Call commit() to save values.

To read values use such methods as getString() and getInt() of SharedPreferences instance.

Here’s a simple usage of SharedPreferences class:


public class SharedPrefsActivity extends Activity {

  public static final String PREFS_NAME = "MyApp_Settings";

  @Override
  public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

     // Writing data to SharedPreferences
     Editor editor = settings.edit();
     editor.putString("key", "some value");
     editor.commit();

     // Reading from SharedPreferences
     String value = settings.getString("key", "");
     Log.d(TAG, value);
  }
}

Please visit the Android Tutorials page for more tutorials.

How to verify an RSS Feed if New Articles have been published.

Recently I built an rss app for a site that publishes daily IT News – ITMoldova.com. The main feature of application is to launch a service in background (at a given interval of time), and check if new articles have been published on http://itmoldova.com site. If it turns out that new articles have been published, then fire a notification message and notify the user about this, something like this: “4 New Articles Published on ITMoldova.com”.

How to identify how many articles were published?

The mechanism to identify if new articles have been published on the site (and how many) is pretty straightforward: when the application is installed and launched for the first time, it parses the Rss Feed and creates a new entry in the SharedPreferences with the value of <pubDate> element, of the first item from the rss list (pubDate = publication date). Then, everytime the service starts, it parses the RSS Feed and checks the value of first item from the rss list against the value stored in SharedPreferences, if the value stored in SharedPreferences is less than value returned by the service, then it means that there are new articles and it’s time to notify the user! Lastly, update the SharedPreferences with the most recent pubDate.

For the sake of simplicity and keeping things consistent, I will post here only snippets of most relevant code, but this will be good enough to give you an idea about how things works.

How to compare two dates?

To compare the dates we need to convert them to milliseconds. The getTime() method of Date class can help us return the number of milliseconds of a given date:

Date date=new Date();
int timeMilliseconds=date.getTime();

 

Below is the implementation of verifyDates(String, String) method that will be used by the Service. The method takes 2 string parameters, the pubDate of rss item, and the pubDate stored in SharedPreferences.


public class Tools {
  public int newArticles;
  public boolean hasMoreArticles = true;

  public void verifyDates(String rssPubDate, String sharedPrefLastPubDate) {
    if (hasMoreArticles) {
      SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
      Date dLastPubDate = null;
      Date dRssPubDate = null;

      try {
        dLastPubDate = df.parse(sharedPrefLastPubDate.substring(5));
        dRssPubDate = df.parse(rssPubDate.substring(5));
      } catch (ParseException e) {
        Log.d("GREC", "Exception in verifayDates: " + e.getMessage());
        e.printStackTrace();
      }

      //We want to count how many new articles were published.
      if (dRssPubDate.getTime() > dLastPubDate.getTime()) {
        newArticles++;
      } else {
        hasMoreArticles = false;
      }
    }
  }

}
The Service Implementation

The service will parse the Rss Feed and do the comparison. Also, it will launch a status bar notification if it turns out that new articles were published.

public class RssService extends IntentService {

  public RssService() {
    super("ITMoldovaRssService");
  }

  @Override
  protected void onHandleIntent(Intent intent) {

    // Retrieve the date from SharedPreferences
    String lastPubDate = getDateFromSharedPrefs();

    // The AndroidFeedParser class helps us parse the Rss Feed.
    AndroidFeedParser parser;

    try {
      parser = new AndroidFeedParser(new URL("http://itmoldova.com/feed/"));
      List<Message> list = parser.parse();

      if (list != null) {
        for (int i = 0; i < list.size(); i++) {

          // Verify the pubDate of each item, against pubDate stored in SharedPreferences
          tools.verifyDates(list.get(i).getDate(), lastPubDate);
        }

        // Get the last pubDate and save it to SharedPreferences.
        lastPubDate = list.get(0).getDate();
        saveToSharedPreferences(lastPubDate);
      }
    } catch (MalformedURLException e) {
      Log.d("GREC", "Malformed URL Exception: " + e.getMessage());
      e.printStackTrace();
    }

    if (tools.newArticles > 0) {
      displayNotification();
    } else {
      Log.d("GREC", "No new articles ");
    }
  }
}

 

The service begins with parsing the Rss Feed and return the list of items:

List<Message> list = parser.parse();

then iterate through it comparing the publication date:

for (int i = 0; i < list.size(); i++) {
    // Verify the pubDate of each item, against pubDate stored in SharedPreferences
    tools.verifyDates(list.get(i).getDate(), lastPubDate);
}

and then ends getting the most recent publication date and saving it to SharedPreferences:

// Get the last pubDate and save it to SharedPreferences.
lastPubDate = list.get(0).getDate();
saveToSharedPreferences(lastPubDate);

If it turns out that new articles were published, display a status bar notification.

if (tools.newArticles > 0) {
displayNotification();
}

 

How to parse an XML feed and how to display a status bar notification are some helper topics you may need to take a look in order to fully complete this task.