Coverting iOS notifications to Android notifications - android

Trying to convert my iOS app to android, I know I can't port it so I wrote it from scratch
How can I covert this notification to Android Java code?
-(IBAction)turnon {
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:28];
[comps setMonth:9];
[comps setYear:2012];
[comps setHour:8];
[comps setMinute:25];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *fireDate = [gregorian dateFromComponents:comps];
UILocalNotification *alarm = [[UILocalNotification alloc] init];
alarm.fireDate = fireDate;
alarm.repeatInterval = NSDayCalendarUnit;
alarm.soundName = #"msl.aiff";
alarm.alertBody = #"This is a message..";
alarm.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:alarm];
I've searched the web for like 4 hours now and I think this is simple for an Android developer but since I just started I just don't have any idea how to do this.
Any help is really appreciated!

This is what your looking for:
You can use the alarm manager to show notifications at specific times, even when your app is not running at all.
http://developer.android.com/reference/android/app/AlarmManager.html
Everyday notifications at certain time
This one is useful to:
Using Alarmmanager to start a service at specific time
Edit see comments:
You can the AlarmManager for this, first create you self some kind of reciever.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent dailyUpdater = new Intent(context, MyService.class);
context.startService(dailyUpdater);
Log.d("AlarmReceiver", "started service");
}
}
Than you need to create the service which is going to show the notifications
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private NotificationManager mNM;
private int NOTIFICATION = 546;
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
return START_STICKY;
}
#Override
public void onDestroy() {
mNM.cancel(NOTIFICATION);
Toast.makeText(this, "stopped service", Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
private void showNotification() {
Toast.makeText(this, "show notification", Toast.LENGTH_SHORT).show();
//notification code here
}
}
And finally you need to set the alarm:
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.set(Calendar.HOUR_OF_DAY, 20);
updateTime.set(Calendar.MINUTE, 30);
Intent open = new Intent(context, AlarmReceiver.class);
open.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, open, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 5000, 10000, pendingIntent);
}
And before you make a test run add your Receiver and Service to your manifest file:
<service android:name=".MyService"></service>
<receiver android:name=".AlarmReceiver"></receiver>

A copy paste with some minor changes from the Android developer site
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.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(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.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) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
// Sets an ID for the notification, so it can be updated
int mId= 1;
mNotificationManager.notify(mId, mBuilder.build());

Related

Android app with daily notification

