Android 에서 전달 대상 의 세 가지 방법의 실현

Android 에 서 는 Activity 와 Fragment 간 전달 대상 을 대상 을 서열 화하 여 Bundle 또는 Intent 에 저장 해 전달 할 수도 있 고,대상 을 JSON 문자열 로 전환 해 전달 할 수도 있다.
직렬 화 대상 은 자바 의 Serializable 인터페이스,Parcelable 인 터 페 이 스 를 사용 할 수 있 습 니 다.JSON 문자열 로 전환 하면 Gson 등 라 이브 러 리 를 사용 할 수 있 습 니 다.
1.Serializable

public class Author implements Serializable{ 
  private int id; 
 
  private String name; 
 
  //... 
} 

public class Book implements Serializable{ 
  private String title; 
  private Author author; 
  //... 
} 
데 이 터 를 전달 하 다

 Book book=new Book();  
 book.setTitle("Java    ");  
 Author author=new Author();  
 author.setId(1);  
 author.setName("Bruce Eckel");  
 book.setAuthor(author);  
 Intent intent=new Intent(this,SecondActivity.class);  
 intent.putExtra("book",book);  
 startActivity(intent); 
수신 데이터

 Book book= (Book) getIntent().getSerializableExtra("book"); 
 Log.d(TAG,"book title->"+book.getTitle()); 
 Log.d(TAG,"book author name->"+book.getAuthor().getName()); 
2.JSON 문자열 로 전환

public class Author{ 
  private int id; 
 
  private String name; 
 
  //... 
} 

public class Book{ 
  private String title; 
  private Author author; 
  //... 
} 
데 이 터 를 전달 하 다

Book book=new Book(); 
book.setTitle("Java    "); 
Author author=new Author(); 
author.setId(1); 
author.setName("Bruce Eckel"); 
book.setAuthor(author); 
Intent intent=new Intent(this,SecondActivity.class); 
intent.putExtra("book",new Gson().toJson(book)); 
startActivity(intent); 
수신 데이터

String bookJson=getIntent().getStringExtra("book"); 
Book book=new Gson().fromJson(bookJson,Book.class); 
Log.d(TAG,"book title->"+book.getTitle()); 
Log.d(TAG,"book author name->"+book.getAuthor().getName()); 
3.Parcelable 사용
Parcelable 인 터 페 이 스 를 실현 하려 면 두 가지 방법 이 필요 합 니 다.
describe Contents 방법.내용 인터페이스 설명,기본 값 으로 0 을 되 돌려 주면 됩 니 다writeToParcel 방법.전 달 된 데 이 터 를 Parcel 용기 에 포장 합 니 다이 두 가지 방법 을 실현 하려 면 Parcel 용기 의 데 이 터 를 읽 기 위해 Parcel lable.Creator 인터페이스의 인 스 턴 스 를 만들어 야 합 니 다.

public class Author implements Parcelable{ 
  private int id; 
 
  private String name; 
 
  //setter & getter... 
 
  @Override 
  public int describeContents() { 
 
    return 0; 
  } 
 
  @Override 
  public void writeToParcel(Parcel dest, int flags) { 
    //               Parcel .           Parcel    , 
    //    parcel       
    dest.writeString(name); 
    dest.writeInt(id); 
 
  } 
  public static final Creator<Author> CREATOR=new Creator<Author>() { 
    @Override 
    public Author createFromParcel(Parcel source) { 
      // Parcel          ,   Parcelable       。 
      Author author=new Author(); 
      author.setName(source.readString()); 
      author.setId(source.readInt()); 
      return author; 
    } 
 
    @Override 
    public Author[] newArray(int size) { 
      //       T,   size   ,    (return new T[size])  。                 。 
      return new Author[size]; 
    } 
  }; 
} 


public class Book implements Parcelable{ 
  private String title; 
  private Author author; 
  //setter & getter... 
 
  @Override 
  public int describeContents() { 
    return 0; 
  } 
 
