-1

我正在尝试在连接处理程序类中实现 toast

public class server implements Runnable {
private static final String TAG = "myLogs";
.....
public void run()
{
.....
while (true) {
    try {

       client = server.accept();
        // here i want to show message, when client is connected
         Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
          Log.d(TAG, "client connected....");

但我在 makeText 和 getApplicationContext() 上遇到错误;他们有下划线..

4

6 回答 6

1

您无法在可运行文件中获取 getApplicationContext(),只能在活动或服务中获取。要在可运行文件中获取应用程序上下文,您应该将活动的上下文传递给可运行文件。

但是在您的情况下,您想在活动上下文中显示祝酒词。为了做到这一点,传递活动对象并调用 runOnUIThread 方法。将您的活动作为 toast 的上下文:

public class Server implements Runnable {
private static final String TAG = "myLogs";
private Activity myActivity;

  public Server(final Activity activity) {
    this.myActivity = activity;
  }

.....
public void run()
{
.....
while (true) {
    try {

       client = server.accept();
        // here i want to show message, when client is connected
        myActivity.runOnUiThread(new Runnable() {
          public void run() {
            Toast.makeText(myActivity, "msg msg", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "client connected....");    
          }
       });

此处也对此进行了描述: Android: Toast in a thread

于 2013-04-26T13:42:14.407 回答
0

看这里的解释

也许您应该使用构造函数或其他方式传递一个 Activity 上下文,但您不能将 applicationcontext 用于 toast。

于 2013-04-26T13:11:09.067 回答
0

我认为您的 getApplicationContext() 方法可能返回 NULL。我认为这是因为您正在从一个线程运行 toast,而该线程将脱离 UI 线程。

您将需要从应用程序中具有 UI 上下文的某个位置调用此方法(即系统可以获得 UI 线程句柄的某个位置 - 或者它需要显示 Toast 的位置)。

在创建 Toast 之前尝试获取应用程序上下文(可能使用此语法):

Context ctx =getApplicationContext();

然后,在尝试显示您的 toast 之前确保它不为 NULL。

如果它实际上是 NULL,您将需要传递上下文(在您确实有上下文的地方使用该方法,并将其作为参数传递到您的线程中)

于 2013-04-26T13:14:14.787 回答
0

使用classname.this它肯定有效

于 2013-04-26T13:15:27.227 回答
0

首先检查你是否进行了正确的导入(我认为它是 import android.widget.Toast; 或者你可以使用 import android.widget.*; 来确定)。然后尝试使用 this 而不是 getApplicationContext() 或 activityname.this。

于 2013-04-26T13:15:58.587 回答
0

试试这个。

上下文上下文;上下文=这个;

Toast.makeText(context, "msg msg", Toast.LENGTH_SHORT).show();

或者

Toast.makeText(ClassName.this, "msg msg", Toast.LENGTH_SHORT).show();

或者

Toast.makeText(this.getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();

于 2013-04-26T13:31:42.930 回答