I'm making an android application.... and I've been trying to write the code for a daily notification set for a specific time of day. At first, I really thought this would be an easy task, almost every app in the play store has a timed notification. But after searching over and over again, all the methods and Youtube tutorials I've found failed to work for me. The problem probably lies in me, but I don't know what it is. All I need is a simple, elegant, easy to understand method (if there is such a thing). Any help would be greatly appreciated.
All the searching I've done has gotten me this far... but still without any luck:
This method is in my MainActivity class and is called only the first time the app is launched to set the alarm...
private void alarmMethod() {
Intent myIntent = new Intent(this, NotifyService.class);
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG)
.show();
This is my NotifyService class:
package com.OHS.example;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class NotifyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification mNotify = new NotificationCompat.Builder(this)
.setContentTitle("Title")
.setContentText("Hello World!")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setSound(sound)
.build();
mNM.notify(1, mNotify);
}
}
Try This Code.
XML layout :
<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=".MainActivity" >
<TextView
android:id="#+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Alarm Example:\n\rSetup an alarm event after 10 seconds from the current time. So just press Setup Alarm button and wait for 10 seconds. You can see a toast message when your alarm time will be reach." />
<Button
android:id="#+id/setAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:onClick="onClickSetAlarm"
android:text="Set Alarm" />
Main Activity :
public class MainActivity extends Activity {
//used for register alarm manager
PendingIntent pendingIntent;
//used to store running alarmmanager instance
AlarmManager alarmManager;
//Callback function for Alarmmanager event
BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register AlarmManager Broadcast receive.
RegisterAlarmBroadcast();
}
public void onClickSetAlarm(View v)
{
//Get the current time and set alarm after 10 seconds from current time
// so here we get
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000 , pendingIntent );
}
private void RegisterAlarmBroadcast()
{
Log.i("Alarm Example:RegisterAlarmBroadcast()", "Going to register Intent.RegisterAlramBroadcast");
//This is the call back function(BroadcastReceiver) which will be call when your
//alarm time will reached.
mReceiver = new BroadcastReceiver()
{
private static final String TAG = "Alarm Example Receiver";
#Override
public void onReceive(Context context, Intent intent)
{
Log.i(TAG,"BroadcastReceiver::OnReceive() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
Toast.makeText(context, "Congrats!. Your Alarm time has been reached", Toast.LENGTH_LONG).show();
}
};
// register the alarm broadcast here
registerReceiver(mReceiver, new IntentFilter("com.myalarm.alarmexample") );
pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("com.myalarm.alarmexample"),0 );
alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
private void UnregisterAlarmBroadcast()
{
alarmManager.cancel(pendingIntent);
getBaseContext().unregisterReceiver(mReceiver);
}
#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;
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
}
I Hope this will help you, this worked for me.
You can always calculate and set the time when you want to trigger the alarm.
Happy Coding !!
You could use AlarmManager to schedule the daily notification. The document here provide a good explanation and example.
Setup the alarm.
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0,
new Intent(this, MainService.class),
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
// set the triggered time to currentHour:08:00 for testing
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 8);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 0, pendingIntent);
Service to handle the alarm.
public class MainService extends IntentService {
public MainService() {
super("mainservice");
}
public MainService(String name) {
super(name);
}
/*
* (non-Javadoc)
*
* #see android.app.IntentService#onHandleIntent(android.content.Intent)
*/
#Override
protected void onHandleIntent(Intent intent) {
showNotification();
}
private void showNotification() {
Uri soundUri = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Alarm title")
.setContentText("Alarm text")
.setContentIntent(
PendingIntent.getActivity(this, 0, new Intent(this,
SecondActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT))
.setSound(soundUri).setSmallIcon(R.drawable.ic_launcher)
.build();
NotificationManagerCompat.from(this).notify(0, notification);
}
}
as alijandro said if you want to have a daily notification in specific time you could use AlarmManager to schedule it and at that time show notification or if you want to get data from server, send a http request to retrieve your data and show notification to the user.
But if you want to have push notification anytime you want, you could use GCM (Google Cloud Messaging). Look at this doc.

how to show android notification and application icon

I have a service running, and would like to send a notification. Too bad, the notification object requires a context, like an Activity, and not a service.
Do you know any way to by pass that ? I tried to create an Activity for each notification bu it seems ugly, and I can't find a way to launch an Activity without any view.
i also want to sent my application icon to notification to show icon top of screen
Here is a working code , which creates a notification from a service itself.
hope it will help you,
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//We get a reference to the NotificationManager
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String MyText = "Reminder";
Notification mNotification = new Notification(R.drawable.ic_launcher, MyText, System.currentTimeMillis() );
//The three parameters are: 1. an icon, 2. a title, 3. time when the notification appears
String MyNotificationTitle = "Medicine!";
String MyNotificationText = "Don't forget to take your medicine!";
Intent MyIntent = new Intent(Intent.ACTION_VIEW);
PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//A PendingIntent will be fired when the notification is clicked. The FLAG_CANCEL_CURRENT flag cancels the pendingintent
mNotification.setLatestEventInfo(getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);
int NOTIFICATION_ID = 1;
notificationManager.notify(NOTIFICATION_ID , mNotification);
//We are passing the notification to the NotificationManager with a unique id.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}

Android notification from service does not open activity

Updated MyService #CommonsWare
i have a service that if started will set up an alarm that triggers the notification.
This works fine and the alarms are canceled if the service is stopped.
i am trying to get the notification to open a new activity class but can not get it done
my service class is the following:
package com.example.andtip;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class BReceiver extends BroadcastReceiver {
private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, DoSomething.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent("com.example.andtip"),0 );
PendingIntent pi2 = PendingIntent.getActivity(context, 0, myIntent,0 );
myNotification=new NotificationCompat.Builder(context)
.setContentTitle("This is a notification from the example alarm application.")
.setContentText("Notification")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pi)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
}
how should i link the intent pi2 to the notification?
i am trying to get the notification to open a new activity class but can not get it done
You are using getBroadcast() to create your PendingIntent. Use getActivity() to create a PendingIntent that starts up an activity. Make sure that the Intent you put in the PendingIntent is for an activity, and make sure that the activity has its entry in the manifest.

