Android显示吐司

时间:2015-11-19 10:21:29

标签: android toast

我看到了this

但不适合我。

我将在我的代码中显示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.thisgetActivity()中都有编译时例外。

解决方案是什么?

5 个答案:

答案 0 :(得分:0)

尝试这种方式:

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

答案 1 :(得分:0)

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

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();
    }
}

现在您需要pass context along with int state and string number youractivityname.this

答案 2 :(得分:0)

您的班级getApplicationContext()中的所有MyPhoneStateListener都可以这样。此方法不是静态的,因此getApplicationContext()就像调用this.getApplicationContext()一样。并且您的班级MyPhoneStateListener不会使用此类方法扩展课程。

因此解决方案是向您的班级添加字段Context mContext。然后添加一个construtor

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);

答案 3 :(得分:0)

代替getApplicationContext()尝试

Toast toast = Toast.makeText(Youractivity.this, msg, duration);

如果你有contentprovider那么

getContext()

答案 4 :(得分:0)

你必须在ui Thread上运行:

  1. 获取对您活动的引用
  2. 这样做

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