Android integration of Rongyun IM (1) Prerequisite preparation and acquisition of Token

1. First of all, go to the official website of Rongyun www.rongcloud.cn , and register an account. You will understand this needless to say.

2. Enter the console and create a new project. This is not detailed. You can take a look at their api. The focus is on the code part.



 

 

Enter the newly created application "Simple Chat"

 


 
 In this way, you can view the APPKey and APP Secret, and you don't need to look at the others for the time being. Our goal this time is to realize the construction of the project and obtain the token, and there is no chat interface.

 



 

 

Download Rongyun's IMKit including chat UI and chat core controls

Import into eclipse and make the project depend on him




 
 

Next, mainly configure AndroidManifest.xml

 

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.chat.simplechat"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!-- Get model information permission-->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!-- Recording -->

    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:name=".SCApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light" >
        <activity
            android:name="com.chat.simplechat.activity.MainActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".activity.SplashActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.Start" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!-- Required: SDK core functions -->
        <!-- Third-party related, service requesting token from third-party push service-->
        <service
            android:name="io.rong.push.core.PushRegistrationService"
            android:exported="false" >
        </service>

        <!-- Services related to processing push messages-->
        <service
            android:name="io.rong.push.core.MessageHandleService"
            android:exported="true" >
        </service>

        <!-- push service -->
        <service
            android:name="io.rong.push.PushService"
            android:exported="false"
            android:process="io.rong.push" > <!-- push process, can be renamed -->
        </service>

        <!-- push related event receiver -->
        <receiver
            android:name="io.rong.push.PushReceiver"
            android:process="io.rong.push" > <!-- The process can be renamed here, and the name needs to be the same as the process where PushService is located -->
            <!-- Heartbeat event-->
            <intent-filter>
                <action android:name="io.rong.push.intent.action.HEART_BEAT" />
            </intent-filter>
            <!-- Network change event-->
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
            <!-- Some user events -->
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>

        <!-- Required: SDK core functions -->
        <!-- imlib config begin -->
        <meta-data
            android:name="RONG_CLOUD_APP_KEY"
            android:value="pkfcgjstfp8j8" />

        <service
            android:name="io.rong.imlib.ipc.RongService"
            android:exported="true"
            android:process=":ipc" />
        <service android:name="io.rong.imlib.ReConnectService" />

        <receiver android:name="io.rong.imlib.ConnectChangeReceiver" />
        <receiver
            android:name="io.rong.imlib.HeartbeatReceiver"
            android:process=":ipc" />
        <!-- imlib config end -->

    </application>

</manifest>

 Then inherit an Application by yourself and implement initialization in it

package com.chat.simplechat;

import org.xutils.x;

import io.rong.imkit.RongIM;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;

public class SCApplication extends Application {

	private static Context content;

	@Override
	public void onCreate() {
		super.onCreate();
		x.Ext.init(this);
		content = getApplicationContext();
		/**
		 * OnCreate will be reentrant by multiple processes, this protection code ensures that only the process you need to use RongIM and the Push process execute init.
		 * io.rong.push is the name of the Rongyun push process, which cannot be modified.
		 */
		if (getApplicationInfo().packageName
				.equals(getCurProcessName(getApplicationContext()))
				|| "io.rong.push"
						.equals(getCurProcessName(getApplicationContext()))) {

			/**
			 * IMKit SDK calls the first step of initialization
			 */
			RongIM.init(this);
		}
	}

	public static Context getObjectContext() {
		return content;
	}

	/**
	 * Get the name of the current process
	 *
	 * @param context
	 * @return process number
	 */
	public static String getCurProcessName(Context context) {

		int pid = android.os.Process.myPid();

		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);

		for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
				.getRunningAppProcesses()) {

			if (appProcess.pid == pid) {
				return appProcess.processName;
			}
		}
		return null;
	}
}

 Then remember to configure the name of the inherited Application to AndroidManifest.xml.

 

 

So far, we have built the project, so the most important thing is to obtain Token and connect to the server, only the core code will be posted, and the source code will be placed at the end, you can download and view the detailed code.

	public static RequestParams addHeader(RequestParams params) {
		Random r = new Random();
		String Nonce = (r.nextInt(10000) + 10000) + "";
		String Timestamp = (System.currentTimeMillis() / 1000) + "";
		params.addHeader("App-Key", RY_APP_KEY);
		params.addHeader("Nonce", Nonce);
		params.addHeader("Timestamp", Timestamp);
		params.addHeader("Signature",
				MD5.encryptToSHA(RY_APP_SECRET + Nonce + Timestamp));

		return params;
	}

 

public static void getToken(final String id, final String username) {
		RequestParams params = new RequestParams(
				"https://api.cn.ronghub.com/user/getToken.json");
		addHeader(params);
		params.addBodyParameter("userId", id);
		params.addBodyParameter("name", username);
		x.http().post(params, new CommonCallback<String>() {

			@Override
			public void onCancelled (CancelledException arg0) {
			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				EBmessage eb = new EBmessage();
				eb.setStatus(false);
				eb.setMessage(arg0.toString());
				eb.setFrom("getToken");
				EventBus.getDefault().post(eb);
			}

			@Override
			public void onFinished() {
			}

			@Override
			public void onSuccess(String s) {
				TokenMod mod = new Gson().fromJson(s, TokenMod.class);
				Editor editor = getEditor();
				editor.putString("username", username);
				editor.putString("userpass", mod.getUserId());
				editor.putString("token", mod.getToken());
				editor.commit();

				EBmessage eb = new EBmessage();
				eb.setStatus(true);
				eb.setMessage(mod.getToken());
				eb.setFrom("getToken");
				EventBus.getDefault().post(eb);
			}
		});
	}

	/**
	 * Establish a connection with Rongyun server
	 *
	 * @param token
	 */
	public static void connect(String token, Context context) {

		if (context.getApplicationInfo().packageName.equals(SCApplication
				.getCurProcessName(context.getApplicationContext()))) {

			/**
			 * IMKit SDK calls the second step to establish a connection with the server
			 */
			RongIM.connect(token, new RongIMClient.ConnectCallback() {

				/**
				 * Token error, mainly because the Token has expired in the online environment, you need to re-request a new one from App Server
				 * Token
				 */
				@Override
				public void onTokenIncorrect() {
					Log.d("LoginActivity", "--onTokenIncorrect");
				}

				/**
				 * Successfully connected to Rongyun
				 *
				 * @param userid
				 * current token
				 */
				@Override
				public void onSuccess(String userid) {
					EBmessage eb = new EBmessage();
					eb.setStatus(true);
					eb.setMessage("success");
					eb.setFrom("connect");
					EventBus.getDefault().post(eb);
					Log.d("LoginActivity", "--onSuccess" + userid);
				}

				/**
				 * Failed to connect to Rongyun
				 *
				 * @param errorCode
				 * For error codes, you can go to the official website to view the comments corresponding to the error codes
				 */
				@Override
				public void onError(RongIMClient.ErrorCode errorCode) {
					Log.d("LoginActivity", "--onError" + errorCode);
				}
			});
		}
	}

 

demo download addresshttp ://download.csdn.net/detail/wangyang00700/9623568

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326563980&siteId=291194637