Problem with android notifications [duplicated]

0

Hello I would need help with notifications on android, I'm with an app that I need to send several notifications during the day, and I only get that if for example send three notifications I get the last, the first and second are ignored, I guess because I'm not doing the PendingIntents well, but I've already looked for many solutions and I really do not.

This is the method that goes into the OnReceive of the class that extends to Broadcast:

public void bigPicture (Context context, Uri alarmSound,Bitmap bitmapArray,CharSequence cs){

        Intent notificationIntent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context,100,notificationIntent,PendingIntent.FLAG_ONE_SHOT);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        int id = 1;
        int idMas = ++id;
        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
                context)
                .setSmallIcon(R.drawable.ic_notify)
                .setContentText(cs)
                .setSound(alarmSound)
                .setColor(context.getResources().getColor(R.color.colorPrimary))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmapArray));

        notificationManager.notify(idMas,mNotifyBuilder.build());
    }

And this other code goes into the activity in an onclick:

Calendar calendar1 = Calendar.getInstance();
                                calendar1.setTimeInMillis(System.currentTimeMillis());

                                Calendar calendar2 = Calendar.getInstance();
                                calendar2.setTimeInMillis(System.currentTimeMillis());

                                Calendar calendar3 = Calendar.getInstance();
                                calendar3.setTimeInMillis(System.currentTimeMillis());


                                calendar1.set(Calendar.HOUR_OF_DAY,15);
                                calendar1.set(java.util.Calendar.MINUTE,48);
                                calendar1.set(java.util.Calendar.SECOND,0);

                                calendar2.set(Calendar.HOUR_OF_DAY,15);
                                calendar2.set(java.util.Calendar.MINUTE,48);
                                calendar2.set(java.util.Calendar.SECOND,30);

                                calendar3.set(Calendar.HOUR_OF_DAY,15);
                                calendar3.set(java.util.Calendar.MINUTE,49);
                                calendar3.set(java.util.Calendar.SECOND,00);


                                int uniqueInt = new Random().nextInt(543254);


                                Intent intent1 = new Intent(Notificaciones_Activity.this,AlarmReceiver.class);
                                intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent1.setAction(Long.toString(System.currentTimeMillis()));


                                PendingIntent pendingIntent1 = PendingIntent.getBroadcast(Notificaciones_Activity.this,uniqueInt
                                        ,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
                                PendingIntent pendingIntent2 = PendingIntent.getBroadcast(Notificaciones_Activity.this,uniqueInt
                                        ,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
                                PendingIntent pendingIntent3 = PendingIntent.getBroadcast(Notificaciones_Activity.this,uniqueInt
                                        ,intent1,PendingIntent.FLAG_UPDATE_CURRENT);

                                AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
                                AlarmManager alarmManager2 = (AlarmManager) getSystemService(ALARM_SERVICE);
                                AlarmManager alarmManager3 = (AlarmManager) getSystemService(ALARM_SERVICE);

                                alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP,calendar1.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent1);
                                alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP,calendar2.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent2);
                                alarmManager3.setRepeating(AlarmManager.RTC_WAKEUP,calendar3.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent3);

If instead of setting setReapeating () I set setExact () if it works, but they jump
 old notifications out of time.

I hope your help, thank you.

    
asked by Ricersa 19.08.2017 в 18:21
source

3 answers

3

The problem is that you are putting the same ID to all notifications so they are overwritten.

int id = 1;
int idMas = ++id;

But id is always 1 and id is always 2. Try defining a static variable in the class:

private static final AtomicInteger atomicInteger = new AtomicInteger(0);

And then use it as id:

int id = atomicInteger.getAndIncrement();
    
answered by 21.08.2017 в 15:23
1

Use setExact . Try this code:

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

Intent i = ...

