应用程序关闭没有任何原因?

时间:2015-10-13 13:03:12

标签: android

我是一个安卓的Android应用程序制造商,以下是我的第一个应用程序。 该应用程序基本上做的是它获取手机的位置,延迟5秒,并运行另一个getLocation;然后它从这两点得出速度,并指出用户是否在使用手机时走路。

Studio中的代码没有问题,但是当我尝试运行我的应用程序时,手机只是说“应用程序停止了”#39;它关闭了应用程序。 我花了几个小时试图搞清楚,但无济于事。

我做错了什么?

package com.example.denny.myapplication;

import android.Manifest.permission;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        PackageManager pm = getPackageManager();
        if (pm.checkPermission(permission.ACCESS_FINE_LOCATION, getPackageName()) == PackageManager.PERMISSION_DENIED) {
            alertboxGPS();
        }
        mHandler = new Handler();
        startRepeatingTask();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
                                   @Override
                                   public void onClick(View view) {
                                       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                                               .setAction("Action", null).show();

                                   }
                               }
        );
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        //Also, chuck the subroutine settings here. :3
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    PackageManager pm = getPackageManager();

    protected void alertboxGPS() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your Device's GPS is Disabled")
                .setCancelable(true)
                .setTitle("** Gps Status **")
                .setPositiveButton("Gps On",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // finish the current activity
                                // AlertBoxAdvance.this.finish();
                                Intent myIntent = new Intent(
                                        Settings.ACTION_SECURITY_SETTINGS);
                                startActivity(myIntent);
                                dialog.cancel();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // cancel the dialog box
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    protected void alertboxViolation() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Please stop walking. You may get in an accident.")
                .setCancelable(false)
                .setTitle("Walking Warning")
                .setPositiveButton("Stop Walking",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // finish the current activity
                                // AlertBoxAdvance.this.finish();
                                Intent myIntent = new Intent(
                                        Settings.ACTION_SECURITY_SETTINGS);
                                startActivity(myIntent);
                                dialog.cancel();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // cancel the dialog box
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    //Some Default Integers
    int ViolationLimit = 10;
    int SpeedLimit = 100;
    int ExceedInstance = 0;

    //Default Value
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location1;
    Location location2;

    private double GetSpeed(Location location1, Location location2) {

        if (location1 == null) {

            location1 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            location2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else {
            location1 = location2;
            if (checkSelfPermission(permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            }
            location2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        }
        double Distance;
        Distance = location1.distanceTo(location2);
        double Speed = Distance / mInterval;
        return Speed;
    }


    private int Judge(double Speed, int ViolationLimit, int SpeedLimit, int ExceedInstance) {
        if (Speed >= 1 && Speed <= SpeedLimit) {
            ExceedInstance += 1;
        }

        if (ExceedInstance >= ViolationLimit) {
            alertboxViolation();
        }
        return ExceedInstance;
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }

    private int mInterval = 3000; // 3 seconds by default, can be changed later
    private Handler mHandler;
    Runnable mStatusChecker = new Runnable() {
        @Override
        public void run() {
            updateStatus();
            mHandler.postDelayed(mStatusChecker, mInterval);
        }
    };

    private void updateStatus() {
        //Is used for updating mInterval
    }

    void startRepeatingTask() {
        double Speed = GetSpeed(location1, location2);
        Judge(Speed, ViolationLimit, SpeedLimit, ExceedInstance);
        mStatusChecker.run();
    }
}

Logcat日志:

10-13 23:23:55.818 13410-13410/? E/SELinux: Function: selinux_android_load_priority [0], There is no sepolicy file 
10-13 23:23:55.818 13410-13410/? E/SELinux:  
10-13 23:23:55.818 13410-13410/? E/SELinux: Function: selinux_android_load_priority , loading version is VE=SEPF_GT-I9505_4.3_0024
10-13 23:23:55.818 13410-13410/? E/SELinux:  
10-13 23:23:55.818 13410-13410/? E/SELinux:  
10-13 23:23:55.818 13410-13410/? E/SELinux: selinux_android_seapp_context_reload: seapp_contexts file is loaded from /data/security/spota/seapp_contexts
10-13 23:23:55.818 13410-13410/? D/dalvikvm: Late-enabling CheckJNI
10-13 23:23:55.928 13410-13410/com.example.denny.myapplication I/dalvikvm: Could not find method com.example.denny.myapplication.MainActivity.checkSelfPermission, referenced from method com.example.denny.myapplication.MainActivity.GetSpeed
10-13 23:23:55.928 13410-13410/com.example.denny.myapplication W/dalvikvm: VFY: unable to resolve virtual method 16261: Lcom/example/denny/myapplication/MainActivity;.checkSelfPermission (Ljava/lang/String;)I
10-13 23:23:55.928 13410-13410/com.example.denny.myapplication D/dalvikvm: VFY: replacing opcode 0x6e at 0x0028
10-13 23:23:55.938 13410-13410/com.example.denny.myapplication D/AndroidRuntime: Shutting down VM
10-13 23:23:55.938 13410-13410/com.example.denny.myapplication W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4190e898)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime: java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.denny.myapplication/com.example.denny.myapplication.MainActivity}: java.lang.NullPointerException
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.access$700(ActivityThread.java:159)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5419)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:525)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:  Caused by: java.lang.NullPointerException
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:94)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.example.denny.myapplication.MainActivity.<init>(MainActivity.java:74)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.Class.newInstanceImpl(Native Method)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.Class.newInstance(Class.java:1130)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.access$700(ActivityThread.java:159) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5419) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:525) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method) 
10-13 23:24:03.355 13410-13410/com.example.denny.myapplication I/Process: Sending signal. PID: 13410 SIG: 9

