如何存取权限getSystemService在应用程序类 [英] How to acces getSystemService in Application class

查看:317
本文介绍了如何存取权限getSystemService在应用程序类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要访问应用程序类的TELEPHONY_SERVICE系统服务,但我的应用程序崩溃时我运行它。

I want to access the TELEPHONY_SERVICE system service in the Application class, but my app crashes when I run it.

public class SimpleDhtApplication extends Application {


    TelephonyManager tel = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() -4);
    final String myPort = String.valueOf((Integer.parseInt(portStr) * 2));
}

我想我不能正确访问的背景下,可以有人帮助!

I think I am not accessing the context correctly, can somebody help!

推荐答案

首先重写应用程序类的onCreate方法。内的onCreate,把code你有那么它看起来像:

Override the onCreate method of the Application class first. Within the onCreate, put the code you have so it would look like:

public class SimpleDhtApplication extends Application {


    @Override
    public void onCreate() {
        super.onCreate();
        TelephonyManager tel = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() -4);
        final String myPort = String.valueOf((Integer.parseInt(portStr) * 2));
    }
}

更新:当心tel.getLine1Number();它可能会返回null作为解释<一个href=\"http://developer.android.com/reference/android/telephony/TelephonyManager.html#getLine1Number%28%29\"相对=nofollow>这里。

Update: Watch out for tel.getLine1Number(); it may return null as explained here.

这篇关于如何存取权限getSystemService在应用程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