如何使用getApplicationContext在广播接收器类? [英] How to use getApplicationContext in BroadcastReceiver class?

查看:586
本文介绍了如何使用getApplicationContext在广播接收器类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是广播类收听短信使用这种code消息

I am using the broadcaster class to listen to sms messages using this code

package com.escortme.basic;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiverActivity extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Parse the SMS.
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null)
        {
            // Retrieve the SMS.
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++)
            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                // In case of a particular App / Service.
                //if(msgs[i].getOriginatingAddress().equals("+91XXX"))
                //{
                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
                //}
            }
            // Display the SMS as Toast.
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();


            Pol_ViewActivity appState = ((Pol_ViewActivity)getApplicationContext()); // ERROR
            appState.move_map_to("33.786047","-59.187287");
        }
    }
}

和它在清单的定义,像这样

and it's defined in manifest like so

    <receiver 
      android:name="com.escortme.basic.SMSReceiverActivity"
      android:enabled="true">
      <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
      </intent-filter>
    </receiver>

但问题是,它说:该方法getApplicationContext()是未定义的类型SMSReceiverActivity。

But the problem is it says "The method getApplicationContext() is undefined for the type SMSReceiverActivity".

有谁知道为什么发生这种情况,如何解决?
谢谢

Does anyone know why this is happening and how to fix it? Thanks

推荐答案

看对的onReceive方法签​​名()

Look at the method signature for onReceive()

public void onReceive(Context context, Intent intent) {

您正在传递一个上下文作为参数。你应该使用这种情况下,当你需要一个。

You are being passed a context as a parameter. You should be using that context when you need one.

Pol_ViewActivity appState = ((Pol_ViewActivity)context); 

编辑:也我不知道它到底是什么你正在尝试做的。但你也许不应该试图获得一个活动对象,然后调用它的方法就像你似乎在做。

also I don't know exactly what it is you are trying to do. But you probably shouldn't be trying to obtain an Activity object and call a method on it like you seem to be doing.

这篇关于如何使用getApplicationContext在广播接收器类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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