繁体   English   中英

Android 显示吐司

[英]Android display toast

我看到了这个

但对我不起作用。

我将在我的代码中显示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()都没有编译时异常。

解决办法是什么?

试试这个方法:

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

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

你可以在你的类MyPhoneStateListener getApplicationContext() 这个方法不是静态的,所以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 线程上运行:

  1. 获取您的活动的参考
  2. 做这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM