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

2023-09-12 22:21:33 作者:Rebound(备胎)

我有一个noraml Java类说ReceivedChat.java在这个类的构造函数,我想打电话给Android系统的活动。

 公共类ReceivedChat {
    字符串消息;
    String一个;
    上下文语境;

    ReceivedChat(字符串消息,从字符串){
        this.message =消息;
        this.from =距离;

        叠B =新包();
        b.putString(信息,this.message);
        (距离,this.from)b.putString;
        b.putString(fromChat,真);

        意图I =新的意图(context.getApplicationContext(),XmppChatActivity.class);
        i.putExtras(B);
        。context.getApplicationContext()startActivity(ⅰ);
    }
}
 

我的动态类是 XmppChatActivity

此程序无法正常工作。他并没有叫我 XmppChatActivity 类的OnCreate 任何帮助将是心存感激我的。

解决方案   

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

和年薪30万的学弟聊了一个小时,我自闭了

您将需要从一个活动或任何其他应用程序组件的电流传递活动上下文来 ReceivedChat 在创建对象的时间:

  ReceivedChat(字符串消息,从,上下文语境字符串)
{
this.message =消息;
this.from =距离;
this.context =背景; //<<这里初始化上下文
意图I =新的意图(背景下,XmppChatActivity.class);
 //....your code在这里
context.startActivity(ⅰ);

}
 

而不是开始从类的构造函数另一个活动的 ReceivedChat 创建方法和对象创建后把它叫做

I have one noraml java class say ReceivedChat.java in the constructor of this class i want to call an Activity of Android.

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

My Activity class is XmppChatActivity.

This program is not working. it is not calling the onCreate of my XmppChatActivity class Any help will be thankfull to me.

解决方案

how to call An Activity class from a normal java class

you will need to pass Current Activity Context to ReceivedChat at the time of Object Creation from an Activity or any other Application Components as :

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

}

and instead of starting another Activity from class Constructor create an method in ReceivedChat and call it after object creation