这是一个非常大的日志,但我不知道如何以更好的方式做到这一点。

声明 这个问题与Null Pointer问题不一样,因为我已经制作了一个应用程序而且我不知道是什么导致它。这就是我提出这个问题的原因。

1 个答案:

答案 0 :(得分:2)

首先,关于你的评论:

  

这个问题是在问别人不知道的事情。我是一个   应用程序,我不知道为什么它会关闭。请不要假设   每个人都知道他们正在做什么的一切   问一个问题。

人们正在努力帮助你。在写这样的评论之前,你可能想重新考虑一下你的态度。

其次,@谢尔文是正确的。您的logcat输出明确指出您的应用程序崩溃是由NullPointerException(NPE)引起的:

E/AndroidRuntime:  Caused by: java.lang.NullPointerException

NullPointerException是由代码中的(其他东西)错误逻辑引起的。您的代码是应用程序的一部分这一事实无关紧要。您应该阅读linked question以了解NPE是什么以及它们发生的原因。

讲座结束,让我们来看看你的问题。

Logcat为您提供了大量有关错误的信息,通常包括显示问题的原因和堆栈跟踪。所以,从顶部开始:

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{...}: java.lang.NullPointerException

好的,在Activity实例化期间,它是一个NullPointerException。为什么呢?

Caused by: java.lang.NullPointerException
E/AndroidRuntime:     at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:94)
 at com.example.denny.myapplication.MainActivity.<init>(MainActivity.java:74)

因此调用getPackageManager()时出现问题。 您的代码中最近的位置是MainActivity.<init>, MainActivity.java, line 74

<init>只是构建对象时的Java方法&#34;。

查看源代码,您试图在对象构造期间初始化PackageManager pm字段实例:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
...
}

PackageManager pm = getPackageManager();

protected void alertboxGPS() {
...
}

问题是当getPackageManager()实例正在构建时正在调用Activity - 此时并不是所有内容都已就绪。

几乎可以肯定的是,对getPackageManager()的调用试图使用尚未创建的对象 - 因此NullPointerException。

一种解决方案是删除pm字段的初始化,而是在onCreate()期间设置它 - 此时,您的Activity实例将完全构建并{{1调用将成功。

更好的解决方案是完全删除getPackageManager()字段,只需在需要时创建局部变量 - 就像您在pm中所做的一样。