我尝试停止获取服务状态并在运行时停止它。 即使我使用How to check if a service is running on Android?
但在停止我的服务后,我重新开始,它一直运行。 这是我的代码:
public class Sauvegarde_Mail extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.sauvauto_layout_boitemail);
final Button byActiver = (Button)findViewById(R.id.btactiver);
Button byDesactiver = (Button)findViewById(R.id.btdesactiver);
byActiver.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
BoitedialogMailEdit();
}
});
byDesactiver.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(isMyServiceRunning()==true){
stopService(new Intent(getApplicationContext(), MyServiceSauvAutoMail.class));}
byActiver.setEnabled(true);
Toast.makeText(getApplicationContext(),"Processus arreté",Toast.LENGTH_LONG).show();
}
});
}
private Boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyServiceSauvAutoMail.class.getName().equals(service.service.getClassName())) {
Log.e("i","Bjr");
return true;
}
}
return false;
}
public void BoitedialogMailEdit(){
AlertDialog.Builder Builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog_layout3, (ViewGroup) findViewById(R.id.layout_root));
final EditText adrmail = (EditText) layout.findViewById(R.id.adrmail);
Builder.setView(layout);
Builder.setPositiveButton("VALIDER",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mail = adrmail.getText().toString();
final Button byActiver = (Button)findViewById(R.id.btactiver);
Intent intent2 = new Intent(getApplicationContext(), MyServiceSauvAutoMail.class);
startService(intent2);
dialog.dismiss();
Toast.makeText(getApplicationContext(),"Processus démarré.",Toast.LENGTH_LONG).show();
byActiver.setEnabled(false);
}
});
AlertDialog dialog = Builder.create();
dialog.show();
}
}
答案 0 :(得分:0)
您无需检查Service
是否正在运行,只需在其上调用stopService()
即可。如果有true
正在运行,则会返回Service
,否则会返回false
。来自reference:
返回:如果有与给定Intent匹配的服务 已经运行,然后停止并返回true;别的假 归还。
类似地,如果多次调用,startService()
将不会启动多个Services
。
返回:如果服务正在启动或已在运行,则返回已启动的实际服务的ComponentName;否则,如果服务不存在,则返回null。