如何为我的Android应用程序创建凭据
我是一名初级安卓开发者,不知道如何解决这个问题。我使用YouTube数据API获取YouTube评论。我找到了Java的示例代码并粘贴到我的项目中,但没有找到一些方法。我为凭证添加了代码示例。你能帮我吗<找不到代码>授权代码InstalledApp和如何为我的Android应用程序创建凭据,android,google-api,youtube-data-api,Android,Google Api,Youtube Data Api,我是一名初级安卓开发者,不知道如何解决这个问题。我使用YouTube数据API获取YouTube评论。我找到了Java的示例代码并粘贴到我的项目中,但没有找到一些方法。我为凭证添加了代码示例。你能帮我吗授权代码InstalledApp和LocalServerReceiver: public Credential authorize(final NetHttpTransport httpTransport) throws IOException { InputStream in = th
LocalServerReceiver
:
public Credential authorize(final NetHttpTransport httpTransport) throws IOException {
InputStream in = this.getResources().openRawResource(Integer.parseInt(CLIENT_SECRETS));
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
.build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return credential;
}
更新
我重写了一个代码示例,但没有得到任何结果:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText link = findViewById(R.id.editTextLink);
textResult = findViewById(R.id.textResult);
Button sonuc = findViewById(R.id.buttonSonucGetir);
sonuc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (link.getText().toString().length() != 0) {
String link_string = link.getText().toString();
videoId = parseVideoName(link_string);
getResultsFromApi();
} else {
Toast.makeText(getApplicationContext(), "Lütfen Link giriniz !", Toast.LENGTH_LONG);
}
}
});
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
}
public static String parseVideoName(String s) {
String[] find;
if(s.contains("youtu.be/")) {
find = s.split(".be/");
Log.d(TAG, "parseTableName: " + find[1]);
}
else{
find = s.split("v=");
Log.d(TAG, "parseTableName: " + find[1]);
}
return find[1];
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private com.google.api.services.youtube.YouTube mService;
MakeRequestTask(GoogleAccountCredential credential) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new YouTube.Builder(
transport, jsonFactory, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
private List<String> getDataFromApi() throws IOException {
List<String> channelInfo = new ArrayList<String>();
YouTube.CommentThreads.List result = mService.commentThreads()
.list("snippet");
try {
CommentThreadListResponse response = result.setKey(DEVELOPER_KEY).setVideoId(videoId).execute();
List<CommentThread> channels = response.getItems();
Log.d(TAG, "channels: " + channels);
if (channels != null) {
CommentThread channel = channels.get(0);
channelInfo.add("Text original is '" + channel.getSnippet().getTopLevelComment().getSnippet().getTextOriginal() + ", " +
"and author display name is " + channel.getSnippet().getTopLevelComment().getSnippet().getAuthorDisplayName());
}
Log.d(TAG, "channelinfo: " + channelInfo);
Log.d(TAG, "response: " + response);
}
catch (Exception e){
Log.e(TAG,"response error");
e.printStackTrace();
}
return channelInfo;
}
@Override
protected List<String> doInBackground(Void... voids) {
try {
return getDataFromApi();
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(List<String> strings) {
if (strings == null || strings.size() == 0) {
textResult.setText("No results returned.");
} else {
strings.add(0, "Data retrieved using the YouTube Data API:");
textResult.setText(TextUtils.join("\n", strings));
}
}
}
private void getResultsFromApi() {
if (!isDeviceOnline()) {
textResult.setText("No network connection available.");
} else {
new MakeRequestTask(mCredential).execute();
}
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
@AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
private void chooseAccount() {
if (EasyPermissions.hasPermissions(
this, Manifest.permission.GET_ACCOUNTS)) {
String accountName = getPreferences(Context.MODE_PRIVATE)
.getString(PREF_ACCOUNT_NAME, null);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
} else {
// Start a dialog from which the user can choose an account
startActivityForResult(
mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
} else {
// Request the GET_ACCOUNTS permission via a user dialog
EasyPermissions.requestPermissions(
this,
"This app needs to access your Google account (via Contacts).",
REQUEST_PERMISSION_GET_ACCOUNTS,
Manifest.permission.GET_ACCOUNTS);
}
}
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode != RESULT_OK) {
textResult.setText(
"This app requires Google Play Services. Please install " +
"Google Play Services on your device and relaunch this app.");
} else {
getResultsFromApi();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
SharedPreferences settings =
getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.apply();
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == RESULT_OK) {
getResultsFromApi();
}
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(
requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> list) {
// Do nothing.
}
@Override
public void onPermissionsDenied(int requestCode, List<String> list) {
// Do nothing.
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
return connectionStatusCode == ConnectionResult.SUCCESS;
}
private void acquireGooglePlayServices() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
}
}
void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
Dialog dialog = apiAvailability.getErrorDialog(
MainActivity.this,
connectionStatusCode,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
@覆盖
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText-link=findViewById(R.id.editTextLink);
textResult=findViewById(R.id.textResult);
按钮sonuc=findViewById(R.id.ButtonSonSucGetir);
sonuc.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
if(link.getText().toString().length()!=0){
String link_String=link.getText().toString();
videoId=parseVideoName(链接字符串);
getResultsFromApi();
}否则{
Toast.makeText(getApplicationContext(),“Lütfen Link girizing!”,Toast.LENGTH_LONG);
}
}
});
mCredential=GoogleAccountCredential.usingAuth2(
getApplicationContext(),Arrays.asList(作用域))
.setBackOff(新的指数backoff());
}
公共静态字符串parseVideoName(字符串s){
字符串[]查找;
如果(s.contains(“youtu.be/”){
find=s.split(“.be/”);
Log.d(标记“parseTableName:+find[1]);
}
否则{
find=s.split(“v=”);
Log.d(标记“parseTableName:+find[1]);
}
返回find[1];
}
私有类MakeRequestTask扩展了AsyncTask{
私有com.google.api.services.youtube.youtube mService;
MakeRequestTask(GoogleAccountCredential凭证){
HttpTransport-transport=AndroidHttp.newCompatibleTransport();
JsonFactory JsonFactory=JacksonFactory.getDefaultInstance();
mService=newyoutube.Builder(
运输、jsonFactory、凭证)
.setApplicationName(应用程序名称)
.build();
}
私有列表getDataFromApi()引发IOException{
List channelInfo=new ArrayList();
YouTube.CommentThreads.List结果=mService.CommentThreads()
.列表(“片段”);
试一试{
CommentThreadListResponse=result.setKey(DEVELOPER_KEY).setVideoId(videoId).execute();
List channels=response.getItems();
日志d(标签“通道:”+通道);
如果(通道!=null){
CommentThread通道=通道.get(0);
channelInfo.add(“原始文本为“”)+channel.getSnippet().getTopLevel注释().getSnippet().getExtriginal()+”,“+
而作者显示名称为“+channel.getSnippet().GetTopLevel注释().getSnippet().getAuthorDisplayName());
}
Log.d(标签“channelinfo:+channelinfo”);
Log.d(标签“响应:”+响应);
}
捕获(例外e){
Log.e(标记“响应错误”);
e、 printStackTrace();
}
返回channelInfo;
}
@凌驾
受保护列表背景(无效…无效){
试一试{
返回getDataFromApi();
}捕获(例外e){
返回null;
}
}
@凌驾
受保护的void onPostExecute(列表字符串){
if(strings==null | | strings.size()==0){
setText(“没有返回结果”);
}否则{
添加(0,“使用YouTube数据API检索的数据:”);
textResult.setText(TextUtils.join(“\n”,字符串));
}
}
}
私有void getResultsFromApi(){
如果(!isDeviceOnline()){
setText(“没有可用的网络连接”);
}否则{
新建MakeRequestTask(mCredential.execute();
}
}
私有布尔值isDeviceOnline(){
连接管理器连接管理器=
(ConnectionManager)getSystemService(Context.CONNECTIVITY_服务);
NetworkInfo NetworkInfo=connMgr.getActiveNetworkInfo();
return(networkInfo!=null&&networkInfo.isConnected());
}
@授予后权限(请求权限获取帐户)
私有void chooseAccount(){
如果(EasyPermissions.hasPermissions(
这个,Manifest.permission.GET_账户){
String accountName=getPreferences(Context.MODE\u PRIVATE)
.getString(首选帐户名称,空);
if(accountName!=null){
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
}否则{
//启动一个对话框,用户可以从中选择帐户
startActivityForResult(
mCredential.newChooseAccountContent(),
请求(账户选取者);
}
}否则{
//通过用户对话框请求GET_ACCOUNTS权限
EasyPermissions.requestPermissions(
这
“此应用程序需要访问您的Google帐户(通过联系人)。”,
请求\u权限\u获取\u帐户,
Manifest.permission.GET_账户);
}
}
@凌驾
活动结果上的受保护无效(
int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
开关(请求
2020-12-14 22:36:57.821 6387-6442/com.mmb.rafflegram W/System.err: java.lang.IllegalArgumentException: the name must not be empty: null
2020-12-14 22:36:57.821 6387-6442/com.mmb.rafflegram W/System.err: at android.accounts.Account.<init>(Account.java:83)
2020-12-14 22:36:57.821 6387-6442/com.mmb.rafflegram W/System.err: at android.accounts.Account.<init>(Account.java:68)
2020-12-14 22:36:57.821 6387-6442/com.mmb.rafflegram W/System.err: at com.google.android.gms.auth.zzd.getToken(Unknown Source:1)
2020-12-14 22:36:57.821 6387-6442/com.mmb.rafflegram W/System.err: at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source:55)
2020-12-14 22:36:57.821 6387-6442/com.mmb.rafflegram W/System.err: at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:269)
2020-12-14 22:36:57.821 6387-6442/com.mmb.rafflegram W/System.err: at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:294)
2020-12-14 22:36:57.821 6387-6442/com.mmb.rafflegram W/System.err: at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
2020-12-14 22:36:57.822 6387-6442/com.mmb.rafflegram W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
2020-12-14 22:36:57.822 6387-6442/com.mmb.rafflegram W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
2020-12-14 22:36:57.822 6387-6442/com.mmb.rafflegram W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
2020-12-14 22:36:57.822 6387-6442/com.mmb.rafflegram W/System.err: at com.mmb.rafflegram.MainActivity$MakeRequestTask.getDataFromApi(MainActivity.java:135)
2020-12-14 22:36:57.822 6387-6442/com.mmb.rafflegram W/System.err: at com.mmb.rafflegram.MainActivity$MakeRequestTask.doInBackground(MainActivity.java:156)
2020-12-14 22:36:57.822 6387-6442/com.mmb.rafflegram W/System.err: at com.mmb.rafflegram.MainActivity$MakeRequestTask.doInBackground(MainActivity.java:117)
2020-12-14 22:36:57.822 6387-6442/com.mmb.rafflegram W/System.err: at android.os.AsyncTask$3.call(AsyncTask.java:394)
2020-12-14 22:36:57.822 6387-6442/com.mmb.rafflegram W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2020-12-14 22:36:57.822 6387-6442/com.mmb.rafflegram W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
2020-12-14 22:36:57.823 6387-6442/com.mmb.rafflegram W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2020-12-14 22:36:57.823 6387-6442/com.mmb.rafflegram W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2020-12-14 22:36:57.823 6387-6442/com.mmb.rafflegram W/System.err: at java.lang.Thread.run(Thread.java:923)