[JAVA] Holen Sie sich Youtube-Videoinformationen mit Retrofit und behalten Sie sie in der Android-App.

In diesem Artikel werden wir drei Hauptaufgaben erledigen.

  1. [Registriere deine App in der Liste, wenn du sie auf Youtube "teilst". ](# -1-Registriere deine App in der Liste, wenn du sie von YouTube aus teilst.)
  2. [Erhalten Sie beim "Teilen" eine ID aus den Linkinformationen und erhalten Sie Youtube-Videoinformationen von dieser ID. ](# -2-Erhalte die ID aus den Linkinformationen beim Teilen und erhalte die Videoinformationen von YouTube von dieser ID)
  3. [Greifen Sie mit Retrofit & Gson auf die API zu. Die Videoinformationen werden in der Erfassungsanwendung angezeigt. ](# -3-retrofit - Zugriff auf API mit gson Videoinformationen abrufen Anzeige auf App-)

Der Code ist hier. SharedText

teilst

1. Registrieren Sie Ihre App in der Liste, wenn Sie sie von Youtube aus "teilen".

Fügen Sie zunächst einen Absichtsfilter zu Manifest.xml hinzu.

AndroidManifest.xml


// ...Unterlassung...
  <activity android:name=".SharedActivity">
      <intent-filter>
          <action android:name="android.intent.action.SEND" />
          <category android:name="android.intent.category.DEFAULT" />
          <data android:mimeType="text/plain"/>
      </intent-filter>
  </activity>
// ...Unterlassung...

Versuchen Sie als Nächstes, es mit SharedActivity.java zu empfangen.

SharedActivity.java


public class SharedActivity extends AppCompatActivity {

    TextView textView;
    ImageView thumbnail;

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

        textView = findViewById(R.id.movieId);
        thumbnail = findViewById(R.id.thumbnail);

        Intent intent = getIntent();
        String id = null;

        if(intent.getType().equals("text/plain")){
            String text = intent.getStringExtra(Intent.EXTRA_TEXT);
            Log.d("text",text);
        }
    }
// ...Unterlassung...
}

Jetzt können Sie den Link erhalten, der von Intent an Text übergeben wurde.

[Referenz]

2. Holen Sie sich die ID aus den Linkinformationen beim "Teilen" und deren Holen Sie sich Youtube-Videoinformationen von der ID.

So erhalten Sie einen Ausweis

Dies extrahierte gehorsam die ID aus der Verbindungszeichenfolge. https://youtu.be/yT_ylSCgY6Q Da Sie die Zeichenfolge wie folgt erhalten können, ist das nachfolgende "yT_ylSCgY6Q" die ID des Videos.

Über den obigen Link gelangen Sie übrigens zu BUMP OF CHICKEN feat. HATSUNE MIKU "ray".

Holen Sie sich Youtube-Videoinformationen.

Informationen zum Abrufen von Youtube-Videos finden Sie im Artikel Abrufen von YouTube-Videoinformationen mithilfe der Daten-API v3, ** Youtube Data API ** wird verwendet. Erhalten Sie den API-Schlüssel und geben Sie die folgende URL in Ihren Browser ein. Informationen zum Erwerb des API-Schlüssels finden Sie unter Abrufen von YouTube-Videoinformationen mithilfe der Daten-API v3.

https://www.googleapis.com/youtube/v3/videos?id=yT_ylSCgY6Q&key=【API Key】&fields=items(id,snippet(channelTitle,title,thumbnails),statistics)&part=snippet,contentDetails,statistics

Geben Sie den erfassten Schlüssel im Teil [API-Schlüssel] ein.

Das Ergebnis ist wie folgt.

result


{
 "items": [
  {
   "id": "yT_ylSCgY6Q",
   "snippet": {
    "title": "BUMP OF CHICKEN feat. HATSUNE MIKU「ray」",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/default.jpg ",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/mqdefault.jpg ",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/hqdefault.jpg ",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/sddefault.jpg ",
      "width": 640,
      "height": 480
     },
     "maxres": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/maxresdefault.jpg ",
      "width": 1280,
      "height": 720
     }
    },
    "channelTitle": "BUMP OF CHICKEN"
   },
   "statistics": {
    "viewCount": "12691874",
    "likeCount": "65136",
    "dislikeCount": "3062",
    "favoriteCount": "0",
    "commentCount": "4337"
   }
  }
 ]
}

[Referenz]

3. Zugriff auf API mit Retrofit & Gson. Die Videoinformationen werden in der Erfassungsanwendung angezeigt.

Überblick

Einführung

