我在android中很新。我使用BroadcastReceiver和intentServices在两个应用程序之间进行了通信。 问题是,我想从app1向app2发送信息。在app1中我需要访问MainActivity.class中的变量,我需要将它发送到servicev.class(处理intent的服务)但是当我访问它时变量“res”为null,为什么会发生这种情况? (App2调用app1 onHandleIntent,它在res.getOtp()中断)我尝试创建一个额外的setter getter类,也是一个intent但getIntent()在onHandleIntent内部不起作用...如何实现传递res.getOTP(字符串)?我真的不想使用SQLite
servicev:
public class servicev extends IntentService {
private static final int RESULT_OK = 1;
protected ResultReceiver mReceiver;
public servicev() {
super("yeah");
}
@Override
protected void onHandleIntent(Intent intent) {
//I receive here the intent from app2 and I need to response with res.getOTP()
helper h = new helper();
String val = intent.getStringExtra("foo");
Intent in = new Intent("com.banorte.bem.movil.veriToken.SendBroadcast");
in.putExtra("resultCode", this.RESULT_OK);
in.putExtra("resultValue", "My Result Value. Passed in: " + h.getRes().getOtp()); //h here is null... setter and getter approach does not work... maybe sqlite could work but it is necesary?
sendBroadcast(in);
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
VTTokenAPI api;
TextView textView;
Button button;
EditText input;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidSetup.getInstance().init(this);
helper h = new helper();
api = new VTTokenAPI("FFFFFF");
res = api.getStatus();
res.getOtp(); //correct value
h.setRes(res);
setContentView(R.layout.activity_main);
}
}
助手:
public class helper {
public VTResult getRes() {
return res;
}
public void setRes(VTResult res) {
this.res = res;
}
VTResult res;
}
答案 0 :(得分:1)
您正在尝试实例化一个新的MainActivity
,它与正在运行的活动不同,而是一个新实例。
如果您需要IntentService
能够从正在运行的Activity
获取数据,则可以使用SharedPreferences
或SQLite等选项。不要将数据保留在内存中,而是尝试将其保留在onCreate
的某个数据库中,然后尝试在handleIntent
期间从存储中读取它