在Android中使用TelephonyManager中的非活动类

时间:2012-03-23 01:07:31

标签: java android eclipse class android-context

这个问题可能源于这样一个事实,即我仍然对“上下文”及其在Android中的使用感到困惑,因为我还是Android新手。提前谢谢。

我只是想创建一个具有函数的类来获取手机的MDN或MEID(我知道这不适用于平板电脑)。我在这一行上只收到错误:

TelephonyManager tManager = (TelephonyManager) Test.getSystemService(Context.TELEPHONY_SERVICE);

Eclipse在“Context”上给我一个错误。我已经查看了Context在这里: What is 'Context' on Android? 并且发现第一条评论非常有用,但它没有告诉您如何在不在活动类中时获取上下文。

有什么建议吗?

以下完整代码:

package com.test.app;

import java.util.UUID;

import android.content.Context;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

public class Test {

    public String getMDN_or_MEID() {

        // getSystemService is a method from the Activity class. getDeviceID()
        // will return the MDN or MEID of the device depending on which radio
        // the phone uses (GSM or CDMA).
        TelephonyManager tManager = (TelephonyManager) Test
                .getSystemService(Context.TELEPHONY_SERVICE);
        String uid = tManager.getDeviceId();
        return uid;

    }
}

1 个答案:

答案 0 :(得分:1)

getMDN_or_MEID()方法更改为getMDN_or_MEID(Context context)并将Context传递给它。

然后您需要做的就是使用context.getSystemService(Context.TELEPHONY_MANAGER)来获取TelephonyManager ...