dependencies {
    // ...Unterlassung...
    implementation 'com.google.code.gson:gson:2.8.4'
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    // ...Unterlassung...
}

[Referenz]

Implementierung der API-Schnittstelle

ApiService.java


public interface ApiService {
    @Headers("Accept-Language: ja")
    @GET("/youtube/v3/videos?")
    Call<APIResponse> requestMovie(@Query("id") String id,
                                    @Query("key") String key,
                                    @Query("fields") String fields,
                                    @Query("part") String part);
}

Definieren Sie eine Klasse, in der die von der API erhaltenen Daten als Java-Objekt gespeichert werden

APIResponse.java


public class APIResponse {

    public List<Item> items;

    public List<Item> getItems() {
        return items;
    }
}

Item.java


public class Item {

    @SerializedName("id")
    private String id;

    @SerializedName("snippet")
    private Snippet snippet;

    @SerializedName("statistics")
    private Statistics statistics;

    public String getId() {
        return id;
    }

    public Snippet getSnippet() {
        return snippet;
    }

    public Statistics getStatistics() {
        return statistics;
    }
}

Snippet.java


public class Snippet {

    @SerializedName("title")
    private String title;

    @SerializedName("thumbnails")
    private Thumbnails thumbnails;

    public class Thumbnails {

        @SerializedName("default")
        public Default aDefault;

        @SerializedName("medium")
        public Medium medium;

        @SerializedName("high")
        public High high;

        public High getHigh() {
            return high;
        }

        @SerializedName("standard")
        public Standard standard;

        @SerializedName("maxres")
        public Maxres maxres;


        public class Default {
            String url;
            String width;
            String height;
        }

        public class Medium {
            String url;
            String width;
            String height;

        }

        public class High {
            String url;
            String width;
            String height;

            public String getUrl() {
                return url;
            }
        }

        public class Standard {
            String url;
            String width;
            String height;
        }

        public class Maxres {
            String url;
            String width;
            String height;
        }

    }

    @SerializedName("channelTitle")
    String channelTitle;

    public String getTitle() {
        return title;
    }

    public Thumbnails getThumbnails() {
        return thumbnails;
    }

    public String getChannelTitle() {
        return channelTitle;
    }
}

Statistics.java


public class Statistics {

    @SerializedName("viewCount")
    String viewCount;

    @SerializedName("likeCount")
    String likeCount;

    @SerializedName("dislikeCount")
    String dislikeCount;

    @SerializedName("favoriteCount")
    String favoriteCount;

    @SerializedName("commentCount")
    String commentCount;


    public String getViewCount() {
        return viewCount;
    }

    public String getLikeCount() {
        return likeCount;
    }

    public String getDislikeCount() {
        return dislikeCount;
    }

    public String getFavoriteCount() {
        return favoriteCount;
    }

    public String getCommentCount() {
        return commentCount;
    }
}

Als ich den Artikel schrieb, bemerkte ich, dass ich ihn schrieb, ohne zu viel über die Modifikatoren nachzudenken. Ich wäre Ihnen dankbar, wenn Sie etwas dagegen tun könnten.

Implementierung der Verarbeitung zum Zugriff auf die YouTube Data API v3 und zum Abrufen von Videoinformationen

MainActivity.java


public class MainActivity extends AppCompatActivity {

    private Retrofit mRetrofit;
    private ApiService mService;

    //API-SCHLÜSSEL Erstellt von der Konsole
    private final String API_KEY = "dummyAPIKey"; //Bitte ändern Sie den API-Schlüssel entsprechend.
    private final String FIELDS = "items(id,snippet(channelTitle,title,thumbnails),statistics)";
    private final String PART = "snippet,contentDetails,statistics";

    // "BUMP OF CHICKEN feat. HATSUNE MIKU「ray」"
    private String testId = "yT_ylSCgY6Q";

    ImageView picture;
    TextView title;
    Button button;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRetrofit = new Retrofit.Builder()
                .baseUrl("https://www.googleapis.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        mService = mRetrofit.create(ApiService.class);

        picture = findViewById(R.id.picture);
        title = findViewById(R.id.title);
        button = findViewById(R.id.button);
        button.setOnClickListener(onClickListener);
    }
    
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Call<APIResponse> mCall = mService.requestMovie(testId,API_KEY,FIELDS,PART);

            mCall.enqueue(new Callback<APIResponse>() {
                @Override
                public void onResponse(Call<APIResponse> call, Response<APIResponse> response) {

                    //Artikel aus Antwort abrufen
                    List<Item> items = response.body().getItems();

                    for(Item item : items){

                        Uri uri = Uri.parse(item.getSnippet().getThumbnails().getHigh().getUrl());
                        Uri.Builder builder = uri.buildUpon();
                        AsyncTaskHttpRequest task = new AsyncTaskHttpRequest(picture);
                        task.execute(builder);
                        
                        title.setText(item.getSnippet().getTitle());
                    }
                }

                @Override
                public void onFailure(Call<APIResponse> call, Throwable t) {

                }
            });

        }
    };
    

}

