You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何将Intent接收的变量设为公共静态供其他类正常调用

报错原因

你遇到的报错是因为直接在静态变量声明阶段使用了属于Activity实例的非静态成员receiverIntent赋值。静态变量的初始化时机早于Activity实例的创建流程,此时receiverIntent还未实例化,自然无法在静态上下文中被引用。


解决方案1:修改静态变量赋值时机

不要在声明静态变量时直接赋值,改为在Activity生命周期回调(如onCreate)中完成赋值,步骤如下:

  1. 先在你的Activity类中声明公共静态变量:
// 只声明不赋值
public static String completeName;
  1. 在onCreate方法中接收Intent参数后给静态变量赋值:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 原有初始化逻辑
    Intent receiverIntent = getIntent();
    // 给静态变量赋值
    completeName = receiverIntent.getStringExtra("name");
}
  1. 其他类访问时直接调用你的Activity类名.completeName即可。

注意:使用这种方式需要做好空值判断,应用被后台回收重建时静态变量会被重置为null。


解决方案2:使用自定义Application全局存储(更稳妥)

如果不想用静态变量,也可以用全局Application类存储参数,避免静态变量的潜在问题:

  1. 新建自定义Application类:
public class MyApplication extends Application {
    // 全局存储的变量
    public String completeName;
}
  1. 在AndroidManifest.xml中注册自定义Application:
<application
    android:name=".MyApplication"
    <!-- 其他原有配置 -->
    >
    <!-- Activity等组件配置 -->
</application>
  1. 在当前Activity中赋值:
Intent receiverIntent = getIntent();
MyApplication app = (MyApplication) getApplicationContext();
app.completeName = receiverIntent.getStringExtra("name");
  1. 其他类只要有Context上下文即可访问:
MyApplication app = (MyApplication) context.getApplicationContext();
String currentName = app.completeName;

内容的提问来源于stack exchange,提问作者Andrew Williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:39:05