主な理由は、インテントを送信するプロセス全体がそれほど単純ではないためです。インテントは、システム内、プロセス間などで移動できます。つまり、作成したオブジェクトは、最後に受信したオブジェクトと同じではありません(これは、インテントクラスを拡張して別のアクティビティに送信し、反対側の拡張クラスにキャストして戻してみてください。同じオブジェクトではありません)。
今、私もこれが本当に嫌いです。そのため、次のように機能するインテント(BundleWrappersと呼びます)を操作するのに役立つ基本クラスをいくつか作成しました。
ゲッター/セッターを使用してPOJOを作成し、そのオブジェクトを埋めて、好きなように使用します。
次に、時が来たら、バンドルにシリアル化し、もう一方の端で同じオブジェクトに逆シリアル化します。
そうすれば、他のアクティビティでもゲッターとセッターと同じオブジェクトを使用できます。
インテントがうまくいかない主な理由は、エクストラのすべてのキーを追跡する方法と、バンドルをシリアル化するための追加の実装を見つける必要があることです。
それでも私の方法でも、インテントを使用するのは簡単ではありませんが、パフォーマンスとオブジェクト編成の点でこれまでに見つけた中で最高です。
public abstract class BundleWrapper implements Parcelable {
protected static final String KEY_PARCELABLE = "key_parcelable";
public static final String TAG = BundleWrapper.class.getSimpleName();
public BundleWrapper() {
super();
}
abstract Parcelable getParcelable();
public Bundle toBundle(){
final Bundle bundle = new Bundle();
Parcelable parcelable = getParcelable();
if (parcelable != null) {
bundle.setClassLoader(parcelable.getClass().getClassLoader());
bundle.putParcelable(KEY_PARCELABLE, parcelable);
}
return bundle;
}
public static Object fromBundle(final Intent intent) {
return fromBundle(intent.getExtras());
}
public static Object fromBundle(final Bundle bundle) {
if (bundle != null && bundle.containsKey(KEY_PARCELABLE)) {
bundle.setClassLoader(BundleWrapper.class.getClassLoader());
return bundle.getParcelable(KEY_PARCELABLE);
}
return null;
}
}
これが私の基本クラスです。これを使用するには、単純に拡張して、parcelable(プロセスの遅延部分:)を実装します。
public class WebViewFragmentBundle extends BundleWrapper implements Parcelable {
public static final String TAG = WebViewFragmentBundle.class.getSimpleName();
private String url;
public WebViewFragmentBundle() {
super();
}
public WebViewFragmentBundle(Parcel source) {
this.url = source.readString();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
Parcelable getParcelable() {
return this;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(url);
}
public static final Parcelable.Creator<WebViewFragmentBundle> CREATOR = new Parcelable.Creator<WebViewFragmentBundle>() {
@Override
public WebViewFragmentBundle createFromParcel(Parcel source) {
return new WebViewFragmentBundle(source);
}
@Override
public WebViewFragmentBundle[] newArray(int size) {
return new WebViewFragmentBundle[size];
}
};
}
ユースケースの場合:
public static void launchAugmentedRealityActivityForResult(final Activity context, WebViewFragmentBundle wrapper) {
final Intent intent = new Intent(context, Augmented.class);
intent.putExtras(wrapper.toBundle());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivityForResult(intent, AUGMENTED_RESULT_CODE);
}
次のようにもう一方の端にキャストします。
(WebViewFragmentBundle)BundleWrapper.fromBundle(getIntent());