Calling non-static function inside a Handler

Asked

Viewed 118 times

1

I’m developing a code in android studio in which I receive data through a buetooth transmission. The data goes to a function called Handler, which is Static.

public static Handler handler = new Handler() {
     @Override
    public void handleMessage(Message msg) {

         Bundle bundle = msg.getData();
         byte[] data = bundle.getByteArray("data");
         String dataString = new String(data);

         if (dataString.equals("---N"))
             statusMessage.setText("Erro de conexão.");
         else if (dataString.equals("---S"))
             statusMessage.setText("Conectado.");

         //GerarNotificacao();

     }
};

Within this Handler function, I want to call a function Oura, which would generate a notification whenever any data was received via bluetooth. However, when I try to call the function the program does not recognize it.

public void GerarNotificacao(){

    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    PendingIntent p = PendingIntent.getActivity(this, 0, new Intent(this, ActTelaUsuarios1.class), 0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setTicker("Ticker Texto")
            .setContentTitle("Titulo")
            .setContentText("Texto")
            .setSmallIcon(R.mipmap.logo_riscos)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.logo_sem_fundo));

    builder.setContentIntent(p);

    Notification n = builder.build();
    nm.notify(R.mipmap.ic_launcher, n);
}

I would like to know how to call the function to generate the notification within the Static Handler method. I am beginner in java, please explain in detail.

1 answer

0

You are calling a non-static method in a static context.

The field Handler handler is declared static, it can be used without there being an instance of the class where it was declared.
On the other hand the method GerarNotificacao(), that is not static, "only exists" if there is an instance.

Has two possibilities:

  1. Declares Handler to be non-static

    public Handler handler = ....
    
  2. Declares the method GerarNotificacao() also static

    public static void GerarNotificacao(){...}
    

Browser other questions tagged

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