后台服务自动关闭

background service getting closed automatically

我写了一个 android 后台服务,它将在按钮单击时启动,并应在另一个按钮单击时停止。我的服务机构是

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();

            }
        }
    };

}

我是这样启动服务的

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

并像这样结束服务

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

在清单文件中,我声明了服务

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

所以我的期望是当我在我的应用程序上使用其他应用程序时,该服务应该 运行。但是当我按下主页按钮(不是杀死应用程序)一段时间后服务被破坏了。有解决办法吗?

在 Android 8.0(Oreo,API 26)或更高版本中,当应用程序本身不在前台时,系统会对 运行 后台服务施加一些新限制。有关这些限制的详细信息,请参阅 Background services and API 26