15

重複の可能性:
Android のアクティビティ間でデータを渡すにはどうすればよいですか?

私はカードゲームを作っており、カードを捨てるアクティビティとスコアを表示するアクティビティがあります。問題は、いくつかのオブジェクト (プレーヤーとディーラーの手) を他のアクティビティに渡して、スコアの imageViews をプレーヤーの手の中にあるカードに設定できるようにすることです。これどうやってするの?セキュリティなどは気にせず、最も簡単な方法が欲しいだけです。

4

5 に答える 5

12

インテント内でバンドルを使用することは、セキュリティに関するものではありません。それは、Android の担当者がその方法を単純明快にしたためです。私の意見では、バンドルとインテントを使用してより大きなオブジェクトを渡すことはお勧めできません。実装が複雑になりすぎて、オブジェクトをプリミティブまで取得し (parcelable を使用する場合)、メモリ内の反対側にコピーを作成します (1 つのオブジェクトを取得し、すべてをインテント内に設定してから、それを再作成します)。反対側はそれから新しいコピーを作成します) これは、メモリ フットプリントが大きいオブジェクトには適していません。

私は提案します:

  1. シングルトンストアを使用するか
  2. アプリケーション クラスの使用 (シングルトンのようにも機能します)

私はしばしば、(atomic Integer から) 整数キーが私によって生成される hashMap と、マップ内に配置されたオブジェクトを持つシングルトンを使用しています。インテント内の ID をエクストラとして送信し、インテントからキーを取得し、シングルトンにアクセスして (そのマップから) オブジェクトを取得および削除し、それを新しいアクティビティ/サービスで使用することで、ID を反対側で取得するだけです。

以下は、次のようなサンプルです。

(注:これは、すべての実装方法の詳細を確認したい場合に備えて、残りのリクエスト用の私のライブラリ(https://github.com/darko1002001/android-rest-client)の一部です)。あなたの場合、コードの一部を取り除いて自分のものに置き換える必要がありますが、一般的な考え方は同じです。

/**
 * @author Darko.Grozdanovski
 */
public class HttpRequestStore {

    public static final String TAG = HttpRequestStore.class.getSimpleName();

    public static final String KEY_ID = "id";
    public static final String IS_SUCCESSFUL = "isSuccessful";

    private static final HashMap<Integer, RequestWrapper> map = new HashMap<Integer, RequestWrapper>();

    private final AtomicInteger counter = new AtomicInteger();
    private static Class<?> executorServiceClass = HTTPRequestExecutorService.class;

    private final Context context;
    private static HttpRequestStore instance;

    private HttpRequestStore(final Context context) {
        this.context = context;
    }

    public static HttpRequestStore getInstance(final Context context) {
        if (instance == null) {
            instance = new HttpRequestStore(context.getApplicationContext());
        }
        return instance;
    }

    public static void init(final Class<?> executorServiceClass) {
        HttpRequestStore.executorServiceClass = executorServiceClass;
    }

    public Integer addRequest(final RequestWrapper block) {
        return addRequest(counter.incrementAndGet(), block);
    }

    public Integer addRequest(final Integer id, final RequestWrapper block) {
        map.put(id, block);
        return id;
    }

    public void removeBlock(final Integer id) {
        map.remove(id);
    }

    public RequestWrapper getRequest(final Integer id) {
        return map.remove(id);
    }

    public RequestWrapper getRequest(final Intent intent) {
        final Bundle extras = intent.getExtras();
        if (extras == null || extras.containsKey(KEY_ID) == false) {
            throw new RuntimeException("Intent Must be Filled with ID of the block");
        }
        final int id = extras.getInt(KEY_ID);
        return getRequest(id);
    }

    public Integer launchServiceIntent(final HttpRequest block) {
        return launchServiceIntent(block, null);
    }

    public Integer launchServiceIntent(final HttpRequest block, RequestOptions options) {
        if (executorServiceClass == null) {
            throw new RuntimeException("Initialize the Executor service class in a class extending application");
        }
        if (isServiceAvailable() == false) {
            throw new RuntimeException("Declare the " + executorServiceClass.getSimpleName() + " in your manifest");
        }
        final Intent service = new Intent(context, executorServiceClass);
        final RequestWrapper wrapper = new RequestWrapper(block, options);
        final Integer requestId = addRequest(wrapper);
        service.putExtra(KEY_ID, requestId);
        context.startService(service);
        return requestId;
    }

    public boolean isServiceAvailable() {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(context, executorServiceClass);
        final List<ResolveInfo> resolveInfo = packageManager.queryIntentServices(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfo.size() > 0) {
            return true;
        }
        return false;
    }

}
于 2012-11-19T07:43:47.270 に答える
1

Bundle を使用して、他のアクティビティで変数を共有できます。他のアクティビティで独自のクラスオブジェクトを渡したい場合はParcelable、クラスに使用します

これが例です

public class Person implements Parcelable {
     private int age;
     private String name;    

     // Setters and Getters
     // ....


     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeString(name);
         out.writeInt(age);
     }

     public static final Parcelable.Creator<Person> CREATOR
             = new Parcelable.Creator<Person>() {
         public Person createFromParcel(Parcel in) {
             return new Person(in);
         }

         public Person[] newArray(int size) {
             return new Person[size];
         }
     };

     private Person(Parcel in) {
         name = in.readString();
         age = in.readInt();
     }
 }

Personオブジェクトをバンドルに挿入します

Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable("bob", new Person());

Personオブジェクトの取得

Intent i = getIntent();
Bundle b = i.getExtras();

Person p = (Person) b.getParcelable("bob");
于 2012-11-19T07:31:28.163 に答える
0

バンドルまたは共有設定のいずれかを共有変数に使用するか、将来使用するために変数を保存することができます。

ここにある共有設定の例ここ にあるバンドルの例

于 2012-11-19T07:25:26.073 に答える
0

シングルトンが最善のアプローチになります

于 2012-11-19T07:26:55.197 に答える
0

インテントエクストラを使用できます、

Intent intent = new Intent(getBaseContext(), NewActivity.class);
intent.putExtra("DATA_KEY", data);
startActivity(intent)

インテントのドキュメントには、より多くの情報があります(「エクストラ」というタイトルのセクションを参照してください)。

于 2012-11-19T07:26:55.303 に答える