How do I create an Android notification? - android

I followed their tutorial step by step but I keep getting strange errors.
The notifymanager doesn't have .notify() as a method and any line of code with notifymanager in it must have brackets regardless of where it is within the code.
I'm beginning to think it's a dependency issue, please help!

Activity 1
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;
public class NotificationAlert extends Activity {
private static final int NOTIFY_ME_ID=1337;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_alert);
/*********** Create notification ***********/
final NotificationManager mgr=
(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.stat_notify_chat,
"Android Example Status message!",
System.currentTimeMillis());
// This pending intent will open after notification click
PendingIntent i=PendingIntent.getActivity(this, 0,
new Intent(this, NotifyMessage.class),
0);
note.setLatestEventInfo(this, "Android Example Notification Title",
"This is the android example notification message", i);
//After uncomment this line you will see number of notification arrived
//note.number=2;
mgr.notify(NOTIFY_ME_ID, note);
}
}
Activity 2
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class NotifyMessage extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView txt=new TextView(this);
txt.setText("Activity after click on notification");
setContentView(txt);
}
}

Related

trouble implementing android notifications

I would greatly appreciate any help with troubleshooting my use of notifications within the Android emulator. I have tried several different versions without success and the code below seems to distill the needed elements down to the minimum. The problem is that the notification simply doesn't get sent. I hear the "click" noise when I tap the button in the emulator but nothing else.
I had read somewhere that having the wrong type of image may cause problems and I have tried several. The one I have included now is generated using Vector Asset within the res folder. It feels like there is something simple that I am missing but from what I can see from all the examples I have found online the basic elements are sound.
Any help or direction would be appreciated.
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int idNumber = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
}
public void sendNotification(View view){
notification.setSmallIcon(R.drawable.ic_android_black_24dp);
notification.setContentText("This is the notification message");
notification.setContentTitle("Notification");
notification.setTicker("There is a notification");
notification.setWhen(System.currentTimeMillis());
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(idNumber, notification.build());
}
}

How to make Android Direct Reply Notification feature work in pre - Android N devices?

I am trying to implement Android Direct Reply notification in my app. I've managed to implement it successfully in Android N emulator. But it is not working on Marshmallow devices. When I click on action button in notification the reply edittext is not showing in devices below Android N. I know this feature will work in pre Android N devices, as it is available in WhatsApp.
My question is how to make it work in pre Android N devices? I'm sharing my code here. Any help would be great. Thanks.
MainActivity
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.RemoteInput;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
// Key for the string that's delivered in the action's intent.
public static final String KEY_TEXT_REPLY = "key_text_reply";
private static final int notificationID = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startNotif();
}
});
}
private void startNotif() {
Intent intent = new Intent(this, NotificationReciever.class);
// use System.currentTimeMillis() to have a unique ID for the pending intent
final PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
String replyLabel = "Reply";
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)
.setLabel(replyLabel)
.build();
// Create the reply action and add the remote input.
Notification.Action action =
new Notification.Action.Builder(R.drawable.ic_send,
"Action", pIntent)
.addRemoteInput(remoteInput)
.build();
// Build the notification and add the action.
Notification newMessageNotification =
new Notification.Builder(MainActivity.this)
.setSmallIcon(R.drawable.ic_remove_circle_black_48dp)
.setContentTitle("Title")
.setContentText("Content")
.addAction(action).build();
// Issue the notification.
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(notificationID, newMessageNotification);
}
}
NotificationReciever
import android.app.Activity;
import android.app.RemoteInput;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
/**
* Created by User on 13-Jun-16.
*/
public class NotificationReciever extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this,getMessageText(getIntent()),Toast.LENGTH_SHORT).show();
}
private CharSequence getMessageText(Intent intent) {
Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
if (remoteInput != null) {
return remoteInput.getCharSequence(MainActivity.KEY_TEXT_REPLY);
}
Toast.makeText(this,"Remoteinput is null",Toast.LENGTH_SHORT).show();
return null;
}
}
In the docs it tells you to not use a broadcast receiver or a service for api below N. So you'd have to launch an activity which does what you want and wrap it in a pending intent instead.
if (isDirectReplySupported) {
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
}
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Implementing this feature is very simple, first make one broadcastreceiver, as usual create a action button & hook up with pendingintent.
Then connect that intent to push notification object & notify.
In broadcastreceiver handle the reading text part & updating to notification.
Refer this post for sample example http://www.feelzdroid.com/2017/01/android-n-inline-reply-push-notifications.html

iBeacon notification on Android

