My Scenario is to show Greeting notification to my users even they are not using the app. Below code is working fine if the open is opened or minimized. But, I want to show the notification in morning even though the user did not open the application.
Main Activity:
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} //end onCreate
}
My Receiver Class:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
/*Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);*/
try{
Utils.generateNotification(context);
}catch(Exception e){
e.printStackTrace();
}
}
}
Utils Class:
public class Utils {
public static NotificationManager mManager;
#SuppressWarnings("static-access")
public static void generateNotification(Context context){
mManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent intent1 = new Intent(context,MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context,0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
}
My Alarm Service:
public class MyAlarmService extends Service {
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Next Activity:
public class NextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
A few things you need to do here. If the user force closes the app, you need to ensure that you start your service with START_STICKY so that the service restarts when the app is force closed.
In order to get the Service to start when the user has rebooted their phone, you will need your BroadcastReceiver to receive BOOT_COMPLETED which will then start the service.
Your service will then set the Alarm as per normal. You will need to store the time of the alarm you want to set somewhere. I use SharedPrefs (PreferenceManager.getDefaultSharedPreferences(getApplicationContext());) but I'm sure there are better methods.
Related
i have a probleme with BroadcastReceiver & Service in my application
.......
i have an
* activity ( MainActivity )
* service ( NotifyService )
* Receiver ( NotifyBroadcast )
service start from activity and then the receiver start from service
everything is good when my app was open , but when i clear it (destroyed) ,receiver stop doing its job ( just a toast message )
here is my code :
MainActivity ..
if( !NotifyService.ServiceIsRun){
NotifyService.ServiceIsRun=true;
startService(new Intent(this, NotifyService.class));
}
NotifyService ..
public class NotifyService extends Service {
public static boolean ServiceIsRun=false;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer t = new Timer();
if(ServiceIsRun){
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.e("broadService", "hello from Service"+i +"new :"+lastnew +"article :"+lastarticle);
i++;
Intent intent = new Intent( "com.latestBabiaNews" );
sendBroadcast(intent);
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
20000);
}
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
NotifyBroadcast ..
public class NotifyBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
if (intent.getAction().equalsIgnoreCase("com.latestBabiaNews")){
Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
}
}
}
And in my Manifest ..
<service android:name=".NotifyService"></service>
<receiver android:name=".NotifyBroadcast">
<intent-filter>
<action android:name="com.latestBabiaNews"></action>
</intent-filter>
</receiver>
..........
finally i can show the Toast message when app was app was opened , but when i clear it i can't show anything !
To prevent service kill use it as foreground service. To perform it as foreground use this (inside Service class):
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
fg();
}
private void fg() {
Intent intent = launchIntent(this);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle(getResources().getString(R.string.app_alias))
.setContentText(getResources().getString(R.string.app_alias))
.setContentIntent(pIntent);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(someicon);
} else {
mBuilder.setSmallIcon(someicon);
mBuilder.setColor(somecolo);
}
noti = mBuilder.build();
noti.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
startForeground(_.ID, noti);
}
to stop, this:
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopForeground(true);
}
EDIT
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class MyBroadCast extends WakefulBroadcastReceiver {
public static final String INTENT_FILTER = "ru.ps.vm.BRTattva";
#Override
public void onReceive(Context ctx, Intent intent) {
Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
}
}
To start use this:
public static void startbyalarm(Context ctx, long nexttime, boolean autoStart, SharedPreferences settings) {
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
Intent intent = new Intent(MyBroadcastReceiver.INTENT_FILTER);
if (autoStart)
intent.putExtra(_.AUTOLOADSERVICE,true);
PendingIntent pi = PendingIntent.getBroadcast(ctx, _.intentalarmindex, intent, PendingIntent.FLAG_CANCEL_CURRENT);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion < android.os.Build.VERSION_CODES.KITKAT){
am.set(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
if (currentapiVersion < android.os.Build.VERSION_CODES.M) {
am.setExact(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
am.setExactAndAllowWhileIdle(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
}
}
//or use repeating:
//am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}
I want to check notifications from background receivers or services.
The notification is shown, but it should also invoke an activity.
MainActicityClass
Here I have created the alarm class which would call broadcast manager at specific interval
public class MainActivity extends AppCompatActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = this;
Intent alarm = new Intent(this.context, AlarmReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this.context, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if(alarmRunning == false) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.context, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent);
}
}
Alarm Receiver Class
This is the broadcast class to invoke from back ground
public class AlarmReceiver extends BroadcastReceiver {
public AlarmReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, MyListenerServices.class);
context.startService(background);
}
}
MyListener
This is subclass of notificationlistener services
Its reads any incoming notification but unable to read the notification from inactive class
Integrate class read any kind of incoming notification from background
public class MyListenerServices extends NotificationListenerService{
public MyListenerServices() {
}
private boolean isRunning;
private Context context;
private Thread backgroundThread;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
public void run() {
// Do something here
Log.d("MSG", "ServiceRunning");
StatusBarNotification[] statusBarNotifications = getActiveNotifications();
Log.d("MSG", "New Object2 "+statusBarNotificationsArray);
if (statusBarNotifications.length > 0) {
Log.d("MSG", "New Object "+statusBarNotifications.length);
//
Intent i = new Intent(context, AutomaticCameraActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
// }
// }catch (Exception e){
// Log.d("MSG",e.getMessage());
}
stopSelf();
}
};
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Notification mNotification=sbn.getNotification();
Log.v("MSG"," Notification"+ mNotification);
}
#Override
public void onDestroy() {
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isRunning) {
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
}
Any help would be appreciated
Thanks in advance
Create a pending intent
Intent resultIntent = new Intent(this, ResultActivity.class);
//Change ResultActivity by your activity you want invoke
...
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
More information in Create Notification
In my Application I have Multiple events for every event I need to create one UILocalNotification for example like I want to say wishes on Fathers day,Mothers and some festivals. So I already I have the specific date now I want to fire it on the particular day please how to do this. I have already done for single UILocalNotification. Now I need for multiple fire dates.
If I comment the date it's firing on particular time. Now date with time is not working.
Now problem how to add multiple dates and time in same activity I want to fire the notifications.
Can anyone please help me.
MyView class
public class MyView extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar firingCal = Calendar.getInstance();
firingCal.set(Calendar.MONTH, 7);
firingCal.set(Calendar.YEAR, 2014);
firingCal.set(Calendar.DAY_OF_MONTH, 9);
firingCal.set(Calendar.HOUR_OF_DAY, 16);
firingCal.set(Calendar.MINUTE, 35);
firingCal.set(Calendar.SECOND, 0);
// MyView is my current Activity, and AlarmReceiver is the
// BoradCastReceiver
Intent myIntent = new Intent(MyView.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyView.this,
0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
/*
* The following sets the Alarm in the specific time by getting the long
* value of the alarm date time which is in calendar object by calling
* the getTimeInMillis(). Since Alarm supports only long value , we're
* using this method.
*/
alarmManager.set(AlarmManager.RTC_WAKEUP, firingCal.getTimeInMillis(),
pendingIntent);
}
}
MyAlarmService class
public class MyAlarmService extends Service
{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
I a trying to get a notifcation to fire at a specific time. I am using AlarmManager and BroadcastReceiver for this.In main activity AlarmManager calls the BroadcastReceiver but I cannot get the notification to fire from that class. It is giving me an error in the line
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
I don't know what to do.
Here's my code
MainActivity
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
long current_time=System.currentTimeMillis();
Calendar time9=Calendar.getInstance();
time9.set(Calendar.HOUR_OF_DAY,16);
time9.set(Calendar.MINUTE,30);
time9.set(Calendar.SECOND,0);
Intent intent=new Intent(MainActivity.this,ScheduledReciever.class);
PendingIntent pintent=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
long interval = 60 * 1000; //
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,time9.getTimeInMillis(), interval, pintent);
finish();
}}`
BroadcastReciever
`public class ScheduledReciever extends BroadcastReceiver {
static final int uniqueId=1234;
NotificationManager nm;
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
String body="i hope this works";
String title="trying";
Intent it=new Intent(context,SecondActivity.class);
PendingIntent pit=PendingIntent.getActivity(context, 0, it,0);
Notification n=new Notification(R.drawable.att,body,System.currentTimeMillis());
n.setLatestEventInfo(context, title, body, pit);
n.defaults=Notification.DEFAULT_ALL;
nm.notify(uniqueId, n);
}
}
Use the context passed:
nm=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
instead of:
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
I have app which in specific time start notification in status bar.But when that time elapsed, every time when I launch the app he start the notification again.
Thanks in advance.
Here is the code:
Activity: MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//notifications with solve problem
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 30 );
calendar.set(Calendar.SECOND, 0);
calendar.getTimeInMillis();
long current_time = System.currentTimeMillis();
long limit_time = calendar.getTimeInMillis();
if (current_time > limit_time) {
//nothing
} else {
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
}
}
Activity: MyReceiver
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
Activity: MyAlarmService
public class MyAlarmService extends Service{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"Run this app", System.currentTimeMillis() );
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "Horoscope", "Run this app", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
I solve the problem with this post - Notification at specific time
use
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), SYNC_REPEAT_MILLSECONDS, pendingIntent);
instead of
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);