I am trying to generate an 'onclick' notification just for learning purposes in android studio, sdk version Oreo. But I just cant get it to work. I have also created a notification channel but it isn't working. Can someone please tell what is the issue in the java code.
package com.example.notificationexample;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
public class MainActivity extends AppCompatActivity {
Button button;
private final String CHANNEL_ID = "perosnal_notifications";
private final int NOTIFICATION_ID = 001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.click);
final long [] vibe = {0,500};
final Uri notificationsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createNotificationChannel();
NotificationCompat.Builder mbuilder = (NotificationCompat.Builder)
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.yo,10)
.setSound(notificationsound)
.setVibrate(vibe)
.setContentTitle("Notification")
.setContentText("This is a notification for you");
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID,mbuilder.build());
}
});
}
private void createNotificationChannel()
{
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
CharSequence name = "Personal not";
String description = "Include all personal nots";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationChannel.setDescription(description);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
XML code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="30sp"
android:text="Notofication"/>
</RelativeLayout>
The application displays an error saying:
"developer warning for package.. Failed to post notification on channel 'personal_notifications'"
Android version of virtual device is 11
Add channel id to builder:
NotificationCompat.Builder mbuilder = (NotificationCompat.Builder)
new NotificationCompat.Builder(getApplicationContext(),
CHANNEL_ID)// add channel id
Related
i am trying to make a small project in android for the college where the user has the option to select time from time picker dialog and based on the time selected an notification to drink water will be issued to the user and repeated every 15 minutes.However the alarm manager used issues notification vaguely.Sometimes notification are issued on time and repeated after every 15 minutes although after midnight the notifications stop.Also sometimes there is a delay to issue the notification.Cant figure out why! Help appreciated..Here are the necessary xml and java files
activity_water.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relative"
tools:context="com.example.priyam.databaselogin.Water">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"
android:layout_marginTop="70dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="15dp">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/reminderWaterCheckbox"
android:buttonTint="#color/red"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="Remind me once at"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="170dp"
android:text="09:30 AM"
android:textColor="#color/red"
android:id="#+id/textViewTime"/>
</LinearLayout>
</RelativeLayout>
water.java
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class Water extends AppCompatActivity implements View.OnClickListener {
TextView time;
CheckBox waterReminder;
int h,m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_water);
setTitle("Water Reminder");
getId();
Toast.makeText(getApplicationContext(),"this",Toast.LENGTH_LONG).show();
}
private void getId(){
time=(TextView)findViewById(R.id.textViewTime);
waterReminder=(CheckBox)findViewById(R.id.reminderWaterCheckbox);
time.setOnClickListener(this);
}
private void showDialog(){
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
h=hourOfDay;
m=minute;
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,h);
calendar.set(Calendar.MINUTE,m);
Intent intent=new Intent(getApplicationContext(),Notification_receiver.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_FIFTEEN_MINUTES,pendingIntent);
time.setText(h+":"+m);
}
}, h, m, false);
timePickerDialog.show();
}
#Override
public void onClick(View v) {
showDialog();
}
}
Notification_receiver.java
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
public class Notification_receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent1=new Intent(context,DashBoard.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent=PendingIntent.getActivity(context,100,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder=new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Hitfit")
.setContentText("Its time you gulped a glass of water!Stay hydrated,stay fit!")
.setAutoCancel(true);
builder.setVibrate(new long[] { 1000, 1000});
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
notificationManager.notify(100,builder.build());
}
}
Minnimum sdkVersion used is 18
Stuck on this since days.Thank you!
In the documentation of AlarmManager, you can see the following notice :
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
I think you are in this case actually, and your alarms aren't exact because that's how the system keeps battery as of API 19.
I have a simple app that generates notifications on button Click. I also have an editText so that the content Text is typed by the user. I have two buttons that generates two different notifications. My requirement is that on every button click there should be only one notification generated and the rest should be in the notification stack. I have tried using notification setGroup property but the method doesn't seem to work. I have attached my code below for further reference.
Main Activity(Java file):-
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private static final String GROUP_NOTIFICATIONS="group_notifications";
NotificationCompat.Builder notification;
NotificationCompat.Builder notification1;
PendingIntent pIntent;
NotificationManager manager,manager1;
Intent resultIntent;
Button button,button1;
EditText editText;
int a=0,b=100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText= (EditText) findViewById(R.id.edittext);
button= (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startNotification();
}
});
button1= (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Notifications();
}
});
}
public void buttonClick(View view)
{
startNotification();
}
public void startNotification()
{
// Intent intent=new Intent(MainActivity.this,MyService.class);
// intent.putExtra("id",Integer.toString(a));
// startService(intent);
// PendingIntent pendingIntent=PendingIntent.getService(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
String str=editText.getText().toString();
notification=new NotificationCompat.Builder(this);
notification.setContentTitle("ABC");
notification.setContentText(str);
notification.setTicker("New Message Arrived");
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setGroup(GROUP_NOTIFICATIONS);
notification.setGroupSummary(true);
int num=0;
// notification.setNumber(++num);
Uri uri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.setSound(uri);
manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(a,notification.build());
a++;
}
public void Notifications()
{
String str=editText.getText().toString();
notification1=new NotificationCompat.Builder(MainActivity.this);
notification1.setContentTitle("ABC");
notification1.setContentText(str);
notification1.setTicker("New Message Arrived");
notification1.setSmallIcon(R.mipmap.ic_launcher);
notification1.setGroup(GROUP_NOTIFICATIONS);
notification1.setGroupSummary(true);
int num=0;
// notification1.setNumber(++num);
Uri uri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification1.setSound(uri);
manager1= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager1.notify(a,notification1.build());
a++;
}
}
activity_main.xml(XML file)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="com.example.pratik.stacked.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edittext"
android:textColor="#color/colorPrimary"
android:textSize="20sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Stacked Notification"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Stacked notifiction 1"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignLeft="#+id/button"
android:layout_alignStart="#+id/button"
/>
</RelativeLayout>
AndroidManifest.xml(Manifest file)
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
This is all about setting properly flags.
FLAG_GROUP_SUMMARY
The problem is that you are incrementing (a++) the notification ID:
manager1.notify(a,notification1.build());
a++;
If you want to update an existing notification you should call notify with the notification ID that you want to update. You can refer to the documentation
If you are on Android >= 4.1 you can use expanded layouts. Take into account that in this case you may want to ensure compatibility following these guidelines.
I am trying to use spannable string with image on push notification. It is not working. Actually I want to show emoticon on push notification like wattsapp. If I am using simple spannable string it is working. The same spannable string with image is working fine with textview.
For this I have also tried custom push notification but did not get success.
My code is as follows :-
MainActivity.class
package com.example.tt.notificationtest;
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.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btnNotification;
TextView txtMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtMsg = (TextView) findViewById(R.id.txtMsg);
btnNotification = (Button) findViewById(R.id.btnNotification);
btnNotification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Notify("Testing", "msg");
Notify2();
}
});
}
private void Notify2(){
int icon = R.drawable.asdf;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, "Custom Notification", when);
NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setImageViewResource(R.id.image, R.drawable.asdf);
SpannableString ss = new SpannableString("abcd");
Drawable d = getResources().getDrawable(R.drawable.asdf);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
contentView.setTextViewText(R.id.title, "Custom notification");
contentView.setTextViewText(R.id.text, ss);
notification.contentView = contentView;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification
notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
notification.defaults |= Notification.DEFAULT_SOUND; // Sound
mNotificationManager.notify(1, notification);
}
private void Notify(String notificationTitle, String notificationMessage){
//This is working
// SpannableString ss = new SpannableString("Large\n\n" ); // index 103 - 112
// ss.setSpan(new BackgroundColorSpan(Color.CYAN), 0, 5, 0);
//this is not working
SpannableString ss = new SpannableString("abcd");
Drawable d = getResources().getDrawable(R.drawable.asdf);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
txtMsg.setText(ss);
Intent i = new Intent(MainActivity.this, MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(this, 0,
i,
0);
Notification notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle(notificationTitle)
.setContentText(ss)
.setSmallIcon(R.drawable.asdf)
// .setLargeIcon(bitmap)
// .setDefaults(Notification.DEFAULT_ALL)
.setStyle(new NotificationCompat.BigTextStyle().bigText(ss))
.setAutoCancel(true)
.setContentIntent(pi)
.build();
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(2, notification);
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.tt.notificationtest.MainActivity">
<TextView
android:id="#+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:id="#+id/btnNotification"/>
</LinearLayout>
custom_notification.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_marginRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/image" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_toRightOf="#id/image" />
</RelativeLayout>
This is the only way I got it working:
Spanned mssg;
mssg = Html.fromHtml(URLDecoder.decode("%F0%9F%98%82"));
It may vary depending on how do you receive your text, in my case i'm sending the emojicons using unicode to a GCM server and I don't have to worry about the URLDecoder, but if I receive a message sent from a emojicon PHP library and not from an android device the only way to show it properly was with the URLDecoder.
So if you're working with GCM it should be working with just
Spanned mssg;
mssg = Html.fromHtml(intent.getStringExtra("message"));
Hope it helps!
Mixpanel have working solution for sending emoticons in push notifications. You can find description here
You are using deprecated code here
Notification notification = new Notification(icon, "Custom Notification", when);
Instead use your RemoteView like NotificationBuilder.sentContent(remoteView)
Take a look at this Custom Notification example
This is my sample code that i used to generate notifications. So far i was able to get English Notifications. But now i want to get another language notifications on the notification bar ("Sinhala" )
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification ")
.setContentText("Hello World!");
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, View.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(View.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());
(i)Add any sinhala TTF file to the assets directory in the project(copy and paste).
For a sample create main.xml file using two edit text filed and a button.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<LinearLayout android:layout_width="match_parent" android:id="#+id/linearLayout1" android:orientation="vertical" android:layout_height="wrap_content">
<EditText android:layout_height="wrap_content" android:id="#+id/editText1" android:layout_width="match_parent">
<requestFocus></requestFocus>
</EditText>
</LinearLayout>
<Button android:text="Tnkak" android:layout_height="wrap_content" android:id="#+id/button1" android:layout_width="104dp"></Button>
<EditText android:layout_height="wrap_content" android:id="#+id/editText2" android:layout_width="match_parent"></EditText>
</LinearLayout>
android:text="Tnkak", this English letters are related to Sinhala ඔබන්න(Click) word.
In LanguageAppActivity class
package com.languageapp;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class LanguageAppActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button myButton=(Button)findViewById(R.id.button1);
Typeface type=Typeface.createFromAsset(getAssets(), "ARADANA.TTF");
myButton.setTypeface(type);
myButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Typeface tf = Typeface.createFromAsset(getAssets(),"ARADANA.TTF");
EditText et=(EditText)findViewById(R.id.editText2);
et.setTypeface(tf);
EditText editText=(EditText)findViewById(R.id.editText1);
et.setText(editText.getText());
}
}
You can do the same thing for your title and notification bar!
I want to show continuous notifications in my application.
Currently I am able to raise notification automatically after 4sec but what I want is it should continuously raise after specific time interval.
Following is my code.
my xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button android:id="#+id/notify"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Raise a notification"
android:onClick="notifyMe"
/>
<Button android:id="#+id/cancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Clear the notification"
android:onClick="clearNotification"
/>
</LinearLayout>
this is my activity file
package com.vimaltuts.android.notificationexample;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class NotificationExampleActivity extends Activity {
private static final int NOTIFY_ME_ID=1987;
private int count=0;
private NotificationManager mgr=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
View v = new View(getApplicationContext());
notifyMe(v);
}},4000);
}
#SuppressWarnings("deprecation")
public void notifyMe(View v)
{
#SuppressWarnings("deprecation")
Notification note=new Notification(R.drawable.stat_notify_chat,"Status message!",System.currentTimeMillis());
PendingIntent i=PendingIntent.getActivity(this,0,new Intent(this, NotificationMessage.class),0);
note.setLatestEventInfo(this, "New Email","Unread Conversation", i);
note.number=++count;
note.vibrate=new long[] {500L, 200L, 200L, 500L};
note.flags|=Notification.FLAG_AUTO_CANCEL;
mgr.notify(NOTIFY_ME_ID, note);
}
public void clearNotification(View v) {
mgr.cancel(NOTIFY_ME_ID);
}
}
Please tell me where should I need to have additional code if any?
Also is it possible with service..how?
i tried following code foe test purpose but it did't work...can anyone tell me where i goes wrong
following is my activity code
Intent i= new Intent(NotificationExampleActivity.this,NotificationService.class);
PendingIntent pi=PendingIntent.getService(NotificationExampleActivity.this, 0, i, 0);
AlarmManager alarmMgr=(AlarmManager)getSystemService(ALARM_SERVICE);
alarmMgr.cancel(pi);
alarmMgr.setRepeating(alarmMgr.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(),(10*1000), pi);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
And following is my broadcast reciver
Toast.makeText(context, "Repeating Alarm worked.", Toast.LENGTH_LONG).show();
i want to display msg="Repeating Alarm worked" after some time intervel
Try using an AlarmManager along with the notification.
You can set a repeating alarm in your Activity. Then create a class that extends the BroadcastReceiver. Override the onReceive method where in you can write the code for your notification.
A tutorial on this is explained very well over here.