Android 简明教程

Android - Facebook Integration

Android 允许您的应用程序连接到 Facebook 并分享数据或任何类型的更新。本章讲述如何将 Facebook 集成到您的应用程序。

Android allows your application to connect to facebook and share data or any kind of updates on facebook. This chapter is about integrating facebook into your application.

您可以通过两种方式集成 Facebook 并从您的应用程序分享内容。这些方式如下所示:

There are two ways through which you can integrate facebook and share something from your application. These ways are listed below −

  1. Facebook SDK

  2. Intent Share

Integrating Facebook SDK

这是连接到 Facebook 的第一种方式。您需要注册您的应用程序,然后接收一些应用程序 ID,之后您必须下载 Facebook SDK 并将其添加到您的项目中。步骤如下:

This is the first way of connecting with facebook. You have to register your application and then receive some Application Id , and then you have to download the facebook SDK and add it to your project. The steps are listed below:

Generating application signature

您需要生成一个密钥签名,但在生成之前,确保您已经安装了 SSL,否则您需要下载 SSL。您可以在 here 处下载。

You have to generate a key signature, but before you generate it, make sure you have SSL installed, otherwise you have to download SSl. It can be downloaded here.

现在打开命令提示符并重定向到您的 java jre 文件夹。到达该位置后,准确输入此命令。您需要用反引号中的路径替换您可以在 Eclipse 中通过选择窗口标签和选择首选项标签,然后从左侧选择 Android 下的构建选项找到的密钥库路径。

Now open command prompt and redirect to your java jre folder. Once you reach there, type this command exactly. You have to replace the path in the inverted commas with your keystore path which you can found in eclipse by selecting the window tab and selecting the preferences tab and then selecting the build option under android from left side.

keytool -exportcert -alias androiddebugkey -keystore "your path"
   | openssl sha1 -binary | openssl base64

输入后,它会提示您输入密码。输入 android 作为密码,然后复制给您的密钥。如下图所示:

Once you enter it, you will be prompt for password. Give android as the password and then copy the key that is given to you. It is shown in the image below −

facebook 2

Registering your application

现在,在 developers.facebook.com/apps 中创建一个新的 Facebook 应用程序并填写所有信息。如下所示:

Now create a new facebook application at developers.facebook.com/apps and fill all the information. It is shown below −

facebook 3

现在转到本机 Android 应用程序部分,填写您的项目和类名,并粘贴您在步骤 1 中复制的哈希。如下所示:

Now move to the native android app section and fill in your project and class name and paste the hash that you copied in step 1. It is shown below −

facebook 4

如果一切正常,您将收到带有密码的应用程序 ID。只需复制应用程序 ID 并将其保存在某个位置。如下图所示:

If everything works fine, you will receive an application ID with the secret. Just copy the application id and save it somewhere. It is shown in the image below −

facebook 5

Downloading SDK and integrating it

下载 Facebook SDK here 。将其导入到 Eclipse 中。导入后,右键单击您的 Facebook 项目并单击属性。单击 Android,单击添加按钮,然后选择 Facebook SDK 作为项目。单击确定。

Download facebook sdk here. Import this into eclipse. Once imported, right click on your facebook project and click on properties.Click on android, click on add button and select facebook sdk as the project.Click ok.

Creating facebook login application

一旦完成所有操作,您就可以运行该 SDK 附带的示例或创建您自己的应用程序。为了登录,您需要调用 openActiveSession 方法并实现其回调。其语法如下:

Once everything is complete , you can run the samples, that comes with SDK or create your own application. In order to login, you need to call openActiveSession method and implements its callback. Its syntax is given below −

// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {

   // callback when session changes state
   public void call(Session session, SessionState state, Exception exception) {
      if (session.isOpened()) {
         // make request to;2 the /me API
         Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

            // callback after Graph API response with user object
            @Override
            public void onCompleted(GraphUser user, Response response) {
               if (user != null) {
                  TextView welcome = (TextView) findViewById(R.id.welcome);
                  welcome.setText("Hello " + user.getName() + "!");
               }
            }
         });
      }
   }
}

Intent share

