Friday, 20 December 2013

Android Notification

Learn to create Notification.

Open the project folder and create a new folder "raw" in the res folder. Put a .mp3 file which you want to use as notification sound.

Do the following coding in the MainActivity.java file.

package com.codingredefined.notification;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity 
{
private static final int HELLO_ID=1;
MediaPlayer mMediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String ns=Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager=(NotificationManager)getSystemService(ns);
int icon=R.drawable.ic_launcher;
CharSequence tickerText="Hello!";
long when=System.currentTimeMillis();
Notification notification=new Notification(icon, tickerText, when);
//Vibrate on Notification
notification.defaults=Notification.DEFAULT_VIBRATE;
long[] vibrate={0,100,200,300};
notification.vibrate=vibrate;
//Glow LED
notification.defaults=Notification.DEFAULT_LIGHTS;
notification.ledARGB=0xff00ff00;
notification.ledOnMS=300;
notification.ledOffMS=1000;
notification.flags=Notification.FLAG_SHOW_LIGHTS;
//Activate notification
Context context=getApplicationContext();
CharSequence contextTitle="My Notification";
CharSequence contextText="Hello World!!!";
Intent notificationIntent=new Intent(this,MainActivity1.class);
PendingIntent contentIntent=PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contextTitle, contextText, contentIntent);
mNotificationManager.notify(HELLO_ID, notification);
//Sound
mNotificationManager.notify(HELLO_ID, notification);
mMediaPlayer=new MediaPlayer();
mMediaPlayer=MediaPlayer.create(this,R.raw.abc);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
Thread t=new Thread()
{
@Override
public void run()
{
try
{
Thread.sleep(5000);
}
catch(Exception e){}
mMediaPlayer.stop();
}
};
t.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


The following output will be obtained.

No comments:

Post a Comment