Android Studio-无法访问的声明

时间:2020-04-01 19:24:13

标签: java android service

我正在尝试调用服务,但是在服务中,当我注册LocationManager时,在onStartCommand()中的Android Studio中,Android Studio说unreachable statement
这很奇怪,因为我在MainActivity中调用了onStartCommand()。
我在android清单中有服务。
当我在服务中使用onCreate()方法时,似乎与MainActivity中的onCreate()方法名称冲突。

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 :(得分:0)

注释是正确的,在执行指令之前,我在onStartCommand方法中使用了返回语句return super.onStartCommand(intent, flags, startId);,因此该指令无法访问。