繁体   English   中英

如何从扩展AppCompatActivity访问getIntent()扩展应用程序

[英]How to access getIntent() from extends AppCompatActivity to extends Application

因此,我的活动A为:

public class imei extends AppCompatActivity {
//variables    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imei);    
        ...    
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if(Long.parseLong(IMEI) == IMEI2){
                    IMEI .equals(IMEI2);
                    textView.setText("IMEI NUMBER : " + IMEI);
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("key", true);
                    Intent intent = new Intent(imei.this, menu_utama.class);
                    intent.putExtras(bundle);
                    imei.this.startActivity(intent);
                }else{}

现在我想将值的布尔值从bundle传递给Activity B:

public class MyApplication extends Application {
private BeaconManager beaconManager;    
    //variables

    @Override
    public void onCreate() {
        super.onCreate();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        final boolean success = bundle.getBoolean("key");    
        ..code
            if(success){
                do something
            }else{do something

但是getIntent()是红色的,但是当我更改为extends AppCompatActivitygetIntent()正确。 它与onCreate(Bundle savedInstanceState)有某种关系,并extends Application我应该怎么做才能解决此问题

所以我的问题是如何在活动类之间传递值到应用程序类,首先尝试我使用正在使用getIntent()的Bundle,但是由于getIntent()在活动类中而没有用,因为我想在应用程序中使用类,所以我正在使用共享的首选项,它可以工作。

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putBoolean("masuk", true);
                    // Save the changes in SharedPreferences
                    editor.apply(); // commit changes

将其放在活动类中,并在应用程序类中获取共享的首选项:

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putBoolean("masuk", true);
        // Save the changes in SharedPreferences
        editor.apply(); // commit changes

然后只需使用if(masuk){do what you want here}else{do what you want here}解决了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM