java - 无法关闭间隔服务

标签 java android service

即使关闭应用程序后,该服务仍然处于 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/

相关文章:

java - Eclipse插件创建项目失败 "Google Cloud Tools for Eclipse"

java - EntityManager contains 或 findById after persist 来了解 persist 方法是否有效

c# - 将现有服务设置为 "Auto (Delayed start)"

java - SHA1withRSA NoSuchAlgorithmException

java - 客户端应该具有与服务器相同的 keystore 吗?

android - 当应用程序处于深色/浅色主题(尤其是深色主题)时,在 Flutter 中测试应用程序外观的最佳方法

Android 浏览器对 HTML 和 CSS 的限制

android - 如何添加网络安全配置以在牛轧糖中启用 Charles 代理 SSL?

android - 从服务更新LiveData

WCF - 在单个 APP.Config 文件中定义多个服务?