PendingIntent pi1 = PendingIntent.getBroadcast(Notificaciones_Activity.this, 1, i, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pi2 = PendingIntent.getBroadcast(Notificaciones_Activity.this, 2, i, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pi3 = PendingIntent.getBroadcast(Notificaciones_Activity.this, 3, i, PendingIntent.FLAG_UPDATE_CURRENT);

am.setExact(AlarmManager.RTC, calendar1.getTimeInMillis(), pi1);
am.setExact(AlarmManager.RTC, calendar2.getTimeInMillis(), pi2);
am.setExact(AlarmManager.RTC, calendar3.getTimeInMillis(), pi3);

Make sure that when you start to write the Calendar objects (calendar1, ...) select them from the pop-up window, do not write them completely.

To restart the Activity at 0 o'clock:

    @Override            
    protected void onResume() {
    super.onResume();
    AlarmManager am5 = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);
    Intent intent = new Intent(this, Notificaciones_Activity.class);

    Calendar cal5 = Calendar.getInstance();
    cal5.set(Calendar.HOUR_OF_DAY,00);
    cal5.set(Calendar.MINUTE,00);
    cal5.set(Calendar.SECOND,0);

    PendingIntent peIntent = PendingIntent.getActivity(this, 8, intent, PendingIntent.FLAG_ONE_SHOT);
    am5.set(AlarmManager.RTC, cal5.getTimeInMillis(), peIntent);
    }

You can add the following code so that past notifications are NOT sent:

long now = System.currentTimeMillis();
if (now <= calendar1.getTimeInMillis()) {
        am.setExact(AlarmManager ...
    }
    
answered by 19.08.2017 в 21:58
0

Thanks to your comments I got the notifications to be sent all, but I have more problems:

The first is that I need those notifications to be released when the device is reneged, for this I modified the xml manifest like this:

  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    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>

    <service
        android:name=".TestService"
        android:enabled="true"
        android:exported="true" />

    <receiver
        android:name=".BootStartUpReciever"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />

        </intent-filter>
    </receiver>

And with that I know that the broadCastReceiver restarts thanks to a Toast, but the notifications do not arrive when you restart the device.

The second problem is that the setReapeating () method causes old notifications to be displayed as soon as you restart the device and I would like that to not happen. The code related to notifications stayed like this:

public class MainActivity extends AppCompatActivity {

private Button boton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    boton = (Button) findViewById(R.id.id_bt);
    boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

  noty1();
        }
    });
}
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
Calendar calendar3 = Calendar.getInstance();


public  void noty1(){

    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();


    calendar1.set(java.util.Calendar.MINUTE,17);
    calendar1.set(java.util.Calendar.SECOND,0);

    calendar2.set(java.util.Calendar.MINUTE,18);
    calendar2.set(java.util.Calendar.SECOND,0);

    calendar3.set(java.util.Calendar.MINUTE,19);
    calendar3.set(java.util.Calendar.SECOND,0);

    Intent i = new Intent(MainActivity.this,BootStartUpReciever.class);


    PendingIntent pi1 = PendingIntent.getBroadcast(MainActivity.this, 1, i, PendingIntent.FLAG_CANCEL_CURRENT);
    PendingIntent pi2 = PendingIntent.getBroadcast(MainActivity.this, 2, i, PendingIntent.FLAG_CANCEL_CURRENT);
    PendingIntent pi3 = PendingIntent.getBroadcast(MainActivity.this, 3, i, PendingIntent.FLAG_CANCEL_CURRENT);

    am.setRepeating(AlarmManager.RTC,calendar1.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pi1);
    am.setRepeating(AlarmManager.RTC,calendar2.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pi2);
    am.setRepeating(AlarmManager.RTC,calendar3.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pi3);

   /* am.setExact(AlarmManager.ELAPSED_REALTIME, calendar1.getTimeInMillis(), pi1);
    am.setExact(AlarmManager.ELAPSED_REALTIME, calendar2.getTimeInMillis(), pi2);
    am.setExact(AlarmManager.ELAPSED_REALTIME, calendar3.getTimeInMillis(), pi3);*/
}

}

public class TestService extends Service {
public TestService() {
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
    // TODO Auto-generated method stub

    //Toast.makeText(getApplicationContext(), "Servicio onCreate",Toast.LENGTH_SHORT).show();
    super.onCreate();
}


@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    Toast.makeText(getApplicationContext(), "Service Destroy",Toast.LENGTH_SHORT).show();
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    showNotification();

    return TestService.START_REDELIVER_INTENT;
}
private static final AtomicInteger atomicInteger = new AtomicInteger(0);


private void showNotification(){



    NotificationManager mManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

    int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);

    int id = atomicInteger.getAndIncrement();


    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
            this.getApplicationContext())
            .setSmallIcon(R.drawable.ic_3d_rotation)
            .setSound(alarmSound)
            .setColor(this.getApplicationContext().getResources().getColor(R.color.colorPrimary))
            .setAutoCancel(true)
            //.setOnlyAlertOnce(true)
            .setStyle(new NotificationCompat.BigTextStyle().bigText("Texto"));

    mManager.notify(id,mNotifyBuilder.build());
    Toast.makeText(TestService.this,"showNotification",Toast.LENGTH_LONG).show();

    //  }


}

}

public class BootStartUpReciever extends BroadcastReceiver {

private static final String TAG = "RestartAppReceiver";

public BootStartUpReciever() {
}

@Override
public void onReceive(Context context, Intent intent) {
    // TODO: This method is called when the BroadcastReceiver is receiving

   Intent service = new Intent(context, TestService.class);
    context.startService(service);

}

}

In short, what I want is to be able to send several notifications each at a specific time, that these notifications are repeated daily, that when the user reboots the system, those notifications continue to work and when rebooting the device, no old notifications are shown. those that are to come.

I have never been so involved with any problem, the notifications take me head on for several weeks and I am far from finding the solution.

I would appreciate if someone could modify the errors found in the code. That surely will not be few ... Thanks.

    
answered by 31.08.2017 в 20:23