'this'的一些问题:方法不适用于参数,也改进了格式

时间:2014-02-28 13:27:09

标签: java android this

的Bonjour

-A-在Appsetting中:

public class AppSettings {
 ...
    public static String getLogFileName(Context context){
    SharedPreferences pref = context.getSharedPreferences(GPSLOGGER_PREF_NAME, 0);
        return pref.getString(LOG_FILE, "");
    }
主要活动中的

-B-:

  AppLog.logString("Version A 05 Service Started with interval " + interval + ", Logfile name: " + AppSettings.getLogFileName(this));

==>工作正常

-C-但在

public class SmsReceiver extends BroadcastReceiver

  File kmlFile = new File(folder.getPath(),AppSettings.getLogFileName(this));

相同的指令“AppSettings.getLogFileName(this)”,错误(xxxx):

“此行的多个标记      - AppSettings类型中的方法getLogFileName(Context)不适用于参数(SmsReceiver)      - 语法错误,插入“)”以完成VariableInitializer“

为什么?存在简单的解决方法吗?

编辑:添加'('但不够

“AppSettings类型中的方法getLogFileName(Context)不适用于参数(SmsReceiver)”

3 个答案:

答案 0 :(得分:0)

在这条线上缺少')'

File kmlFile = new File(folder.getPath(),AppSettings.getLogFileName(this); xxxx

尝试

File kmlFile = new File(folder.getPath(),AppSettings.getLogFileName(this));

答案 1 :(得分:0)

Activity延伸Context。在Activity类实例中,this引用当前实例,该实例是超级类Context的实例。

SmsReceiver中,this指的是当前实例,它是超级BroadcastReceiver的实例。

您的getLogFileName方法需要Context类型的参数,这就是this来自Activity但不来自SmsReceiver的原因。

相反:

public class SmsReceiver extends BroadcastReceiver

  private Context mContext;

  public SmsReceiver(Context context)
  {
      mContext = context;
  }

  File kmlFile = new File(folder.getPath(),AppSettings.getLogFileName(mContext));

然后在Activity

smsReceiver = new SmsReceiver(this);

答案 2 :(得分:0)

错误意味着您无法将SmsReceiver对象传递给AppSettings.getLogFileName()方法,因为它只接受Context类或其后代的实例。 SmsReceiver不是Context类的直接或间接子项,因此您不能这样做。