Android Studio - недостижимая выписка в сервисе - PullRequest
0 голосов
/ 01 апреля 2020

Я пытаюсь вызвать службу, но внутри службы Android Studio в onStartCommand () Android Studio сообщает unreachable statement, когда я регистрирую LocationManager.
Что странно, потому что я вызываю onStartCommand () в моей MainActivity.
У меня есть услуга в манифесте android.
Когда я использую метод onCreate () в службе, возникает конфликт имен с методом onCreate () в MainActivity.

package com.example.gpstosqlite;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv1 = (TextView) findViewById(R.id.textView1);

        Switch switch1 = (Switch) findViewById(R.id.switch1);

        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == true) {
                    tv1.setText(R.string.switchOn);
                    Intent serviceIntent = new Intent();
                    serviceIntent.setAction("com.gpstosqlite.GPSservice");
                    startService(serviceIntent);
                } else {
                    tv1.setText(R.string.switchOff);
                }
            }
        });
    }
}
package com.example.gpstosqlite;

import android.app.Service;
import android.content.Intent;
import android.location.LocationManager;
import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;


public class GPSservice extends Service {
    LocationManager locationManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
        //the next line is underlined red
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    }
}

1 Ответ

0 голосов
/ 07 апреля 2020

Комментарии верны, у меня был оператор return return super.onStartCommand(intent, flags, startId); в методе onStartCommand перед инструкцией, и поэтому эта инструкция была недоступна.

...