I just started with Java and Android coding. I wrote an application for a scientific study in my university. The app is for a local exhibition of a museum. I have different locations in my town, each location with its own exhibit.
Now I made an activity for each of the locations, so the user can see some useful information of the sample. Now I want to combine the app with iBeacons, I bought 6 beacons from Estimote. As I am not really experienced with this, I hope you can help with a point to start off?
I want the app to give the user a notification with some text like: "You are in front of object XY. Tap to see more information." After tapping on the notification the user should open the specific activity which I created. I also want the app to search for beacons in the background, so if the user comes close to a location, he/she gets automatically a notification after a few seconds.
I already read a post, but I could not really figure out how to use it correctly:
Estimote iBeacon: Monitoring in background (Android)
A broad answer to a broad question: We did exactly that type of application for a museum here in Finland using our Proximi.io platform. You can of course hardcode the beacons, actions and content into the application by e.g. using the Estimote SDK. The benefit of using an external portal/backend is that you don't have to update the entire app whenever the museum exhibition changes. In the best scenario, the museum itself could be in charge of updating the exhibit info, when they wish. If you're interested, Proximi.io is now in open beta, and it's free and super simple to use.
The free and open source Android Beacon Library has a reference application that launches an activity the first time a beacon is seen. You can see the line of code that launches the Activity here.
In order to modify this to do what you want, you would need to make a different Region object for each museum location, initializing it with its beacon identifiers. You'd put this in the Application onCreate method like this:
Region museumLocation1 = new Region("museumLocation1", Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"), Identifier.parse("1"), Identifier.parse("1"));
Region museumLocation2 = new Region("museumLocation2", Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"), Identifier.parse("1"), Identifier.parse("2"));
List regionList = Arrays.asList(new Region[] {museumLocation1, museumLocation2} );
regionBootstrap = new RegionBootstrap(this, regionList);
Then you can modify the didEnterRegion method in that same class to launch different activities for each beacon like this:
if (region.getUniqueId().equals("museumLocation1")) {
Intent intent = new Intent(this, Museum1Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
if (region.getUniqueId().equals("museumLocation2")) {
Intent intent = new Intent(this, Museum2Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
so now I played a little bit with the code and this is my MainActivity for now.
But I think I am not done yet. The problem is also, that the app not recognizes the region variable in the didEnterRegion - method.
package com.example.walter.him;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Application;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.Identifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.powersave.BackgroundPowerSaver;
import org.altbeacon.beacon.startup.RegionBootstrap;
import org.altbeacon.beacon.startup.BootstrapNotifier;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity implements BootstrapNotifier
{
private static final String TAG = "AndroidProximityReferenceApplication";
private RegionBootstrap regionBootstrap;
private BackgroundPowerSaver backgroundPowerSaver;
private boolean haveDetectedBeaconsSinceBoot = false;
private andreasplatz monitoringActivity = null;
private hagentor monitoringActivity2 = null;
Typeface segoe_wp, times;
private static Button liste, info, about_us;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
liste = (Button) findViewById(R.id.liste);
info = (Button) findViewById(R.id.info);
about_us = (Button) findViewById(R.id.about_us);
segoe_wp = Typeface.createFromAsset(getAssets(), "fonts/segoe_wp.ttf");
times = Typeface.createFromAsset(getAssets(), "fonts/times.ttf");
liste.setTypeface(segoe_wp);
info.setTypeface(segoe_wp);
about_us.setTypeface(segoe_wp);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
BeaconManager beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
Region museumLocation1 = new Region("museumLocation1", Identifier.parse("B9407F30-F5F8-466E-AFF9-25556B57FE6D"), Identifier.parse("56170"), Identifier.parse("42307"));
Region museumLocation2 = new Region("museumLocation2", Identifier.parse("B9407F30-F5F8-466E-AFF9-25556B57FE6D"), Identifier.parse("55787"), Identifier.parse("12089"));
List regionList = Arrays.asList(new Region[]{museumLocation1, museumLocation2});
regionBootstrap = new RegionBootstrap(this, regionList);
backgroundPowerSaver = new BackgroundPowerSaver(this);
onClickOpenInfo();
onClickOpenListe();
onClickOpenAbout();
}
public void didEnterRegion(Region arg0) {
// Cannot resolve symbol 'region'
if (region.getUniqueId().equals("museumLocation1")) {
Intent intent = new Intent(this, andreasplatz.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
if (region.getUniqueId().equals("museumLocation2")) {
Intent intent = new Intent(this, hagentor.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
haveDetectedBeaconsSinceBoot = true;
}
#Override
public void didExitRegion(Region region) {
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
private void sendNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setContentTitle("Beacon Reference Application")
.setContentText("An beacon is nearby.")
.setSmallIcon(R.drawable.ic_launcher);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(new Intent(this, andreasplatz.class));
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
public void setMonitoringActivity(andreasplatz activity) {
this.monitoringActivity = activity;
}
public void onClickOpenInfo()
{
info = (Button)findViewById(R.id.info);
info.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openInfo = new Intent("com.example.walter.him.info_ausstellung");
startActivity(openInfo);
}
}
);
}
public void onClickOpenListe()
{
liste = (Button) findViewById(R.id.liste);
liste.setOnClickListener(
new View.OnClickListener()
{
public void onClick (View v)
{
Intent openListe = new Intent("com.example.walter.him.liste_orte");
startActivity(openListe);
}
}
);
}
public void onClickOpenAbout()
{
about_us = (Button) findViewById(R.id.about_us);
about_us.setOnClickListener(
new View.OnClickListener()
{
public void onClick (View v)
{
Intent openAbout = new Intent("com.example.walter.him.about_us");
startActivity(openAbout);
}
}
);
}
}

How to make the notification disappeared after the user have clicked on it

Please take a look at my code:
package com.yarin.android.Examples_04_23;
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;
import android.widget.Button;
public class Activity01 extends Activity {
Button m_Button1;
//声明通知(消息)管理器
NotificationManager m_NotificationManager;
Intent m_Intent;
PendingIntent m_PendingIntent;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//初始化NotificationManager对象
m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//获取按钮对象
m_Button1 = (Button) findViewById(R.id.Button01);
//点击通知时转移内容
m_Intent = new Intent(Activity01.this, Activity02.class);
//主要是设置点击通知时显示内容的类
m_PendingIntent = PendingIntent.getActivity(Activity01.this, 0, m_Intent, 0);
m_Button1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Notification m_Notification = new Notification();
//设置通知在状态栏显示的图标
m_Notification.icon = R.drawable.img1;
//当我们点击通知时显示的内容
m_Notification.tickerText = "Button1通知内容...........";
//通知时发出默认的声音
m_Notification.defaults = Notification.DEFAULT_SOUND;
//设置通知显示的参数
m_Notification.setLatestEventInfo(Activity01.this, "Button1", "Button1通知", m_PendingIntent);
//可以理解为执行这个通知
m_NotificationManager.notify(0, m_Notification);
}
});
}
}
When a user click on the button click , a notification will appear on the application bar. However, the notification will stay there for ever after a user have click on it
Just add a line in your m_Button1 click listener right after :
m_Notification.defaults = Notification.DEFAULT_SOUND;
m_Notification.flags |= Notification.FLAG_AUTO_CANCEL;
Notification notification = new Notification();
notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL
From the docs
"Bit to be bitwise-ored into the flags field that should be set if the notification should be canceled when it is clicked by the user"

launch activity from service when notification is clicked

I know, there are tons of these on here, but I've been trying solutions all day and haven't gotten anywhere.
Neither the example on google's docs, nor any of the 5 other ways I've found on here have worked for me at all.
As is the typical case, when I click the notification it closes the status bar and nothing new is shown onscreen.
I am creating the notification from a service and need the notification to trigger a new activity that has not yet been created.
I also will need a way to pass information to that activity via intent.
And yes... this is java for Android
What follows are the shattered remnants of my code.
package com.bobbb.hwk2;
import java.io.FileOutputStream;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.widget.Toast;
public class contactBackup extends Service
{
private NotificationManager nManager;
private static final int NOTIFY_ID = 1100;
#Override
public void onCreate()
{
super.onCreate();
String ns = Context.NOTIFICATION_SERVICE;
nManager = (NotificationManager)getSystemService(ns);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// inform user that service has started
Toast.makeText(getApplicationContext(), R.string.service_started,Toast.LENGTH_LONG).show();
String data = lookUpContacts();
if( saveToSDCard(getResources().getString(R.string.backup_file_name),data) )
{
Context context = getApplicationContext();
// create the statusbar notification
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
//nIntent.putExtra("data",data);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
}
}
#Override
public void onDestroy()
{
nManager.cancel(NOTIFY_ID);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
// function returns string containing information
// from contacts
public String lookUpContacts()
{
...
}
public boolean saveToSDCard(String fileName, String data)
{
...
}
}
I can only hope that whatever is causing my problem is something fixable and not more of the crazy glitches I've been getting with eclipse (which no one else seems to have ever seen >:U )
If you can help me solve this problem, please share.
If you can't help with this specific problem but feel obligated to say unrelated things about posting, styles, topics, or good practice, then DON'T
Thank you :D
Edit:
You're going to have to add a flag for FLAG_ACTIVITY_NEW_TASK:
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
This is because you're launching from outside your app (from the system notification bar).
This is what happens when people overwork themselves. XD
The only reason none of the tutorials I tired worked is because I misspelled my activity name in the manifest.
Thanks for stopping by
Just add following in contactBackup(service class),
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
nIntent.putExtra("data",data);
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
then get value in contactViewer class,
as,
String s=getIntent().getStringExtra("data");

Categories

Resources