Android后台服务自动关闭

问题描述 投票:-1回答:1

我已经编写了一个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 android-service background-service
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.