2011-01-14 118 views
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(); 


    } 

    } 
} 

回答

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(...); 
+0

我确实已经把Context传递给了这个,但是我想调用它的一些地方只是类,比如DBHelper,并且没有UI。 – 2011-01-14 19:26:04

0

添加上下文关系中类味精的构造函数的参数,并从任何活动正在使用它在通过此。

+0

使用它是否必须是一个 “活动” 本身?像公共类xtz延伸Activity()? – 2011-01-14 19:26:36