  @Override 
  public void writeToParcel(Parcel dest, int flags) { 
    dest.writeString(title); 
    dest.writeParcelable(author,flags); 
  } 
  public static final Creator<Book> CREATOR=new Creator<Book>() { 
    @Override 
    public Book createFromParcel(Parcel source) { 
      Book book=new Book(); 
      book.setTitle(source.readString()); 
      book.setAuthor(source.<Author>readParcelable(Author.class.getClassLoader())); 
      return book; 
    } 
 
    @Override 
    public Book[] newArray(int size) { 
      return new Book[0]; 
    } 
  }; 
} 
데 이 터 를 전달 하 다

Book book=new Book(); 
book.setTitle("Java    "); 
Author author=new Author(); 
author.setId(1); 
author.setName("Bruce Eckel"); 
book.setAuthor(author); 
Intent intent=new Intent(this,SecondActivity.class); 
intent.putExtra("book",book); 
startActivity(intent); 
수신 데이터

Book book=getIntent().getParcelableExtra("book"); 
Log.d(TAG,"book title->"+book.getTitle()); 
Log.d(TAG,"book author name->"+book.getAuthor().getName()); 
4.성능 분석
테스트 를 통 해 우 리 는 다음 그림 의 효 과 를 얻 었 다.
 
문자열 로 전환 하 는 속도 가 가장 느 린 것 으로 나 타 났 다.Seralizable 다음으로 Parcelable 은 Seralizable 보다 10 배 빠르다.그래서 성능 을 고려 하여 우 리 는 반드시 Parcelable 을 우선 선택 할 것 이다.그러나 Parcelable 은 반복 되 는 템 플 릿 코드 가 많 습 니 다.이 동작 을 어떻게 간소화 하 는 지 는 다음 과 같은 주요 설명 입 니 다.
5.Parcel 조작 간소화
안 드 로 이 드 스튜디오 를 사용 하면 안 드 로 이 드-parcelable-intellij-plugin 플러그 인 을 설치 하거나 템 플 릿 을 설정 하여 작업 할 수 있 습 니 다.
5.1 parceler
위의 조작 을 제외 하고 대량의 제3자 라 이브 러 리 가 Parcelable 작업 을 간소화 합 니 다.물론 이 라 이브 러 리 를 사용 하면 Parcelable 의 성능 을 떨 어 뜨 릴 수 있 습 니 다.Parceler 는 바로 이런 라 이브 러 리 입 니 다.
Parceler 는 Model 을 정의 할 때@Parcel 로 주 해 를 하고 데 이 터 를 전달 할 때 Parcels 의 wrap 방법 으로 Parcelable 대상 으로 포장 합 니 다.데 이 터 를 가 져 올 때 대상 을 Parcels 의 unwrap 방법 으로 가 져 옵 니 다.

@Parcel 
 
public class Author { 
 
  int id; 
 
  String name; 
 
  //setter & getter... 
} 

@Parcel 
public class Book { 
  String title; 
  Author author; 
  //setter & getter 
} 
전달 대상

Book book=new Book(); 
book.setTitle("Java    "); 
Author author=new Author(); 
author.setId(1); 
author.setName("Bruce Eckel"); 
book.setAuthor(author); 
Intent intent=new Intent(this,SecondActivity.class); 
intent.putExtra("book", Parcels.wrap(book)); 
startActivity(intent); 
수신 대상

Book book= Parcels.unwrap(getIntent().getParcelableExtra("book")); 
Log.d(TAG,"book title->"+book.getTitle()); 
Log.d(TAG,"book author name->"+book.getAuthor().getName()); 
Parceler 외 에 도 auto-parcel,Parcelable CodeGenerator,Parcelable Generator 등 제3자 라 이브 러 리 도 있 습 니 다.여기 서 저 는 설명 을 하지 않 고 관심 이 있 는 친구 들 은 스스로 연구 할 수 있 습 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기