Außerdem habe ich auf die folgende Site verwiesen, um das Bild von der URL abzurufen und in ImageView anzuzeigen. Beachten Sie, dass die AsyncTaskHttpRequest-Klasse auch dann undefiniert ist, wenn Sie den obigen Code kopieren und einfügen. [Referenz]

Implementierung der Layoutdatei

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/title"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title"
        app:layout_constraintVertical_bias="0.3" />

</android.support.constraint.ConstraintLayout>

activity.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".SharedActivity">

    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:padding="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.201"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/movieId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="TextView"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

AndroidManifest.xml Für alle Fälle werde ich auch die Manifestdatei veröffentlichen.

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tomiyama.noir.sharedtext">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SharedActivity">

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain"/>

            </intent-filter>
        </activity>
    </application>

</manifest>

[Referenz] Dies war sehr hilfreich beim Zugriff auf die API rund um Retrofit. Weitere Informationen finden Sie im Code auf Github.

Recommended Posts

Holen Sie sich Youtube-Videoinformationen mit Retrofit und behalten Sie sie in der Android-App.
Holen Sie sich Ihre Versionsnummer in der Android-App
[Android-Entwicklung] Holen Sie sich mit Java Bilder vom Server und legen Sie sie in ImageView fest! !!
Holen Sie sich Videoinformationen von Nikorepo und werfen Sie sie zu Slack
Holen Sie sich Youtube-Kanalinformationen mit der Rails-App (mit Yt gem)
[Rails] Erhalten Sie access_token zum Zeitpunkt der Twitter-Authentifizierung mit Sorcery und speichern Sie es in der Datenbank
Stellen Sie die Sensorinformationen von Raspberry Pi in Java grafisch dar und überprüfen Sie sie mit einem Webbrowser
Fügen Sie Android eine vorgefertigte JAR-Bibliothek hinzu und rufen Sie sie im Framework auf
[Rails] So erhalten Sie die aktuell mit devise angemeldeten Benutzerinformationen
Ist es möglich, die Bibliothek (aar) in die Android-Bibliothek (aar) zu stellen und zu verwenden?
Die Android App stürzt ab. Klicken Sie einfach auf eine Schaltfläche und es wird fallen.
Ich mache eine Android-App und sie steckt voller Fehler und wie man sie löst
[Android] Verzweifelte Geschichte mit UserId und SharedUserId der App
Ich habe versucht, YouTube-Video von DB mit haml aufzurufen und es eingebettet anzuzeigen
Lassen Sie das Armbandgerät mit Bluetooth über die Android-App vibrieren
Pulldown in der ursprünglichen App mit Active Hash implementiert
Holen Sie sich Standortinformationen mit Rails und sortieren Sie in aufsteigender Reihenfolge
Greifen Sie mit Get on Android auf die Web-API zu und verarbeiten Sie Json (vorerst Java).
Bis Sie mit Maven ein von Scala geschriebenes Projekt erstellen und es mit dem Befehl scala ausführen.
Holen Sie sich Android-Standortinformationen
Android App, die Bilder aus der Galerie auswählt und anzeigt
So erhalten Sie Werte in Echtzeit mit TextWatcher (Android)
Informationen in einer Instanz abrufen und Zahlen berechnen Standardversion
In Redmine können Sie das Projekt mit Project.find (<Kennung>) abrufen.
Abrufen von Fehlerinformationen mithilfe von DefaultErrorAttributes und ErrorAttributeOptions in Spring Boot 2.3
Elasticsearch> Mit Docker erstellen, Twitter-Informationen abrufen und mit Kibana visualisieren
Wenn sich dies mit der Option disable_with in Safari nicht ändert
[Android] Ändern Sie den App-Namen und das App-Symbol für jeden Geschmack
Der Unterschied zwischen der Programmierung mit Ruby-Klassen und der Programmierung ohne Ruby-Klassen
Technische Ursachen und Gegenmaßnahmen für die Punkte, denen ich mit der ersten Android-App und Kotlin verfallen war
[Für Super-Anfänger] Das Mindestwissen, das Sie mit Hashes und Symbolen berücksichtigen möchten
Generieren Sie mit TableGenerator of Hibernate (JPA) eine Seriennummer und speichern Sie diese in der ID von String.