我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。

单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?

本案的任何替代方案


当前回答

这是我的最佳实践,当项目规模巨大且复杂时,它会帮助很大。

假设我有两个活动,LoginActivity和HomeActivity。我想将2个参数(用户名和密码)从LoginActivity传递到HomeActivity。

首先,我创建HomeIntent

public class HomeIntent extends Intent {

    private static final String ACTION_LOGIN = "action_login";
    private static final String ACTION_LOGOUT = "action_logout";

    private static final String ARG_USERNAME = "arg_username";
    private static final String ARG_PASSWORD = "arg_password";


    public HomeIntent(Context ctx, boolean isLogIn) {
        this(ctx);
        //set action type
        setAction(isLogIn ? ACTION_LOGIN : ACTION_LOGOUT);
    }

    public HomeIntent(Context ctx) {
        super(ctx, HomeActivity.class);
    }

    //This will be needed for receiving data
    public HomeIntent(Intent intent) {
        super(intent);
    }

    public void setData(String userName, String password) {
        putExtra(ARG_USERNAME, userName);
        putExtra(ARG_PASSWORD, password);
    }

    public String getUsername() {
        return getStringExtra(ARG_USERNAME);
    }

    public String getPassword() {
        return getStringExtra(ARG_PASSWORD);
    }

    //To separate the params is for which action, we should create action
    public boolean isActionLogIn() {
        return getAction().equals(ACTION_LOGIN);
    }

    public boolean isActionLogOut() {
        return getAction().equals(ACTION_LOGOUT);
    }
}

以下是我如何在LoginActivity中传递数据

public class LoginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        String username = "phearum";
        String password = "pwd1133";
        final boolean isActionLogin = true;
        //Passing data to HomeActivity
        final HomeIntent homeIntent = new HomeIntent(this, isActionLogin);
        homeIntent.setData(username, password);
        startActivity(homeIntent);

    }
}

最后一步,这里是我如何在HomeActivity中接收数据

public class HomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        //This is how we receive the data from LoginActivity
        //Make sure you pass getIntent() to the HomeIntent constructor
        final HomeIntent homeIntent = new HomeIntent(getIntent());
        Log.d("HomeActivity", "Is action login?  " + homeIntent.isActionLogIn());
        Log.d("HomeActivity", "username: " + homeIntent.getUsername());
        Log.d("HomeActivity", "password: " + homeIntent.getPassword());
    }
}

完成!酷:)我只是想分享我的经验。如果你在做小项目,这应该不是大问题。但当你在大项目上工作时,当你想进行重构或修复bug时,这真的很痛苦。

其他回答

如果要在活动/片段之间传输位图


活动

在活动之间传递位图

Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);

在“活动”类中

Bitmap bitmap = getIntent().getParcelableExtra("bitmap");

碎片

在片段之间传递位图

SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);

在SecondFragment内部接收

Bitmap bitmap = getArguments().getParcelable("bitmap");

传输大型位图

如果您正在获取失败的绑定器事务,这意味着您正在通过将大型元素从一个活动转移到另一个活动来超出绑定器事务缓冲区。

因此,在这种情况下,您必须将位图压缩为字节数组,然后在另一个活动中解压缩,如下所示

在第一个活动中

Intent intent = new Intent(this, SecondActivity.class);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray(); 
intent.putExtra("bitmapbytes",bytes);

在第二次活动中

byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

我们可以通过两种方式将值传递给另一个Activity(已经发布了相同类型的答案,但我在这里发布了通过意图尝试的redcing代码)

1.通过意图

  Activity1:
      startActivity(new Intent(getApplicationContext(),Activity2.class).putExtra("title","values"));

InActivity 2:

String recString= getIntent().getStringExtra("title");

2.通过SharedPreference

  Activity1:

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
 // 0 - for private mode
Editor editor = pref.edit();
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes

Activty2:
   SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

pref.getString("key_name", null); // getting String
 Intent intent = new Intent(getBaseContext(), SomeActivity.class);
 intent.putExtra("USER_ID", UserId);
 startActivity(intent);

 On SomeActivity : 

 String userId= getIntent().getStringExtra("("USER_ID");

您可以使用intent类在Activities之间发送数据。它基本上是一条发送给操作系统的消息,您可以在其中描述数据流的源和目的地。类似于从A到B活动的数据。

在活动A(源)中:

Intent intent = new Intent(A.this, B.class);
intent.putExtra("KEY","VALUE");
startActivity(intent);

在活动B(目标)->

Intent intent =getIntent();
String data =intent.getString("KEY");

在这里,您将获得密钥“key”的数据

为了更好地使用,为了简单起见,密钥应该存储在类中,这将有助于将键入错误的风险降至最低

这样地:

public class Constants{
public static String KEY="KEY"
}

现在在活动A中:

intent.putExtra(Constants.KEY,"VALUE");

在活动B中:

String data =intent.getString(Constants.KEY);

使用回调在活动之间进行新的实时交互:

-步骤01:实现共享接口

public interface SharedCallback {
    public String getSharedText(/*you can define arguments here*/);
}

-步骤02:实现共享类

final class SharedMethode {
    private static WeakReference<Context> mContext;

    private static SharedMethode sharedMethode = new SharedMethode();

    private SharedMethode() {
        super();
    }

    public static SharedMethode getInstance() {
        return sharedMethode;
    }

    public void setContext(Context context) {
        if (mContext != null)
            return;

        mContext = new WeakReference<Context>(context);
    }

    public boolean contextAssigned() {
        return mContext != null && mContext.get() != null;
    }

    public Context getContext() {
        return mContext.get();
    }

    public void freeContext() {
        if (mContext != null) mContext.clear();
        mContext = null;
    }
}

-步骤03::在第一个活动中玩代码

public class FirstActivity extends Activity implements SharedCallback {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        // call playMe from here or there
        playMe();
    }

    private void playMe() {
        SharedMethode.getInstance().setContext(this);
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }

    @Override
    public String getSharedText(/*passed arguments*/) {
        return "your result";
    }

}

-步骤04::在SecondActivity中完成游戏

public class SecondActivity extends Activity {

    private SharedCallback sharedCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        if (SharedMethode.getInstance().contextAssigned()) {
            if (SharedMethode.getInstance().getContext() instanceof SharedCallback)
                sharedCallback = (SharedCallback) SharedMethode.getInstance().getContext();

            // to prevent memory leak
            SharedMethode.freeContext();
        }

        // You can now call your implemented methodes from anywhere at any time
        if (sharedCallback != null)
            Log.d("TAG", "Callback result = " + sharedCallback.getSharedText());

    }

    @Override
    protected void onDestroy() {
        sharedCallback = null;
        super.onDestroy();
    }

}

步骤05::您还可以实现backword回调(从First到Second),以从SecondAvctivity获取一些结果或调用一些方法