The same push notification keeps appearing whenever I reopen my apps although i have already cleared the notification in the notification bar. Secondly how do I implement a service so that my apps can receive notification although the apps is closed.
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF, MODE_PRIVATE);
String id = sharedPreferences.getString(Constants.UNIQUE_ID, null);
Firebase firebase = new Firebase(Constants.FIREBASE_APP + id);
firebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String msg = snapshot.child("msg").getValue().toString();
if (msg.equals("none"))
return;
showNotification(msg);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: ", firebaseError.getMessage());
}
});
return START_STICKY;
}
private void showNotification(String msg){
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
Intent intent = new Intent(NotificationListener.this,ViewRecord.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("Notifier");
builder.setContentText(msg);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder.setAutoCancel(true);
notificationManager.notify(1, builder.build());
}
my service code as below. and i call the service at onCreate function in the 1st activity..
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
}
}
Posting this as answer since code in comment wud make it look unstructured
isServiceStarted
public class MainActivity extends AppCompatActivity {
private SharedPreferences servicePref;
private boolean isServiceStarted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
servicePref = getSharedPreferences("servicePref", MODE_PRIVATE);
isServiceStarted = servicePref.getBoolean("isServiceStarted", false);
if (!isServiceStarted) {
startService(new Intent(this, MyService.class));
servicePref.edit().putBoolean("isServiceStarted",true).apply();
}
}
and in ur MyService.class inside onStop method do this without fail.
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
// save value as false when service gets destroyed so as to start again when u open the app
getSharedPreferences("servicePref", MODE_PRIVATE).edit().putBoolean("isServiceStarted",false).apply();
}
}
override the onStartCommand() method and then return START_STICKY.
Related
I am using a service to start the mediaplayer as soon as the notification is shown and then stop the service when the action button is pressed. The service starts fine. But the service doesn't stop on clicking the action button.
This is my notification builder
public NotificationCompat.Builder getReminderNotification(String title,String message,PendingIntent intent1){
return new NotificationCompat.Builder(getApplicationContext(),reminderChannelID)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.ic_medicine)
.setColor(getResources().getColor(R.color.colorPrimary))
.setOngoing(true)
.addAction(R.drawable.ic_arrow_back,"OK",intent1);
}
public void cancelNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(1); // Notification ID to cancel
}
public void startMyService(){
startService(new Intent(this, TimerService.class));
}
public void stopMyService(){
stopService(new Intent(this,TimerService.class));
}
This is my reminder receiver:
public class ReminderReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
Intent newIntent = new Intent(context,DismissReminderReceiver.class);
newIntent.putExtra("action","stop");
PendingIntent intent1 = PendingIntent.getBroadcast(context,0,newIntent,0);
Bundle extras = intent.getExtras();
String title=extras.getString("title");
String message=extras.getString("message");
NotificationCompat.Builder builder = notificationHelper.getReminderNotification(title, message,intent1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context.getApplicationContext(),TimerService.class));
}else {
notificationHelper.startMyService();
}
notificationHelper.getManager().notify(1, builder.build());
}}
This is my code to dismiss the notification
public class DismissReminderReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Here");
Bundle extras = intent.getExtras();
String action = extras.getString("action");
System.out.println(action);
if (action.equals("stop")) {
NotificationHelper notificationHelper = new NotificationHelper(context);
notificationHelper.stopMyService();
notificationHelper.cancelNotification();
}
}}
And this is my service:
public class TimerService extends Service {
public Context context = this;
public Handler handler = null;
public Runnable runnable = null;
MediaPlayer mediaPlayer;public TimerService(){}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
System.out.println("Service Started");
mediaPlayer=MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
};
handler.postDelayed(runnable,0);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
handler.removeCallbacks(runnable);
mediaPlayer.stop();
}}
I also don't see where you register the receiver - if you're doing it in the manifest, make sure it's there with a matching action (and the receiver stanza is there to begin with).
this code get request from server and do some thing. i want when app is closed get request and show it by notification. i can get message from firebase and show it but this is not something that i want
MyActivity
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
public class MyActivity extends ActionBarActivitiy implements AsyncTaskCompleteListener{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
.
.
.
}
private void displayFirebaseRegId() {
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
String regId = preferenceHelper.getSessionToken();
if (!TextUtils.isEmpty(regId))
}
private void subscribeToPushService() {
FirebaseMessaging.getInstance().subscribeToTopic("news");
String token = FirebaseInstanceId.getInstance().getToken();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
protected void onDestroy() {
}
#Override
public void onTaskCompleted(String response, int service) {
super.onTaskCompleted(response, service);
switch (service) {
case MyValues.Service.REQUEST_NEW:
// addNotification();
...
if (requestId == MyValues.NO_REQUEST) {
addNotification();
addNewFragment(new myFragment(), false,
MyValues.REQUEST_, true);
} else {
...
}
break;
}
}
ActionBarActivitiy
abstract public class ActionBarActivitiy extends AppCompatActivity implements OnClickListener , AsyncTaskCompleteListener
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(MyApplication.applicationContext)
.setSmallIcon(R.mipmap.ic_cl)
.setContentTitle("Notifications get request")
.setContentText("This is get request notification");
Intent notificationIntent = new Intent(MyApplication.applicationContext, MainActivity.class);
PendingIntent contentIntent =
PendingIntent.getActivity(MyApplication.applicationContext, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
builder.setSound(Uri.parse("android.resource://"
+ MyApplication.applicationContext.getPackageName() + "/" + R.raw.sfx_counter_loop));
// builder.setOngoing(true);
try {
builder.setWhen(System.currentTimeMillis());
builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
builder.setLights(Color.RED, 3000, 3000);
}catch (Exception e){
}
// Add as notification
NotificationManager manager = (NotificationManager)
MyApplication.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
#Override
public void onTaskCompleted(String response, int service) {
}
....
}
interface AsyncTaskCompleteListener
public interface AsyncTaskCompleteListener
{
void onTaskCompleted(String response, int service);
}
You can use A service, An alarm manager to do so.
Schedule a timer tat will run the service. The service will fetch the data and then show the notification. You can also use IntentService for that so as to free up your main thread.
Edit
Here is an link for alarm manager :
https://developer.android.com/training/scheduling/alarms.html
and IntentService :
https://developer.android.com/training/run-background-service/create-service.html
Also, to call certain task before your app gets close, call your method in onStop right before calling super.
I have created a background service that checks for value changes in my Firebase Database and sends a Notification if there are any changes. The service notifies for value changes as long as the app is running. When I close the app, I stop receiving notifications. My onStartCommand contains a new thread comprising of a firebase value event listener. As the value changes
I call sendNotification method. Here's my complete service class:
public class NotifyService extends Service
{
Firebase mRef;
#Override
public IBinder onBind(Intent p1)
{
// TODO: Implement this method
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(this,"service started",Toast.LENGTH_LONG).show();
Firebase.setAndroidContext(this);
mRef= new Firebase(myURL);
Runnable run = new Runnable(){
#Override
public void run(){
mRef.child("politics").child("story1").child("title").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot p1)
{
// TODO: Implement this method
String data = (String)p1.getValue();
sendNotification(data);
}
#Override
public void onCancelled(FirebaseError p1)
{
// TODO: Implement this method
}
});
mRef.child("sports").child("story1").child("title").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot p1)
{
// TODO: Implement this method
String data = (String)p1.getValue();
sendNotification(data);
}
#Override
public void onCancelled(FirebaseError p1)
{
// TODO: Implement this method
}
});
mRef.child("science").child("story1").child("title").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot p1)
{
// TODO: Implement this method
String data = (String)p1.getValue();
sendNotification(data);
}
#Override
public void onCancelled(FirebaseError p1)
{
// TODO: Implement this method
}
});
mRef.child("gossip").child("story1").child("title").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot p1)
{
// TODO: Implement this method
String data = (String)p1.getValue();
sendNotification(data);
}
#Override
public void onCancelled(FirebaseError p1)
{
// TODO: Implement this method
}
});
}};
Thread serviceThread = new Thread(run);
serviceThread.start();
return Service.START_STICKY;
}
#Override
public void onDestroy()
{
Toast.makeText(this, "activity destroyed", Toast.LENGTH_LONG).show();
}
public void sendNotification(String title){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(NotifyService.this);
mBuilder.setSmallIcon(R.drawable.nicon);
mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.nlicon));
mBuilder.setAutoCancel(true);
mBuilder.setContentTitle("New Story")
.setContentText(title);
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(NotifyService.this);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify((int)System.currentTimeMillis(), mBuilder.build());
}
}
I call it with
Intent i = new Intent(this, NotifyService.class);
startService(i);
What is it that doesn't let the notifications appear after app exit. I suspect it is something wrong with the notification method.
My service was apparently running in settings, but it was actually getting killed after the app was killed.
To keep your service running, instead of
startService(new Intent(this, MyService.class));
use this:
Intent serviceintent =new Intent(this, MyService.class);
PendingIntent pendingintent =PendingIntent.getService(this,0, serviceintent,0);
AlarmManager alarm =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingintent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),5000, pendingintent);
This ensures your service keeps using AlarmManager every 5 seconds, so no matter what happens, the service will keep running.
I'm trying to create a Service that will run in the background and put a notification in the status bar every 10 sec (for testing only).
I reviewed many posts here but still was unable to find help.
For some reason, when I call the AlarmManager to run the Service, the application crushing.
Please advice.
This is the "Main Class" code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_screen);
MyAlarmManager.scheduleAlarms(this);
This is the AlarmManager code:
public class MyAlarmManager extends BroadcastReceiver {
private static final int PERIOD=1000*10; // 15 minutes
private static final int INITIAL_DELAY=500; // 5 seconds
#Override
public void onReceive(Context ctxt, Intent i) {
scheduleAlarms(ctxt);
}
static void scheduleAlarms(Context ctxt) {
AlarmManager mgr= (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(ctxt, MyService.class);
PendingIntent pi=PendingIntent.getBroadcast(ctxt, 0, i, 0);
Log.i("My Log", "Alarm Manager Started ......... Alarm Manager Started");
mgr.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + INITIAL_DELAY, PERIOD, pi);
}
}
This is the "Service" code:
public class MyService extends Service {
private NotificationManager mNM;
private final IBinder mBinder = new LocalBinder();
private int NOTIFICATION = R.string.service_started;
public class LocalBinder extends Binder {
SecRssService getService() {
return SecRssService.this;
}
}
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Log.i("My Log", "Received onCreate Service !!!!!!!!!!!!!!!!!!!");
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("My Log", "Received onStartCommand id " + startId + ": " + intent);
Toast.makeText(this, R.string.service_started, Toast.LENGTH_SHORT).show();
showNotification();
// This service will continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}
#Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(NOTIFICATION);
Toast.makeText(this, R.string.service_stopped, Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private void showNotification() {
CharSequence text = getText(R.string.service_started);
Notification noti = new Notification.Builder(getBaseContext())
.setContentTitle(getText(R.string.noto))
.setContentText("Test Notification ON")
.setSmallIcon(R.drawable.ic_launcher)
.build();
}
}
This is my Log
08-02 11:09:48.872: E/AndroidRuntime(9550): Caused by: java.lang.ClassCastException: com.homeapps4u.sec_ticker_rss.MyService cannot be cast to android.content.BroadcastReceiver
08-02 11:09:48.872: E/AndroidRuntime(9550): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2400)
08-02 11:09:48.872: E/AndroidRuntime(9550): ... 10 more
Please advise my where I'm wrong.
Thanks a lot.
Thanks, I should have used:
PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);
On MyAlarmManager.
I need to be able to start chronometer, then close activity, after that through notifications, back to that activity, and see the right time in chronometer.
What I've Done
A part of my Activity:
public void doClick(View target)
{
switch(target.getId())
{
case R.id.buttonStart:
{
Mchronometer.setBase(SystemClock.elapsedRealtime());
Mchronometer.start();
Intent intent = new Intent(RecentActivity.this, ChronometerService.class);
intent.putExtra("task_name",task_name);
intent.putExtra("task_id",task_id);
intent.putExtra("ellapsedTime",Mchronometer.getBase());
Log.d("base",""+Mchronometer.getBase());
startService(intent);
break;
}
case R.id.buttonStop:
{
stopService(new Intent(RecentActivity.this, ChronometerService.class));
Mchronometer.stop();
Mchronometer.setBase(SystemClock.elapsedRealtime());
break;
}
case R.id.button3:
{
break;
}
}
}
A part of my Service:
public class ChronometerService extends Service {
private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");
private NotificationManager notificationMgr;
private int task_id;
private long ellapsedTime;
#Override
public void onCreate() {
super.onCreate();
notificationMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
String task_name =intent.getExtras().getString("task_name");
task_id =intent.getExtras().getInt("task_id");
ellapsedTime = intent.getExtras().getLong("ellapsedTime");
Log.d("servicebase",""+ellapsedTime);
displayNotificationMessage(task_name);
new Thread(myThreads, new ServiceWorker(),"ChronometerService").start();
return START_STICKY;
}
private class ServiceWorker implements Runnable {
public void run() {
}
}
#Override
public void onDestroy()
{
myThreads.interrupt();
notificationMgr.cancelAll();
super.onDestroy();
}
public IBinder onBind(Intent intent) {
return null;
}
public void displayNotificationMessage(String message){
Notification notification = new Notification(R.drawable.emo_im_winking,message,System.currentTimeMillis());
notification.flags = Notification.FLAG_NO_CLEAR;
Intent intent = new Intent(this, RecentActivity.class);
intent.putExtra("task_id", task_id);
intent.putExtra("ellapsedTime",ellapsedTime);
Log.d("servicebase1",""+Long.toString(ellapsedTime));
PendingIntent contentintent = PendingIntent.getActivity(this,0,intent,0);
notification.setLatestEventInfo(this,"ChronometerService",message,contentintent);
notificationMgr.notify(0, notification);
}
}
I tried to send a message from activity to a service, which contains elapsed information.
If I started it first on my device (after system load) it's works right, but when I launch it again. The activity receives wrong message. It receives the time of the first service launched on the device.
As you can see I also send one more variable, and activity reads it correctly.
I've found a solution to my question.
It's simple.
It's needed to use flag(PendingIntent.FLAG_UPDATE_CURRENT)
PendingIntent contentintent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
And it's work fine.