-1

I have written an android background service, which will start on button click and should stop on another button click. My service body is

public class BatteryServices extends Service {

    int on;
    int off;
    int deviceStatus;
    IntentFilter intentfilter;
    static int batteryLevel;
    String mDeviceAddress;
    public String notyTxt="";
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        try {
            on = intent.getIntExtra("on", 0);
            off = intent.getIntExtra("off", 100);
            mDeviceAddress = intent.getStringExtra("address");
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        if (on > 0)
            notyTxt = "Plug will turn off at: " + off + "% and will turn on at: " + on + "%";
        else if (off > 0)
            notyTxt = "Overnight charge running. Battery will turn off at: " + off + "%";
        Log.d("notify ", notyTxt);
        try {
            SelectOperation.notifyText.setText("" + notyTxt);
            NormalbatteryOn_OFF.backgroundLayout.setBackgroundColor(Color.parseColor("#BEC4C4"));
            NormalbatteryOn_OFF.serviceTxt.setText(notyTxt);
            NormalbatteryOn_OFF.serviceTxt.setVisibility(View.VISIBLE);
            NormalbatteryOn_OFF.cbOverNight.setEnabled(false);
            NormalbatteryOn_OFF.offpercenedittext.setVisibility(View.GONE);
            NormalbatteryOn_OFF.offpercentageText.setText("" + off);
            NormalbatteryOn_OFF.offpercentageText.setVisibility(View.VISIBLE);
            NormalbatteryOn_OFF.onpercenedittext.setVisibility(View.GONE);
            NormalbatteryOn_OFF.onpercentageText.setText("" + on);
            if (on > 0)
                NormalbatteryOn_OFF.onpercentageText.setVisibility(View.VISIBLE);
            NormalbatteryOn_OFF.activatebutton.setVisibility(View.GONE);
            NormalbatteryOn_OFF.change.setVisibility(View.VISIBLE);
            NormalbatteryOn_OFF.onoff_btn.setVisibility(View.GONE);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        registerReceiver(broadcastreceiver, intentfilter);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(), "Service Closed", Toast.LENGTH_SHORT).show();
        SelectOperation.notifyText.setText("");
        NormalbatteryOn_OFF.serviceTxt.setVisibility(View.GONE);
        SharedPreferences.Editor editor = NormalbatteryOn_OFF.preferences.edit();
        editor.putString("serviceCheck","");
        editor.apply();
       try {
           NormalbatteryOn_OFF.backgroundLayout.setBackgroundColor(Color.parseColor("#FCE4EC"));
           NormalbatteryOn_OFF.cbOverNight.setEnabled(true);
           NormalbatteryOn_OFF.offpercenedittext.setVisibility(View.VISIBLE);
           NormalbatteryOn_OFF.offpercentageText.setVisibility(View.GONE);
           NormalbatteryOn_OFF.onpercenedittext.setVisibility(View.VISIBLE);
           if (on>0){
               NormalbatteryOn_OFF.onpercentageText.setVisibility(View.GONE);
           }
           NormalbatteryOn_OFF.activatebutton.setVisibility(View.VISIBLE);
           NormalbatteryOn_OFF.change.setVisibility(View.GONE);
           NormalbatteryOn_OFF.onoff_btn.setVisibility(View.VISIBLE);
           NormalbatteryOn_OFF.id_ontextview.setVisibility(View.VISIBLE);
       } catch (NullPointerException e){
           e.printStackTrace();
       }
        unregisterReceiver(broadcastreceiver);
    }

    //Battery Percentage.
    private BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            batteryLevel = (int) (((float) level / (float) scale) * 100.0f);
            final String action = intent.getAction();
            Log.e("battery status","status"+deviceStatus);

            try {
                if (batteryLevel >= off) {
                    MyAppApplication.getBLeService().ON_OFF_Logic("smpoff");
                    if (on==0){
                        final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

                        SharedPreferences.Editor editor = NormalbatteryOn_OFF.preferences.edit();
                        editor.putString("serviceCheck","");
                        editor.apply();
                        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
                        homeIntent.addCategory( Intent.CATEGORY_HOME );
                        homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(homeIntent);
                        final Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (deviceStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
                                    if (mBluetoothAdapter.isEnabled()) {
                                        mBluetoothAdapter.disable();
                                        System.exit(0);
                                    }
                                }
                            }
                        }, 5000);

                    }
                }
                if (batteryLevel <= on)
                    MyAppApplication.getBLeService().ON_OFF_Logic("smpon");
            } catch (Exception e){
                e.printStackTrace();
            }

            if (deviceStatus == BatteryManager.BATTERY_STATUS_DISCHARGING){
                Toast.makeText(getApplicationContext(),"Charger disconnected",Toast.LENGTH_SHORT).show();
            }
            if (deviceStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
                 Toast.makeText(getApplicationContext(), "Charger connected", Toast.LENGTH_SHORT).show();

            }
        }
    };

}

I am starting the service like this

startService(new Intent(getApplicationContext(), BatteryServices.class).putExtra("on",0).putExtra("off",Integer.parseInt(offpercenedittext.getText().toString())).putExtra("address",mDeviceAddress));

And ending service like this

stopService(new Intent(getApplicationContext(),BatteryServices.class));

in the manifest file, I declared the service

<service android:name=".battery_onoff.BatteryServices"
            android:enabled="true"/>

So my expectation is this service should run while I am using other applications over my app. But while I am pressing the home button( Not killing the app) after some time service is getting destroyed. Is there any solution for that?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • share your stacktrace please no service will get killed by itself unless the OS does it that's a know issue with many devices – Mr. Patel Mar 27 '20 at 06:57
  • Thanks for your response. Below is my stcktrace 2020-03-27 12:41:33.634 11161-11305/com.smartplugapp E/BluetoothLeService: onCharacteristicChanged 2020-03-27 12:41:35.095 11161-11161/com.smartplugapp D/InputTransport: Input channel constructed: fd=78 2020-03-27 12:41:35.096 11161-11161/com.smartplugapp D/ViewRootImpl@c2cb40[Toast]: setView = android.widget.LinearLayout{5e3a79 V.E...... ......I. 0,0-0,0} TM=true MM=false 2020-03-27 12:41:35.124 11161-11161/com.smartplugapp D/ViewRootImpl@c2cb40[Toast]: Relayout returned: old=[0,55][720,1436] new=[235,1247][485,1324] result=0x7 surface={tr – Prithwi Chanda Mar 27 '20 at 07:13

1 Answers1

1

In Android 8.0 (Oreo, API 26) or higher, the system imposes some new restrictions on running background services when the app itself isn't in the foreground. For details about these restrictions, see Background services and API 26.

Amirhosein
  • 4,266
  • 4
  • 22
  • 35