Notification when I receive message in the background

Asked

Viewed 607 times

1

I’m developing an app that customers and drivers log in, I wanted when my app runs in the background and when a customer sends a message, the driver receives a notification, all the data is in an online bank and the system and login, registration etc is already ok, so, how do I know if I got the message in the background and show that I got it to the driver.

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

    showProgress(true);

    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();


    if(networkInfo != null && networkInfo.isConnected()) {

                url = ip;

                parametros = "mensagem=buscar";

                new SolicitaDados().execute(url);

    } else {
        Toast.makeText(getApplicationContext(), "Nenhuma conexão foi detectada", Toast.LENGTH_LONG).show();
    }
}


private void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        login.setVisibility(show ? View.VISIBLE : View.GONE);
        login.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                login.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        login.setVisibility(show ? View.VISIBLE : View.GONE);
        login.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

private class SolicitaDados extends AsyncTask<String, Void, String> {
    @Override
    protected  String doInBackground(String... urls) {

        return Conexao.postDados(urls[0], parametros);

    }

    @Override
    protected void onPostExecute(String resultado) {

        mensagem= resultado;

    }

In the above code in the oncreate it makes the request and in onPostExecute it picks the result and puts everything in the string

  • How you’re getting this message in the app?

  • I put when the driver opens the app he makes the request and receives a mailing list if it exists in the bank, but I wanted him to make this request from time to time in the background

  • Okay, I put the code part

1 answer

1


If you are not using the Firebase or another database, I recommend using them.

This way you will receive database changes when they occur. This will avoid unnecessary delay and save battery.


If you still want to use a database on your server. You can use some scheduling services, such as the Alarmmanager (Lollipop or lower) or Jobscheduler (Lollipop or above) to schedule tasks in your app.

Example with Jobschedule (Checks every 1 minute)

ComponentName componentName = new ComponentName(context, checkMessageJobService.class);

JobInfo jobInfo = JobInfo.Builder(context)
   .setBackoffCriteria(60*1000, BACKOFF_POLICY_LINEAR)
   .setRequiredNetworkType(NETWORK_TYPE_ANY)
   .build();

JobSchedule jobSchedule = (JobSchedule) context.getSystemService(JOB_SCHEDULER_SERVICE);
jobSchedule.schedule(jobInfo);

checkMessageJobService.java

public class checkMessageJobService extends JobService {
    @Override
    public boolean onStartJob(final JobParameters params) {

        /* Aqui você faz sua requisição com AsyncTask */

        // Retorne true para o serviço ser reagendado conforme o método setBackoffCriteria
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return true;
    }
}

The above code will run every 1 minute approximately. This way you can execute requests to check for new messages.


Example with Alarmmanager (Checks every 1 minute)

Intent intent = new Intent(this, checkMessageReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

if (alarmManager != null) {
    alarmManager.setRepeating(ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60 * 1000, alarmIntent);
}

checkMessageReceiver.java

public class checkMessageReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        /* Faça sua requisição aqui */
    }
}

The above code will run every 1 minute. This way you can execute requests to check for new messages.


Displaying notification

Notification notification = new NotificationCompat.Builder(context, "NewMessage")
        .setContentTitle("Nova mensagem de Fulano")
        .setContentInfo("Já está no caminho?")
        .setSmallIcon(R.mipmap.ic_launcher)
        .build();

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

if (notificationManager != null) {
    notificationManager.notify((int) System.currentTimeMillis(), notification);
}
  • Does this 1-in-1-minute update even occur in the background? And if not, how do I leave the app on in the background and doing this update?

  • It happens in the background yes. According to the documentation itself: O AlarmManager destina-se a casos em que você deseja que seu código de aplicativo seja executado em um horário específico, mesmo que seu aplicativo não esteja sendo executado.

  • In the case of Jobschedule, it will run the independent server the app is in the background or not. In the example I put, it is enough that the device has access to the internet to run the service indicated.

  • Man, thank you very much, I will implement here but I think it will work, thanks msm

  • @Valdeirpsr guy, in the example of Jobschedule, where add the first part of the code? I created the class, but the first part do not know where I add

  • @Valdeirpsr error occurs on this line: checkMessageJobService jobSchedule = (checkMessageJobService) this.getSystemService(JOB_SCHEDULER_SERVICE);

  • @Wotonsampaio What error? Can be added to Activity, Adapter etc.

  • @Valdeirpsr I moved here and it worked, however, it only runs one time, you would know me what would be the possible problem?

  • You are using Alarm or Job? Which version of Android are you testing?

  • @Valdeirpsr O job, I’m using version 7.0

  • @Wotonsampaio In API 24, use setPeriodic with the flexMillis. Also check on LogCat, in latest versions of Android, it limit the minimum time between 5 and 15 minutes.

  • @Valdeirpsr then n it is possible to do it with less d 5 minutes? Only at least from 5 in 5?

  • @Wotonsampaio I haven’t tested one in a few minutes. If you want an accuracy, use the AlarmManager. As I said in the reply, JS is an approximate time. But I will try to test and return something

  • @Valdeirpsr thank you, I’ll wait

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.