1

我创建了一个类来处理一个简单的消息弹出窗口,这样我就可以在整个应用程序中重用代码。我似乎无法正确理解上下文。这是从各处调用的,通常是从没有直接 UI 的类调用的。请参阅下面的行...

public class msg  {

    public void msghand(String message, Exception e) {
    {

        String s;

        if (e != null) 
        {
            s=  message + "\n" + e.getLocalizedMessage() + " " + e.toString();
        }
        else
        {
            s= message ;
        }

        new AlertDialog.Builder(  getApplicationContext () )  <<<< HERE IS THE PROBLEM
        .setMessage(s)

        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
            }
        })
        .create()
        .show();


    }

    }
}
4

2 回答 2

2

您是否可以将 Context 作为参数传递?

public void msghand(String message, Exception e, Context context) {
    ...
    new AlertDialog.Builder(context)
    ...

您在哪里执行没有上下文的工作?服务没有 UI,但仍然有 Context。

编辑:

您可以创建一个可静态访问的小型消息服务,并在应用程序启动时创建。例如:

class MyActivity extends Activity
{
    public void onCreate(Bundle savedInstanceState)
    {
        // create the Message service that can be statically accessed
        s_MessageService = new MessageService(getApplicationContext());
        ...
    }

    public static MessageService getApplicationMessageService()
    {
        return s_MessageService;
    }

    private static MessageService s_MessageService;
}

适当实施 MessageService 的地方

class MessageService
{
    public MessageService(Context messageContext)
    {
        m_MyContext = messageContext;
    }

    public msghand(String message, Exception e)
    {
        // exactly the same as before, except using the stored context
    }

    Context m_MyContext = null;
}

您的 DBHelper 类可以通过

MyActivity.getApplicationMessageService().msghand(...);
于 2011-01-14T19:21:04.397 回答
0

在类 msg 的构造函数中添加 Context 作为参数,并从使用它的任何活动中传递它。

于 2011-01-14T19:20:24.750 回答