Calling non-static function inside a Handler

1

I'm developing a code in android studio where I get 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 another function, 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 I can call the function to generate the notification within the static handler method. I am a beginner in java, please explain in detail.

    
asked by anonymous 22.09.2017 / 22:25

1 answer

0

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

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

You have two possibilities:

  • Declare the Handler as non-static

    public Handler handler = ....
    
  • Declare the method GerarNotificacao() also static

    public static void GerarNotificacao(){...}
    
  • 23.09.2017 / 15:22