简体   繁体   English

Android开发(Java)-崩溃

[英]Android Developing (Java) - Crash

I'm trying to learn more about Java. 我试图学习有关Java的更多信息。 I don't know much anything about it. 我对此一无所知。 People are saying that if I know PHP I know Java. 人们说,如果我懂PHP,我就会懂Java。 I don't think so. 我不这么认为。 Java is too much dot grinding and it doesn't allow any exceptions. Java太多了点打磨,并且不允许任何异常。

My application crashes immediately when started. 我的应用程序启动时立即崩溃。 I have added "FINE_LOCATION" and "COARSE_LOCATION" to permissions of application. 我已将“ FINE_LOCATION”和“ COARSE_LOCATION”添加到应用程序的权限。

package either.no.me.myapplication2;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    TextView textLat;
    TextView textLon;
    Timer timer1 = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textLat = (TextView) findViewById(R.id.textLat);
        textLon = (TextView) findViewById(R.id.textLon);
        GPSFinder gpsFinder = new GPSFinder();
        gpsFinder.GetLocation();
    }
}

class GPSFinder extends MainActivity {
    public void GetLocation() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location provider.
                textLat.setText(Double.toString(location.getLatitude()));
                textLon.setText(Double.toString(location.getLongitude()));
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }
        };

        // Register the listener with the Location Manager to receive location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    }
}

The error I am getting in logcat: 我在logcat中遇到的错误:

07-31 01:36:45.611 1703-1703/either.no.me.myapplication2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: either.no.me.myapplication2, PID: 1703
                                                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{either.no.me.myapplication2/either.no.me.myapplication2.MainActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
                                                                               at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:136)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5045)
                                                                               at java.lang.reflect.Method.invokeNative(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:515)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                                               at dalvik.system.NativeStart.main(Native Method)
                                                                            Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
                                                                               at android.app.Activity.getSystemService(Activity.java:4532)
                                                                               at either.no.me.myapplication2.GPSFinder.GetLocation(MainActivity.java:37)
                                                                               at either.no.me.myapplication2.MainActivity.onCreate(MainActivity.java:31)
                                                                               at android.app.Activity.performCreate(Activity.java:5231)
                                                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269) 
                                                                               at android.app.ActivityThread.access$800(ActivityThread.java:135) 
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                               at android.os.Looper.loop(Looper.java:136) 
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5045) 
                                                                               at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                               at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
                                                                               at dalvik.system.NativeStart.main(Native Method) 
07-31 01:36:48.875 1703-1703/either.no.me.myapplication2 I/Process: Sending signal. PID: 1703 SIG: 9

Remove GPSFinder class and use code of GetLocation method inside MainActivity like below 删除GPSFinder类,并在MainActivity内部使用GetLocation方法的代码,如下所示

<pre>
package either.no.me.myapplication2;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    TextView textLat;
    TextView textLon;
    Timer timer1 = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textLat = (TextView) findViewById(R.id.textLat);
        textLon = (TextView) findViewById(R.id.textLon);
        getLocation();
    }

public void getLocation() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location provider.
                textLat.setText(Double.toString(location.getLatitude()));
                textLon.setText(Double.toString(location.getLongitude()));
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }
        };

        // Register the listener with the Location Manager to receive location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    }  } 

GPSFinder shouldn't derive from MainActivity. GPSFinder不应源自MainActivity。 It isn't an Activity. 这不是活动。

Also, activities should never be created via new- they won't be fully initialized. 另外,永远不要通过新建活动来创建活动,因为活动不会被完全初始化。 They should be started (or the code shouldn't be an activity at all like here). 它们应该被启动(或者代码根本不应该是一个活动,就像这里一样)。 Because it wasn't properly initialized when it called getSystemServices it failed. 因为在调用getSystemServices时未正确初始化,所以失败了。 If you need a context or system service it should be passed in, you shouldn't just derive from a Context class. 如果需要上下文或系统服务,则应该传递它,而不仅仅是从Context类派生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM