Я написал 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"/>
Так что я ожидаю, что эта служба должна работать, пока я использую другие приложения поверх своего приложения. Но пока я нажимаю кнопку «Домой» (не убивая приложение), через некоторое время сервис разрушается. Есть ли какое-то решение для этого?