Notification when I receive message in the background

1

I'm developing an app that clients and drivers log, I wanted when my app was running in the background and when a customer sent a message, the driver received a notification, all the data is in an online bank and the system is login , registration etc is already ok, so how do I know if I received the message in the background and show that I received 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 oncreate it makes the request and in the onPostExecute it catches the result and puts everything in the string

    
asked by anonymous 18.12.2017 / 22:41

1 answer

1

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

This way you will receive changes to the database as they occur. This will prevent unnecessary delay and save battery power.

If you still want to use a database on your server. You can use some scheduling services , such as 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 code above will run every 1 minute approximately. This way you can execute the 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 the 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);
}
    
18.12.2017 / 23:48