簡體   English   中英

在非活動的類中使用Android中的TelephonyManager

[英]Using TelephonyManager in Android in a class that is NOT an activity

這個問題可能源於我仍然對“上下文”及其在Android中的使用感到困惑的事實,因為我還是Android的新手。 提前致謝。

我只是想使類具有獲取電話的MDN或MEID的功能(我知道這不適用於平板電腦)。 我只在這條線上出現錯誤:

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

Eclipse給我“上下文”錯誤。 我查看了這里的上下文: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;

    }
}

將您的getMDN_or_MEID()方法更改為getMDN_or_MEID(Context context)並將一個Context傳遞給它。

然后,您所需要做的就是使用context.getSystemService(Context.TELEPHONY_MANAGER)來獲取TelephonyManager ...

暫無
暫無

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

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