gpt4 book ai didi

java - 无法关闭间隔服务

转载 作者:行者123 更新时间:2023-12-01 08:57:14 25 4
gpt4 key购买 nike

即使关闭应用程序后,该服务仍然处于 Activity 状态。

启动服务:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotion);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

//Service
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent1 = new Intent(this, PositionService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent1, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 15 * 1000, pintent);
startService(new Intent(getBaseContext(), PositionService.class));
}

类(class)服务

public class PositionService extends Service {
String id_user;
private String JSON_STRING;
double lat;
double lon;
int id_promotions;
String description_1;
String promotionDetail;
String address;
double latPromotion;
double lonPromotion;

//notification
// private static final String TAG = "MyService";



@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onCreate() {
// TODO Auto-generated method stub
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
id_user = sharedPref.getString("id_user", "");
super.onCreate();
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//stopService(new Intent(this, PositionService.class));
}

@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
//stopService(new Intent(this, PositionService.class));
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Running", Toast.LENGTH_SHORT).show();

/* Uso de la clase LocationManager para obtener la localizacion del GPS */
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Localizacion Local = new Localizacion();
Local.setMainActivity(this);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);


return super.onStartCommand(intent, flags, startId);
}

public void setLocation(Location loc) {
//Obtener la direccion de la calle a partir de la latitud y la longitud
if (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) {
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list = geocoder.getFromLocation(
loc.getLatitude(), loc.getLongitude(), 1);
if (!list.isEmpty()) {
Address DirCalle = list.get(0);
//textViewAddress.setText(DirCalle.getAddressLine(0));
}

} catch (IOException e) {
e.printStackTrace();
}
}
}


public class Localizacion implements LocationListener {
PositionService positionService;

public PositionService getPositionService() {
return positionService;
}

public void setMainActivity(PositionService positionService) {
this.positionService = positionService;
}

@Override
public void onLocationChanged(Location loc) {
// Este metodo se ejecuta cada vez que el GPS recibe nuevas coordenadas
// debido a la deteccion de un cambio de ubicacion

loc.getLatitude();
loc.getLongitude();
lat = loc.getLatitude();
lon = loc.getLongitude();
//Toast.makeText(getApplicationContext(), "latitud: " + lat + ", longitud: " + lon, Toast.LENGTH_SHORT).show();
//textViewLatitud.setText(String.valueOf(lat));
//textViewLongitud.setText(String.valueOf(lon));

this.positionService.setLocation(loc);
}

@Override
public void onProviderDisabled(String provider) {
// Este metodo se ejecuta cuando el GPS es desactivado
//textViewLatitud.setText("GPS Desactivado");
}

@Override
public void onProviderEnabled(String provider) {
// Este metodo se ejecuta cuando el GPS es activado
//textViewLatitud.setText("GPS Activado");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// Este metodo se ejecuta cada vez que se detecta un cambio en el
// status del proveedor de localizacion (GPS)
// Los diferentes Status son:
// OUT_OF_SERVICE -> Si el proveedor esta fuera de servicio
// TEMPORARILY_UNAVAILABLE -> Temporalmente no disponible pero se
// espera que este disponible en breve
// AVAILABLE -> Disponible
}

}/* Fin de la clase localizacion */



}

我尝试以此结束服务,但不起作用

else if (id == R.id.nav_send) {
stopService(new Intent(this, PositionService.class));
finish();

}

list :

        <service
android:name=".service.PositionService"
android:enabled="true"
android:exported="true">
</service>
我用 toast 控制服务运行,但从不停止运行

感谢您的帮助

最佳答案

添加START_NOT_STICKY,这将阻止服务再次启动:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Running", Toast.LENGTH_SHORT).show();

/* Uso de la clase LocationManager para obtener la localizacion del GPS */
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Localizacion Local = new Localizacion();
Local.setMainActivity(this);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);


return START_NOT_STICKY; //here
}

关于java - 无法关闭间隔服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41970147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com