Thursday, September 6, 2012

Notification in Android Using AlarmManager, BoradCastReceiver & Services


    Our aim is to show notification message to user in a specific time.

    Say For example , I have planned to show Notification Message to user at 2 pm on 25 September 2012, even though the user did not visited my app.

   You can download the complete code from My Github
    https://github.com/sankarganesh/NotificationDemo

          Step 1:

                      Create a Calendar Object and set the date and time in which we want to show the Notification message to the user. As per our example , we have to set 2012-Sep-06 14:25:00
                        
                        The Calendar takes the Value for month of January as 0 , the value of Sep should be 8 not 9.

                         Calendar Calendar_Object  = Calendar.getInstance();
                         Calendar_Object.set(Calendar.MONTH, 8);
                         Calendar_Object.set(Calendar.YEAR, 2012);
                         Calendar_Object.set(Calendar.DAY_OF_MONTH, 6);

                         Calendar_Object.set(Calendar.HOUR_OF_DAY, 14);
                         Calendar_Object.set(Calendar.MINUTE, 25);
                         Calendar_Object.set(Calendar.SECOND, 0);


           Step 2:

                We need to create an alarm which help us to invoke the BroadCastReceiver on our specified time.

                           // MyView is my current Activity, and AlarmReceiver is the BoradCastReceiver
                             Intent myIntent = new Intent(MyView.this, AlarmReceiver.class);

                            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                            MyView.this, 0, myIntent, 0);

                           AlarmManager alarmManager = (AlarmManager)                              getSystemService(ALARM_SERVICE);

                        /* 
                           The following sets the Alarm in the specific time by getting the long value of the alarm  date time which is in calendar object by calling the getTimeInMillis(). Since Alarm supports only long value , we're using this method.
                       */

                    alarmManager.set(AlarmManager.RTC, Calendar_Object.getTimeInMillis(),
                            pendingIntent);

             Step 3:
                         
               We need to create a BroadCastReceiver which invoked when our alarm is triggered.

                            import android.content.BroadcastReceiver;
                            import android.content.Context;
                            import android.content.Intent;

                            public class AlarmReceiver extends BroadcastReceiver {

                                 @Override
                                 public void onReceive(Context context, Intent intent) {
                                 // When our Alaram time is triggered , this method will be excuted (onReceive)
                                 // We're invoking a service in this method which shows Notification to the User
                                  Intent myIntent = new Intent(context, NotificationService.class);
                                  context.startService(myIntent);
                                }

                          } 

             Step 4:

               We need to Create a Service which will show Notification to the User.

                           import android.app.Notification;
                           import android.app.NotificationManager;
                           import android.app.PendingIntent;
                           import android.app.Service;
                           import android.content.Intent;
                           import android.os.IBinder;

                           public class NotificationService extends Service {

                               private NotificationManager mManager;

                               @Override
                                public IBinder onBind(Intent arg0) {
                                 // TODO Auto-generated method stub
                                 return null;
                               }

                               @Override
                               public void onCreate() {
                               super.onCreate();
                               }

                               @Override
                               public void onStart(Intent intent, int startId) {
                               super.onStart(intent, startId);
                              // Getting Notification Service
                              mManager = (NotificationManager) this.getApplicationContext()
                             .getSystemService(                                                         this.getApplicationContext().NOTIFICATION_SERVICE);
                              /* 
                              When the user taps the notification we have to show the Home Screen of our App,      this job can be done with the help of the following Intent.
                              */
                                Intent intent1 = new Intent(this.getApplicationContext(),
                                MyView.class);

                               Notification notification = new Notification(R.drawable.icon,
                              "See My App something for you", System.currentTimeMillis());

                               intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                                | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                               PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
                               this.getApplicationContext(), 0, intent1,
                               PendingIntent.FLAG_UPDATE_CURRENT);

                               notification.flags |= Notification.FLAG_AUTO_CANCEL;

                              notification.setLatestEventInfo(this.getApplicationContext(), "SANBOOK",
                              "See My App something for you", pendingNotificationIntent);

                              mManager.notify(0, notification);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Logger.error("Alam Services Destroyed");
        super.onDestroy();
    }

}

 Step 5:
        Don't forget to register your Broadcast Receiver as well as Services and your Activity in Manifest File.
       Also Don't forget to add the permission <uses-permission android:name="android.permission.WAKE_LOCK" />

Step 6:

              Here's the output in Tablet Devices and Mobile 

             Tablet Device:

                         
 


       Mobile Devices:
                                    
                                                  

Friday, May 18, 2012

Checking whether your app running in a Phone or in a Tablet


How to check whether your app running in a Phone or in  a Tablet ?


Step1:  Create a Display Object which help us to retrieve the width and height of the device.

Step2 :  Method which i had wrote below will return true if your app running in Tablet or it will return false.
 
public static boolean isTablet(Display display) {

        Log.d("tablet", "isTablet()  invoked");
      
        final int width = display.getWidth();
        final int height = display.getHeight();     
  

        switch (display.getOrientation()) {

        case 0: case 2:   // Landscape Mode
            if(width > height) return true;
            break;
        case 1: case 3:  // Portrait Mode
            if(width < height) return true;
            break;
        }
        return false;
    }

Monday, January 30, 2012

Using Custom Font in android

How to use Custom Font whose file size is higher than asset folder in android?

Step 1: Just place that font file on raw folder "/res/raw/chen.ttf" , Say here the font name is chen.ttf

Step 2: 

Typeface  typeFace= readFont(R.raw.chen); 
textView.setTypeface(typeFace);

Step 3:

Create a method which reads the font file and set it to typeface object
 
Step 4:  

Typeface readFont(int resource)
{  
Typeface tf_obj = null;
InputStream is = getResources().openRawResource(resource);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/gmg_underground_tmp";
File f = new File(path);
if (!f.exists())
{
    if (!f.mkdirs())
        return null;
}
String outPath = path + "/tmp.raw";
try
{
    byte[] buffer = new byte[is.available()];
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));

    int l = 0;
    while((l = is.read(buffer)) > 0)
    {
        bos.write(buffer, 0, l);
    }
    bos.close();

    tf_obj = Typeface.createFromFile(outPath);

    File f2 = new File(outPath);
    f2.delete();
}
catch (IOException e)
{
    return null;
}
return tf_obj;      }

Notification in Android Using AlarmManager, BoradCastReceiver & Services

    Our aim is to show notification message to user in a specific time.     Say For example , I have planned to show Notification ...