Android 安卓显示吐司

Android 安卓显示吐司,android,toast,Android,Toast,我看到 但对我来说不管用 我将在我的代码中显示Toast: private class MyPhoneStateListener extends PhoneStateListener { public void onCallStateChanged(int state, String incomingNumber) { Log.d("MyPhoneListener", state + " incoming no:" + incomingNumber);

我看到

但对我来说不管用

我将在我的代码中显示
Toast

private class MyPhoneStateListener extends PhoneStateListener {

    public void onCallStateChanged(int state, String incomingNumber) {

        Log.d("MyPhoneListener", state + "   incoming no:" + incomingNumber);

        if (state == 1) {

            String msg = "New Phone Call Event. Incomming Number : " + incomingNumber;
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(getApplicationContext(), msg, duration);
            toast.show();

        }
    }
}
但是我在
getApplicationContext()
MainActivity中都没有编译时异常。这是
getActivity()

解决方案是什么?

请尝试以下方法:

Toast.makeText(getApplicationContext(), "message", Toast.LENGTH_SHORT).show();

您需要从调用方法的活动中传递上下文,您需要更改代码,如下所示

public void onCallStateChanged(Context context, int state, String incomingNumber) {

    Log.d("MyPhoneListener", state + "   incoming no:" + incomingNumber);

    if (state == 1) {

        String msg = "New Phone Call Event. Incomming Number : " + incomingNumber;
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, msg, duration);
        toast.show();
    }
}

现在您需要
传递上下文以及int state和string number
类似
您的ActivityName。这
您可以
获取应用程序上下文()
类似于类中的
MyPhoneStateListener
。此方法不是静态的,因此
getApplicationContext()
类似于调用
This.getApplicationContext()
。您的类
MyPhoneStateListener
不使用这种方法扩展类

因此,解决方案是在类中添加一个字段
Context mContext
。然后添加一个构造函数

public MyPhoneStateListener(Context context, ...some other arguments if you need then ...) {
     super();
     mContext = context;
     ...some other stuff if you need then...
}
然后你可以做你的吐司:

enterToast toast = Toast.makeText(mContext, msg, duration);

请尝试使用,而不是
getApplicationContext()

Toast toast = Toast.makeText(Youractivity.this, msg, duration);
如果您有contentprovider,那么

getContext()

您必须在ui线程上运行:

  • 获取对您的活动的引用
  • 这样做

            activity.runOnUiThread(new Runnable() { public void run() {
                Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
            }
        });
    

  • 你有什么例外?把它送到这里。您是否尝试使用getBaseContext()而不是getApplicationContext()。尝试使用ActivityName。这..传递
    Context Context
    您不能这样做,它将更改方法签名在您的回答中确定bro您正在做同样的事情我说的是方法的签名
    onCallStateChanged
    。您不应该更改其签名。@Ghkjnsadxzcx使用getBaseContext()而不是getApplicationContext(),那么您在做什么?请检查您的代码。您正在传递
    “context”
    ,以及构造函数中的一些其他参数。然后在字段中引用此上下文。方法
    onCallStateChanged
    在超类
    PhoneStateListener
    中定义。如果您更改其签名,它将不会重写super类中的方法。请检查问题,方法未被重写。请检查文档,