How to start an activity using AlarmManager etc

I am trying to start code inside an activity at regular intervals using Alarm manager. I have looked at various examples on here but they have not really helped.
For testing purposes, all I am trying to do is pop up a toast at 10 second intervals, but nothing seems to be happening at all. Please help guys!
I have this in the manifest (also declarations for all three activities):
<receiver android:name=".receiver.AlarmReceiver"></receiver>
Code from main activity, in OnCreate:
//
// Setting up the Alarm Manager
//
Intent myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long timerInterval = 10 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timerInterval, pendingIntent);
//finish();
AlarmReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context," onRecieve() test" , Toast.LENGTH_LONG).show();
Intent scheduledIntent = new Intent(context, MyService.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
MyService.java:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
Toast.makeText(getBaseContext(),"test message.",
Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Your activity is not showing, because you are calling startActivity() on an Intent that identifies a Service. You should see warnings related to this in LogCat.
I humbly suggest that you use LogCat yourself, via the Log class, for logging background operations, rather than attempting to use a Toast.
test this code:
private void establecerAlarmaClick(int when){
AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivityAlarmita.this, MainActivityAlarmita.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivityAlarmita.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + when * 1000, pendingIntent);
}

notificationID cannot be resolved to a variable

I have just started studying Android, I have limited java knowledge but am semi capable with c/c++ objective C etc... I am currently working through a p2pwrox ebook called Beginning Android Application Development that I brought, however I am coming unstuck with the "Try it out: Display Notifications on the status bar" on pg73.
I have managed to write it all out sweet and am getting used to the android sdk and eclipse ide, however I have got this error in my NotificationActivity.java file shown below that I just don't know how to fix.
package com.androidtestingfun.www;
import android.app.Activity;
import android.os.Bundle;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class NotificationsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.btn_displaynotif);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
displayNotification();
}
});
}
protected void displayNotification()
{
//---PendingIntent to launch activity if the user selects this notification---
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID); //-----the second parameter here is getting an error
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.icon,
"Reminder: Meeting starts in 5 minutes",
System.currentTimeMillis());
CharSequence from = "System Alarm";
CharSequence message = "Meeting with customer at 3pm...";
notif.setLatestEventInfo(this, from, message, pendingIntent);
//---100ms delay, vibrate for 250ms, pause for 100ms and then vibrate for 500ms---
notif.vibrate = new long[] {100, 250, 100, 500};
nm.notify(notificationID, notif);//-----the first parameter here is getting an error
}
}
Any ideas that could hear me would be greatly appreciated, I have tried cleaning my build but that didnt do anything to help.
You do not have a variable called notificationID.
Add this variable to the class, see snippet example:
public class NotificationsActivity extends Activity {
private static final int notificationID = 1234;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// ........
}
protected void displayNotification()
{
//---PendingIntent to launch activity if the user selects this notification---
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.icon,
"Reminder: Meeting starts in 5 minutes",
System.currentTimeMillis());
CharSequence from = "System Alarm";
CharSequence message = "Meeting with customer at 3pm...";
notif.setLatestEventInfo(this, from, message, pendingIntent);
notif.vibrate = new long[] {100, 250, 100, 500};
nm.notify(notificationID, notif);
}
}

Categories

Resources