簡體   English   中英

Android電話管理器崩潰

[英]Android telephony manager Crashes

我絕對是android的初學者,我試圖創建一個可以顯示GSM蜂窩塔詳細信號強度等的小應用程序。如上所述,我是這些應用程序的新手,我嘗試使用堆棧下面的代碼-溢出搜索結果,但是應用程序崩潰而沒有啟動。
如果有人可以幫助我,我將不勝感激! 謝謝。

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   // TelephonyManager Tel;
    MyPhoneStateListener MyListener;

    private TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    private GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
    private Button btnRefresh,btnClose,btnReset;
    private TextView CellLocation,CellID,GSMCode,signalPow;
    int cellid= cellLocation.getCid();
    int celllac = cellLocation.getLac();
    int signalST ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyListener   = new MyPhoneStateListener();
        telephonyManager       = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(MyListener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        btnRefresh = (Button)findViewById(R.id.btnRefresh);
        btnClose = (Button)findViewById(R.id.btnClose);
        btnReset = (Button)findViewById(R.id.btnReset);

        CellLocation = (TextView)findViewById(R.id.txtCellLocation);
        CellID = (TextView)findViewById(R.id.txtBaseStation);
        GSMCode = (TextView)findViewById(R.id.txtGSMLocation);
        signalPow = (TextView)findViewById(R.id.txtSignalStr);

        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signalPow.setText(Integer.toString(signalST));
                CellLocation.setText(cellLocation.toString());
                CellID.setText(Integer.toString(cellid));
               // GSMCode.setText(Integer.toString(celllac));
            }
        });

    }



    @Override
    protected void onPause()
    {
        super.onPause();
        telephonyManager.listen(MyListener, PhoneStateListener.LISTEN_NONE);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        telephonyManager.listen(MyListener,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    public  class MyPhoneStateListener extends PhoneStateListener
    {
        /* Get the Signal strength from the provider, each tiome there is an update */
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength)
        {
            super.onSignalStrengthsChanged(signalStrength);
//            Toast.makeText(getApplicationContext(), "Go to Firstdroid!!! GSM Cinr = "
//                    + String.valueOf(signalStrength.getGsmSignalStrength()), Toast.LENGTH_SHORT).show();
            signalST = signalStrength.getGsmSignalStrength();
            //I have tried to assign signal strength to an integer and display onClik of a button

        }

    }

}

鏈接https://stackoverflow.com/a/33936721

LOGCAT

10-28 04:22:34.594 1781-1781/com.example.gih.test1 I/art: Late-enabling -Xcheck:jni
10-28 04:22:34.615 1781-1786/com.example.gih.test1 I/art: Debugger is no longer active
10-28 04:22:34.628 1781-1781/com.example.gih.test1 W/System: ClassLoader referenced unknown path: /data/app/com.example.gih.test1-1/lib/x86
10-28 04:22:36.584 1781-1781/com.example.gih.test1 W/System: ClassLoader referenced unknown path: /data/app/com.example.gih.test1-1/lib/x86
10-28 04:22:36.685 1781-1791/com.example.gih.test1 W/art: Suspending all threads took: 8.202ms
10-28 04:22:36.723 1781-1781/com.example.gih.test1 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.example.gih.test1, PID: 1781
                                                                       java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.gih.test1/com.example.gih.test1.MainActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                           at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                        Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
                                                                           at android.app.Activity.getSystemService(Activity.java:5253)
                                                                           at com.example.gih.test1.MainActivity.<init>(MainActivity.java:18)
                                                                           at java.lang.Class.newInstance(Native Method)
                                                                           at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                           at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                           at android.os.Looper.loop(Looper.java:148) 
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                           at java.lang.reflect.Method.invoke(Native Method) 
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
10-28 04:22:41.885 1781-1781/com.example.gih.test1 I/Process: Sending signal. PID: 1781 SIG: 9

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gih.test1">
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

LOGCAT-將移動初始化為創建后

10-28 04:39:28.339 2343-2343/com.example.gih.test1 I/Process: Sending signal. PID: 2343 SIG: 9
10-28 04:41:46.462 2505-2505/com.example.gih.test1 W/System: ClassLoader referenced unknown path: /data/app/com.example.gih.test1-2/lib/x86
10-28 04:41:46.634 2505-2515/com.example.gih.test1 I/art: Background sticky concurrent mark sweep GC freed 10950(703KB) AllocSpace objects, 5(116KB) LOS objects, 63% free, 828KB/2MB, paused 441us total 117.451ms
10-28 04:41:47.113 2505-2505/com.example.gih.test1 W/System: ClassLoader referenced unknown path: /data/app/com.example.gih.test1-2/lib/x86
10-28 04:41:47.353 2505-2505/com.example.gih.test1 W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-28 04:41:47.601 2505-2505/com.example.gih.test1 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.example.gih.test1, PID: 2505
                                                                       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gih.test1/com.example.gih.test1.MainActivity}: java.lang.SecurityException: getCellLocation: Neither user 10062 nor current process has android.permission.ACCESS_COARSE_LOCATION.
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                           at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                        Caused by: java.lang.SecurityException: getCellLocation: Neither user 10062 nor current process has android.permission.ACCESS_COARSE_LOCATION.
                                                                           at android.os.Parcel.readException(Parcel.java:1599)
                                                                           at android.os.Parcel.readException(Parcel.java:1552)
                                                                           at com.android.internal.telephony.ITelephony$Stub$Proxy.getCellLocation(ITelephony.java:2292)
                                                                           at android.telephony.TelephonyManager.getCellLocation(TelephonyManager.java:826)
                                                                           at com.example.gih.test1.MainActivity.onCreate(MainActivity.java:29)
                                                                           at android.app.Activity.performCreate(Activity.java:6237)
                                                                           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                           at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                           at android.os.Looper.loop(Looper.java:148) 
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                           at java.lang.reflect.Method.invoke(Native Method) 
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

替換這條線

    private TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    private GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
 int cellid= cellLocation.getCid();
    int celllac = cellLocation.getLac();

    private TelephonyManager telephonyManager; 
    private GsmCellLocation cellLocation ; 
 int cellid;
    int celllac;

寫這個來檢查api> = 23中的位置許可

 if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            111);
                }
            }
            return;
        }

並重寫此方法以檢查權限結果

  @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 111: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

然后在onCreate方法中將它們寫為

    telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
       cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
  cellid= cellLocation.getCid();
     celllac = cellLocation.getLac();

正如logcat錯誤指出的cellLocation ,將變量初始化( telephonyManagercellLocationcellidcelllac )移動到onCreate

logcat中的重要行: Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate() (發生的情況)和at com.example.gih.test1.MainActivity.<init>(MainActivity.java:18) Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate() (發生的位置),以便您可以看到問題所在的確切位置(18)。 更正該行之后,您將為下一行( cellLocation )得到類似的錯誤。 然后,如果您嘗試啟動您的應用程序,則將獲得NullPointerException來初始化cellid ,並下次獲取celllac 在將所有內容移到onCreate內部之后,您的應用程序應該可以運行了。

結合debug日志可以告訴您一切(在您的情況下,並不總是:))。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM