如何从Android中的noraml java类调用一个Activity类

我有一个noraml java类,在这个类的构造函数中说ReceivedChat.java我想调用Android的Activity。

public class ReceivedChat { String message; String from; Context context; ReceivedChat(String message, String from) { this.message = message; this.from = from; Bundle b = new Bundle(); b.putString("message", this.message); b.putString("from", this.from); b.putString("fromChat", "true"); Intent i = new Intent(context.getApplicationContext(), XmppChatActivity.class); i.putExtras(b); context.getApplicationContext().startActivity(i); } } 

我的Activity类是XmppChatActivity

这个程序不起作用。 它没有调用我的XmppChatActivity类的onCreate任何帮助都会感谢我。

如何从普通的java类调用一个Activity类

您需要在活动或任何其他应用程序组件创建对象时将当前活动上下文传递给ReceivedChat ,如下所示:

 ReceivedChat(String message, String from,Context context) { this.message = message; this.from = from; this.context=context; //<< initialize Context here Intent i = new Intent(context,XmppChatActivity.class); //....your code here context.startActivity(i); } 

而不是从类Constructor中启动另一个Activity在ReceivedChat创建一个方法,并在创建对象后调用它