Handlers inside thread android studio not called looper .Prepare()

1.1k views Asked by At

This method getting called again and again i.e BatteryLevelmethodon() when declared in onCreate(),onResume() and onDestroy() in main activity and the button on_off is clicked automatically.

public void BatteryLevelmethodon()
{
    final  Handler handler=new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
           Log.v(TAG,"in BatteryLevelmethod");
            on_off.performClick();
            handler.postDelayed(this, 1000);
        }
    },1000);

}

But i want that to be clicked even though the app is killed so i am calling this method BatteryLevelmethodon() in Service class in Onstart command so when we start the Service with the click of a another starts_service_button the service class executes BatteryLevelmethodon()

import android.app.Service;
import android.content.ClipData;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import static android.content.ContentValues.TAG;
import static com.light.intensity.bluetooth.le.R.id.on_off;

public class Battery_Service extends Service {
final class BatteryThread implements Runnable
{
    int serviceid;
    BatteryThread(int serviceid)
    {
        this.serviceid=serviceid;
    }

    @Override
    public void run()
    {
          synchronized (this)
        {

          try {
                wait(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();

            }
            new DeviceControlActivity().BatteryLevelmethodon();
        }
          stopSelf(serviceid);

    }
}


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
       Thread thread=new Thread(new BatteryThread(startId));
        thread.start();
        return START_STICKY;
    }

    @Override
    public void onDestroy()
    {
        Toast.makeText(this,"Battery_service_destroy_command",Toast.LENGTH_LONG).show();
        super.onDestroy();
    }
}

But i am getting the below error log:

image

1

There are 1 answers

0
Abdur Rahman On

Call looper.prepare() in the run() function.

public void BatteryLevelmethodon()
{
    final  Handler handler=new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
           looper.prepare()
           Log.v(TAG,"in BatteryLevelmethod");
            on_off.performClick();
            handler.postDelayed(this, 1000);
        }
    },1000);

}

If it didn't work try to put looper.prepare() in some other place ( Sorry I didn't reemeber where it actually be put ). But you can try the above code. I hope it's the rite placement.