Android Notification Example

Android Notification Example

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity implements View.OnClickListener {
NotificationHandler nHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
nHandler = NotificationHandler.getInstance(this);
initUI();
}


private void initUI () {
setContentView(R.layout.activity_main);
findViewById(R.id.simple_notification).setOnClickListener(this);
findViewById(R.id.big_notification).setOnClickListener(this);
findViewById(R.id.progress_notification).setOnClickListener(this);
findViewById(R.id.button_notifcation).setOnClickListener(this);
}


@Override
public void onClick (View v) {
switch (v.getId()) {

case R.id.simple_notification:
nHandler.createSimpleNotification(this);
break;

case R.id.big_notification:
nHandler.createExpandableNotification(this);
break;

case R.id.progress_notification:
nHandler.createProgressNotification(this);
break;

case R.id.button_notifcation:
nHandler.createButtonNotification(this);
}

}
}

NotificationHandler.java

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.widget.Toast;

import java.util.Random;

public class NotificationHandler {
// Notification handler singleton
private static NotificationHandler nHandler;
private static NotificationManager mNotificationManager;


private NotificationHandler () {}


/**
* Singleton pattern implementation
* @return
*/
public static  NotificationHandler getInstance(Context context) {
if(nHandler == null) {
nHandler = new NotificationHandler();
mNotificationManager =
(NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
}

return nHandler;
}


/**
* Shows a simple notification
* @param context aplication context
*/
public void createSimpleNotification(Context context) {
// Creates an explicit intent for an Activity
Intent resultIntent = new Intent(context, TestActivity.class);

// Creating a artifical activity stack for the notification activity
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(TestActivity.class);
stackBuilder.addNextIntent(resultIntent);

// Pending intent to the notification manager
PendingIntent resultPending = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

// Building the notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher) // notification icon
.setContentTitle("I'm a simple notification") // main title of the notification
.setContentText("I'm the text of the simple notification") // notification text
.setContentIntent(resultPending); // notification intent

// mId allows you to update the notification later on.
mNotificationManager.notify(10, mBuilder.build());
}


public void createExpandableNotification (Context context) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// Building the expandable content
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
String lorem = context.getResources().getString(R.string.long_lorem);
String [] content = lorem.split("\\.");

inboxStyle.setBigContentTitle("This is a big title");
for (String line : content) {
inboxStyle.addLine(line);
}

// Building the notification
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher) // notification icon
.setContentTitle("Expandable notification") // title of notification
.setContentText("This is an example of an expandable notification") // text inside the notification
.setStyle(inboxStyle); // adds the expandable content to the notification

mNotificationManager.notify(11, nBuilder.build());

} else {
Toast.makeText(context, "Can't show", Toast.LENGTH_LONG).show();
}
}


/**
* Show a determinate and undeterminate progress notification
* @param context, activity context
*/
public void createProgressNotification (final Context context) {

// used to update the progress notification
final int progresID = new Random().nextInt(1000);

// building the notification
final NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.refresh)
.setContentTitle("Progres notification")
.setContentText("Now waiting")
.setTicker("Progress notification created")
.setUsesChronometer(true)
.setProgress(100, 0, true);



AsyncTask<Integer, Integer, Integer> downloadTask = new AsyncTask<Integer, Integer, Integer>() {
@Override
protected void onPreExecute () {
super.onPreExecute();
mNotificationManager.notify(progresID, nBuilder.build());
}

@Override
protected Integer doInBackground (Integer... params) {
try {
// Sleeps 2 seconds to show the undeterminated progress
Thread.sleep(5000);

// update the progress
for (int i = 0; i < 101; i+=5) {
nBuilder
.setContentTitle("Progress running...")
.setContentText("Now running...")
.setProgress(100, i, false)
.setSmallIcon(R.drawable.download)
.setContentInfo(i + " %");

// use the same id for update instead created another one
mNotificationManager.notify(progresID, nBuilder.build());
Thread.sleep(500);
}

} catch (InterruptedException e) {
e.printStackTrace();
}

return null;
}


@Override
protected void onPostExecute (Integer integer) {
super.onPostExecute(integer);

nBuilder.setContentText("Progress finished :D")
.setContentTitle("Progress finished !!")
.setTicker("Progress finished !!!")
.setSmallIcon(R.drawable.accept)
.setUsesChronometer(false);

mNotificationManager.notify(progresID, nBuilder.build());
}
};

// Executes the progress task
downloadTask.execute();
}


public void createButtonNotification (Context context) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// Prepare intent which is triggered if the  notification button is pressed
Intent intent = new Intent(context, TestActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);

// Building the notifcation
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher) // notification icon
.setContentTitle("Button notification") // notification title
.setContentText("Expand to show the buttons...") // content text
.setTicker("Showing button notification") // status bar message
.addAction(R.drawable.accept, "Accept", pIntent) // accept notification button
.addAction(R.drawable.cancel, "Cancel", pIntent); // cancel notification button

mNotificationManager.notify(1001, nBuilder.build());

} else {
Toast.makeText(context, "You need a higher version", Toast.LENGTH_LONG).show();
}
}
}

TestActivity.java


import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TestActivity extends Activity {

@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TextView text = new TextView(this);
text.setText("Test activity");
setContentView(text);

}
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
    tools:context=".MainActivity" >

<Button
android:id="@+id/simple_notification"
   android:text="Simple notification"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
style="@style/buttonStyle">
</Button>

<Button
android:id="@+id/big_notification"
android:text="Expandable with buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/buttonStyle">
</Button>

<Button
android:id="@+id/progress_notification"
android:text="Progress notification"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/buttonStyle">
</Button>

<Button
android:id="@+id/button_notifcation"
android:text="Button notification"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/buttonStyle">
</Button>




</LinearLayout>

I Am Not The Owner Of These Code .I Merely Have Copied Them From Various Sources. The Only Thing I Did Is That I Am Going To Present Them In More Easy Way To Understand.






Comments

Popular posts from this blog

LED Blinking using 8051 Microcontroller and Keil C – AT89C51

Android Camera Example 2

Java Script to make text change text color