意图共享用于在应用程序之间共享数据。在此策略中,我们不会处理 SDK 内容,而是让 Facebook 应用程序处理它。我们只需调用 Facebook 应用程序并将数据传递以进行共享。通过此方式,我们可以在 Facebook 上共享内容。

Intent share is used to share data between applications. In this strategy, we will not handle the SDK stuff, but let the facebook application handles it. We will simply call the facebook application and pass the data to share. This way, we can share something on facebook.

Android 提供意图库,用来在活动和应用程序之间共享数据。为了使用它作为共享意图,我们必须将共享意图的类型指定为 ACTION_SEND 。其语法如下:

Android provides intent library to share data between activities and applications. In order to use it as share intent , we have to specify the type of the share intent to ACTION_SEND. Its syntax is given below −

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);

接下来您需要做的就是定义要传递的数据类型,然后传递数据。其语法如下:

Next thing you need to is to define the type of data to pass , and then pass the data. Its syntax is given below −

shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from tutorialspoint");
startActivity(Intent.createChooser(shareIntent, "Share your thoughts"));

除了这些方法,还有其他允许意图处理的方法。它们列在下面 −

Apart from the these methods, there are other methods available that allows intent handling. They are listed below −

Sr.No

Method & description

1

addCategory(String category) This method add a new category to the intent.

2

createChooser(Intent target, CharSequence title) Convenience function for creating a ACTION_CHOOSER Intent

3

getAction() This method retrieve the general action to be performed, such as ACTION_VIEW

4

getCategories() This method return the set of all categories in the intent and the current scaling event

5

putExtra(String name, int value) This method add extended data to the intent.

6

toString() This method returns a string containing a concise, human-readable description of this object

Example

以下示例演示了如何使用 IntentShare 在 Facebook 上共享数据。它创建了一个基本的应用程序,允许你在 Facebook 上分享文本。

Here is an example demonstrating the use of IntentShare to share data on facebook. It creates a basic application that allows you to share some text on facebook.

要试验此示例,您可以在实际设备或模拟器上运行它。

To experiment with this example, you can run this on an actual device or in an emulator.

Steps

Description

1

You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication.

2

Modify src/MainActivity.java file to add necessary code.

3

Modify the res/layout/activity_main to add respective XML components.

4

Run the application and choose a running android device and install the application on it and verify the results.

以下是修改后的主活动文件内容 MainActivity.java

Following is the content of the modified main activity file MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;

import java.io.FileNotFoundException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
   private ImageView img;

   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      img=(ImageView)findViewById(R.id.imageView);
      Button b1=(Button)findViewById(R.id.button);

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            Uri screenshotUri = Uri.parse("android.
            resource://comexample.sairamkrishna.myapplication/*");

            try {
               InputStream stream = getContentResolver().openInputStream(screenshotUri);
            } catch (FileNotFoundException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }

            sharingIntent.setType("image/jpeg");
            sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
            startActivity(Intent.createChooser(sharingIntent, "Share image using"));
         }
      });
   }
}

以下是修改后的 xml res/layout/activity_main.xml 内容。

Following is the modified content of the xml res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"
      android:text="Facebook share " />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="35dp"
      android:textColor="#ff16ff01" />

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true"
      android:src="@drawable/abc"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Share"
      android:id="@+id/button"
      android:layout_marginTop="61dp"
      android:layout_below="@+id/imageView"
      android:layout_centerHorizontal="true" />

</RelativeLayout>

下面是 AndroidManifest.xml 文件的内容。

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>
   </application>
</manifest>

我们尝试运行您的应用程序。我假设您已经将实际 Android 移动设备与您的计算机连接好。要从 Android Studio 运行该应用程序,请打开您项目的一个活动文件,并单击工具栏中的“运行”图标。在启动您的应用程序之前,Android Studio 将显示以下窗口,让您选择要运行 Android 应用程序的位置。

Let’s try to run your Application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.

choose device

选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 −

Select your mobile device as an option and then check your mobile device which will display your default screen −

facebook

现在,轻触该按钮,你便会看到一个分享提供程序列表。

Now just tap on the button and you will see a list of share providers.

facebook1

现在只需从该列表中选择 Facebook,然后输入任何消息。如下图所示:

Now just select facebook from that list and then write any message. It is shown in the image below −

facebook2