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.

Advertisement

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

How to create popups in Android

In this post I’ll show you how to create a popup window in Android. A popup window can be used to display an arbitrary view, and it can be very convenient in cases when you want to display an additional information, but don’t want or it’s not appropriate to launch a new activity or  display a dialog.

The final output should look like this:

Android Popup

We will use the PopupWindow class to create the popup.

One thing I would like to mention is that we want the popup to be attached to the button that opened it. For example if the “Show Popup” button from the screenshot above would be positioned in the middle of the screen, we want the popup window stick to the button’s position. To achieve this, first we should get the button’s “x” and “y” position on the screen, and pass them to the popup window. Then will we use an offset to align the popup properly – a bit to the right, and a bit down, so it won’t overlap the whole button.

Another think I would like to mention is that we will use a 9 patch background image for the popup, so it will look more fancy. But of course you can skip it and put any background you want, or no background at all.

9 patch image:

9 patch image

Put the image into res/drawable directory.

 

1. Create a new project in Eclipse:
Project: TestPopup
Activity: TestPopupActivity

2. Open layout/main.xml file and add a button


<?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:background="#CCC"
android:orientation="vertical" >

<Button
   android:id="@+id/show_popup"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Show Popup" />

</LinearLayout>

3. Create a new layout file: layout/popup_layout.xml that defines the layout of popup.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:id="@+id/popup"
   android:layout_height="wrap_content"
   android:background="@drawable/popup_bg"
   android:orientation="vertical" >

<TextView
   android:id="@+id/textView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Popup"
   android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
   android:id="@+id/textView2"
   android:layout_marginTop="5dp"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="This is a simple popup" />

<Button
   android:id="@+id/close"
   android:layout_marginTop="10dp"
   android:layout_gravity="center_horizontal"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Close" />

</LinearLayout>

 

4. And now the most interesting part. Open the TestPopupActivity and fill it with below code. Carefully read the comments to understand what’s going on.


public class TestPopupActivity extends Activity {

//The "x" and "y" position of the "Show Button" on screen.
Point p;

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

   Button btn_show = (Button) findViewById(R.id.show_popup);
   btn_show.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View arg0) {

       //Open popup window
       if (p != null)
       showPopup(TestPopupActivity.this, p);
     }
   });
}

// Get the x and y position after the button is draw on screen
// (It's important to note that we can't get the position in the onCreate(),
// because at that stage most probably the view isn't drawn yet, so it will return (0, 0))
@Override
public void onWindowFocusChanged(boolean hasFocus) {

   int[] location = new int[2];
   Button button = (Button) findViewById(R.id.show_popup);

   // Get the x, y location and store it in the location[] array
   // location[0] = x, location[1] = y.
   button.getLocationOnScreen(location);

   //Initialize the Point with x, and y positions
   p = new Point();
   p.x = location[0];
   p.y = location[1];
}

// The method that displays the popup.
private void showPopup(final Activity context, Point p) {
   int popupWidth = 200;
   int popupHeight = 150;

   // Inflate the popup_layout.xml
   LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
   LayoutInflater layoutInflater = (LayoutInflater) context
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);

   // Creating the PopupWindow
   final PopupWindow popup = new PopupWindow(context);
   popup.setContentView(layout);
   popup.setWidth(popupWidth);
   popup.setHeight(popupHeight);
   popup.setFocusable(true);

   // Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
   int OFFSET_X = 30;
   int OFFSET_Y = 30;

   // Clear the default translucent background
   popup.setBackgroundDrawable(new BitmapDrawable());

   // Displaying the popup at the specified location, + offsets.
   popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y);

   // Getting a reference to Close button, and close the popup when clicked.
   Button close = (Button) layout.findViewById(R.id.close);
   close.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
       popup.dismiss();
     }
   });
}
}

Introducing “Even or Odd” – My First Android Game :)

Hello everyone,

I would like to introduce you the freshly cooked “Even or Odd” game, an addictive casual game for Android.

The idea of the game is pretty simple: you are given a series of numbers, and have 30 seconds at your disposal to answer if the given numbers are even or odd ones. Give a correct answer and you get +100 points, you give a wrong answer and you go down: -100 points. Try to give as many correct answers as you can in 30 sec.

This is my first attempt into this kind of Android apps. What was new from what I did previously, is that I made use of MediaPlayer to play sounds. Using MediaPlayer to play sounds will be the subject of another tutorial in the upcoming period of time. Stay tuned. 😉

Android Game Even or Odd

 

First Android Android Game

 

Give it a try and let me know your high score :).

9GAG Pictures Funny Images

ITMoldova – My First Android Application.

Although it has passed awhile since I published my first android application on Google Play, and I published already my second Android App meanwhile, I decided to write about it as well, as almost all my posts from this blog till now are findings and experience gained while I was working on ITMoldova app.

ITMoldova.com is a Moldavian site that provides daily IT News for romanian speaking people. The main purpose of Android application is to check the RSS feed of the site if there are any new articles. If it turns out that new articles have been published on the site, then launch a status bar notification and notify the user. And of course, the user is able to see the most recent articles and read them right from his device.

The application settings provides the ability to set up the desired interval of time, when the application should verify the RSS feed, plus the possibility to Turn On or Off this feature.

ITMoldova Main

ITMoldova

I have some doubts in regards to how many of my readers and visitors of this blog understand Romanian language, but just in case, here’s the Google Play download link: 🙂

Get it on Google Play - ITMoldova

Do you want to build your own RSS Reader Application?

Here are the topics that will help you achieve this:

Creating A Simple RSS Application in Android

Understanding AsyncTask – Once and Forever

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

Working With Services – IntentService

Showing status bar notifications in Android

How to Create Android Menus

Writing and Reading from SharedPreferences

Detecting Internet Connection

Building a Custom Fancy ListView in Android

After reading (and exercising) the above tutorials, you should be able to build your own Cool RSS Application :).

 

Please visit the Android Tutorials page for more Android tutorials.