内容:介绍个推接入及使用
步骤如下:
1、项目gradle中添加maven库地址
//Maven URL地址
maven {
url "http://mvn.gt.igexin.com/nexus/content/repositories/releases/"
}
2、app.gradle配置依赖
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
compile 'com.getui:sdk:2.12.4.0'
compile 'org.greenrobot:eventbus:3.0.0'
}
3、gradle.properties文件中配置useDeprecatedNdk参数
android.useDeprecatedNdk=true
4、在app/build.gradle文件中的android.defaultConfig下指定所需的 CPU 架构,配置so
android {
...
defaultConfig {
...
ndk {
abiFilters "armeabi", "armeabi-v7a", "x86_64"
}
}
}
5、在app/build.gradle文件中的android.defaultConfig下添加manifestPlaceholders,配置个推相关的应用参数
manifestPlaceholders = [
GETUI_APP_ID : "GETUI_APP_ID ",
GETUI_APP_KEY : "GETUI_APP_KEY ",
GETUI_APP_SECRET : "GETUI_APP_SECRET "
]
6、实现推送
1)继承自Android.app.Service的类
package com.example.leixiansheng.getui;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.igexin.sdk.GTServiceManager;
/**
* Created by Leixiansheng on 2018/8/16.
*/
public class PushService extends Service {
@Override
public void onCreate() {
super.onCreate();
GTServiceManager.getInstance().onCreate(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return GTServiceManager.getInstance().onStartCommand(this, intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return GTServiceManager.getInstance().onBind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
GTServiceManager.getInstance().onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
GTServiceManager.getInstance().onLowMemory();
}
}
2)在AndroidManifest.xml中添加上述自定义Service
<service
android:name=".PushService"
android:exported="true"
android:label="PushService"
android:process=":pushservice">
</service>
权限:
<!-- iBeancon功能所需权限 -->;
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<!-- 个推3.0电子围栏功能所需权限 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
3)res/raw
中添加keep.xml
文件
<?xml version="1.0" encoding="utf-8"?>
<resources
xmlns:tools="http://schemas.android.com/tools"
tools:keep="@layout/getui_notification"/>
<!-- 若您需要使用其他自定义推送图标,也需要在此处添加 -->
或者自己指定图标,但是命名必须为push.png(通知图标)、push_small.png(作为通知图标展示在通知栏顶部)(同时存在于drawable)
建议的push.png
图片尺寸如下:
ldpi: 48*48
mdpi: 64*64
hdpi: 96*96
xhdpi: 128*128
xxhdpi: 192*192
建议的push_small.png图片尺寸如下:
ldpi: 18*18
mdpi: 24*24
hdpi: 36*36
xhdpi: 48*48
xxhdpi: 72*72
xxxhdp: 96*96
<?xml version="1.0" encoding="utf-8"?>
<resources
xmlns:tools="http://schemas.android.com/tools"
tools:keep="@layout/getui_notification,
@drawable/push,
@drawable/push_small"/>
<!-- 若您需要使用其他自定义推送图标,也需要在此处添加 -->
7、初始化
1)继承自com.igexin.sdk.GTIntentService的类
package com.example.leixiansheng.getui;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.FeedbackCmdMessage;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.igexin.sdk.message.SetTagCmdMessage;
import org.greenrobot.eventbus.EventBus;
/**
* 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
* onReceiveMessageData 处理透传消息<br>
* onReceiveClientId 接收 cid <br>
* onReceiveOnlineState cid 离线上线通知 <br>
* onReceiveCommandResult 各种事件处理回执 <br>
*/
public class GetuiIntentService extends GTIntentService {
Vibrator vibrator;
public GetuiIntentService() {
}
@Override
public void onReceiveServicePid(Context context, int pid) {
Log.d(TAG, "onReceiveServicePid -> " + pid);
}
@Override
public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
Log.d(TAG, "onReceiveMessageData -> " + msg.toString());
String appId = msg.getAppid();
String taskId = msg.getTaskId();
String messageId = msg.getMessageId();
byte[] payload = msg.getPayload();
String pkg = msg.getPkgName();
String cid = msg.getClientId();
// 第三方回执调用接口,actionid范围为90000-90999,可根据业务场景执行
boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskId, messageId, 90001);
if (payload == null) {
Log.e(TAG, "receiver payload = null");
} else {
String data = new String(payload);
// sendMessage(data, 0);
Log.d(TAG, "payload -> " + data);
final char[] strChar = data.substring(0, 1).toCharArray();
final char firstChar = strChar[0];
if(firstChar == '{'){
setNewNotification(data);
}else{
/* if(MyApplication.messageBoxListActivity == null) {
setNotification(data);
}else {
vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE); //震动
long [] pattern = {100,100,100,100}; // 停止 开启 停止 开启
vibrator.vibrate(pattern,-1);
}*/
}
}
}
@Override
public void onReceiveClientId(Context context, String clientid) {
//todo 此处获取到推送客户的ID,将ID传到服务器,让服务器发起推送
Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
}
@Override
public void onReceiveOnlineState(Context context, boolean online) {
}
@Override
public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
int action = cmdMessage.getAction();
if (action == PushConsts.SET_TAG_RESULT) {
setTagResult((SetTagCmdMessage) cmdMessage);
} else if ((action == PushConsts.THIRDPART_FEEDBACK)) {
feedbackResult((FeedbackCmdMessage) cmdMessage);
}
}
@Override
public void onNotificationMessageArrived(Context context, GTNotificationMessage msg) {
}
@Override
public void onNotificationMessageClicked(Context context, GTNotificationMessage msg) {
}
private void setTagResult(SetTagCmdMessage setTagCmdMsg) {
String sn = setTagCmdMsg.getSn();
String code = setTagCmdMsg.getCode();
String text = "设置标签失败, 未知异常";
switch (Integer.valueOf(code)) {
case PushConsts.SETTAG_SUCCESS:
text = "设置标签成功";
break;
case PushConsts.SETTAG_ERROR_COUNT:
text = "设置标签失败, tag数量过大, 最大不能超过200个";
break;
case PushConsts.SETTAG_ERROR_FREQUENCY:
text = "设置标签失败, 频率过快, 两次间隔应大于1s且一天只能成功调用一次";
break;
case PushConsts.SETTAG_ERROR_REPEAT:
text = "设置标签失败, 标签重复";
break;
case PushConsts.SETTAG_ERROR_UNBIND:
text = "设置标签失败, 服务未初始化成功";
break;
case PushConsts.SETTAG_ERROR_EXCEPTION:
text = "设置标签失败, 未知异常";
break;
case PushConsts.SETTAG_ERROR_NULL:
text = "设置标签失败, tag 为空";
break;
case PushConsts.SETTAG_NOTONLINE:
text = "还未登陆成功";
break;
case PushConsts.SETTAG_IN_BLACKLIST:
text = "该应用已经在黑名单中,请联系售后支持!";
break;
case PushConsts.SETTAG_NUM_EXCEED:
text = "已存 tag 超过限制";
break;
default:
break;
}
Log.d(TAG, "settag result sn = " + sn + ", code = " + code + ", text = " + text);
}
private void feedbackResult(FeedbackCmdMessage feedbackCmdMsg) {
String appid = feedbackCmdMsg.getAppid();
String taskid = feedbackCmdMsg.getTaskId();
String actionid = feedbackCmdMsg.getActionId();
String result = feedbackCmdMsg.getResult();
long timestamp = feedbackCmdMsg.getTimeStamp();
String cid = feedbackCmdMsg.getClientId();
Log.d(TAG, "onReceiveCommandResult -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nactionid = " + actionid + "\nresult = " + result
+ "\ncid = " + cid + "\ntimestamp = " + timestamp);
}
//使用系统默认样式的通知
protected void setNewNotification(String text) {
/* Gson gson = new Gson();
NotificationBean notificationBean = gson.fromJson(text, NotificationBean.class);
Uri uri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.ring);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notificationBean.title)
.setSound(uri)
.setContentText("点击查看详情");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
resultIntent.putExtra(Contants.NOTIFICATION_TYPE, notificationBean.type);
resultIntent.putExtra(Contants.NOTIFICATION_ID, notificationBean.id);
resultIntent.putExtra(Contants.NOTIFICATION_SUB_TYPE, notificationBean.subtype);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(1, notification);*/
}
//使用系统默认样式的通知
protected void setNotification(String text) {
/* Bitmap bitmap = BitmapFactory. decodeResource (getResources(), R.mipmap.ic_launcher);
Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
Uri uri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.ring);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(text)
.setSound(uri)
.setContentText("点击查看详情");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
resultIntent.putExtra(Contants.NOTIFICATION_TYPE, 200000);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(1, notification);*/
}
}
2)在AndroidManifest.xml
中配置上述 IntentService 类
<service android:name=".GetuiIntentService"/>
8、测试是否配置成功
连接手机或启动Android模拟器,编译运行你的工程,查看logcat信息。在搜索框中输入clientid
,如果能显示clientid is xxx
日志,则说明个推SDK已经成功运行起来了
9、更多设置参考开发者文档
http://docs.getui.com/getui/mobile/android/api/
个推官方demo
1、DemoApplication
package com.getui.demo;
import android.app.Application;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class DemoApplication extends Application {
private static final String TAG = "GetuiSdkDemo";
private static DemoHandler handler;
public static GetuiSdkDemoActivity demoActivity;
/**
* 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
*/
public static StringBuilder payloadData = new StringBuilder();
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "DemoApplication onCreate");
if (handler == null) {
handler = new DemoHandler();
}
}
public static void sendMessage(Message msg) {
handler.sendMessage(msg);
}
public static class DemoHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
if (demoActivity != null) {
payloadData.append((String) msg.obj);
payloadData.append("\n");
if (GetuiSdkDemoActivity.tLogView != null) {
GetuiSdkDemoActivity.tLogView.append(msg.obj + "\n");
}
}
break;
case 1:
if (demoActivity != null) {
if (GetuiSdkDemoActivity.tLogView != null) {
GetuiSdkDemoActivity.tView.setText((String) msg.obj);
}
}
break;
}
}
}
}
2、AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.getui.demo"
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 支持iBeancon 需要蓝牙权限 -->
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<!-- 支持个推3.0 电子围栏功能 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:name=".DemoApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true">
<!-- 第三方应用配置 -->
<activity
android:name=".GetuiSdkDemoActivity"
android:label="@string/app_name"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- 用户自定义服务继承自GTIntentService,作为SDK与APP桥梁服务,用来接收各种消息和命令回复-->
<service android:name=".DemoIntentService"/>
<!-- 配置SDK核心服务 -->
<service
android:name=".DemoPushService"
android:exported="true"
android:label="PushService"
android:process=":pushservice">
</service>
</application>
</manifest>
3、GetuiSdkDemoActivity
package com.getui.demo;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.Tag;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* PushManager 为对外接口, 所有调用均是通过 PushManager.getInstance() 日志过滤器输入 PushManager, 在接口调用失败会有对应 Error 级别
* log 提示.
*/
public class GetuiSdkDemoActivity extends Activity implements OnClickListener {
private static final String TAG = "GetuiSdkDemo";
private static final String MASTERSECRET = "MASTERSECRET";
private Button clearBtn;
private Button serviceBtn;
private Button bindAliasBtn;
private Button unbindAliasBtn;
private Button btnAddTag;
private Button btnVersion;
private Button btnSilentime;
private Button btnGetCid;
private TextView appKeyView;
private TextView appSecretView;
private TextView masterSecretView;
private TextView appIdView;
public static TextView tView; //显示clientId
public static TextView tLogView; //显示透传内容
// 透传测试.
private Button transmissionBtn;
// 通知测试.
private Button notifactionBtn;
// SDK服务是否启动.
private boolean isServiceRunning = true;
private Context context;
private String appkey = "";
private String appsecret = "";
private String appid = "";
private static final int REQUEST_PERMISSION = 0;
// DemoPushService.class 自定义服务名称, 核心服务
private Class userPushService = DemoPushService.class;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
isServiceRunning = true;
DemoApplication.demoActivity = this;
initView();
parseManifests();
appKeyView.setText(String.format("%s", getResources().getString(R.string.appkey) + appkey));
appSecretView.setText(String.format("%s", getResources().getString(R.string.appsecret) + appsecret));
masterSecretView.setText(String.format("%s", getResources().getString(R.string.mastersecret) + MASTERSECRET));
appIdView.setText(String.format("%s", getResources().getString(R.string.appid) + appid));
Log.d(TAG, "initializing sdk...");
PackageManager pkgManager = getPackageManager();
// 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
boolean sdCardWritePermission =
pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
// read phone state用于获取 imei 设备信息
boolean phoneSatePermission =
pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
requestPermission();
} else {
PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
}
// 注册 intentService 后 PushDemoReceiver 无效, sdk 会使用 DemoIntentService 传递数据,
// AndroidManifest 对应保留一个即可(如果注册 DemoIntentService, 可以去掉 PushDemoReceiver, 如果注册了
// IntentService, 必须在 AndroidManifest 中声明)
PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
// 应用未启动, 个推 service已经被唤醒,显示该时间段内离线消息
if (DemoApplication.payloadData != null) {
tLogView.append(DemoApplication.payloadData);
}
// cpu 架构
Log.d(TAG, "cpu arch = " + (Build.VERSION.SDK_INT < 21 ? Build.CPU_ABI : Build.SUPPORTED_ABIS[0]));
// 检查 so 是否存在
File file = new File(this.getApplicationInfo().nativeLibraryDir + File.separator + "libgetuiext2.so");
Log.e(TAG, "libgetuiext2.so exist = " + file.exists());
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
REQUEST_PERMISSION);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_PERMISSION) {
if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
} else {
Log.e(TAG, "We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
+ "functions will not work");
PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
public void onDestroy() {
Log.d("GetuiSdkDemo", "onDestroy()");
DemoApplication.payloadData.delete(0, DemoApplication.payloadData.length());
super.onDestroy();
}
@Override
public void onStop() {
Log.d("GetuiSdkDemo", "onStop()");
super.onStop();
}
public void onClick(View v) {
if (v == clearBtn) {
tLogView.setText("");
DemoApplication.payloadData.delete(0, DemoApplication.payloadData.length());
} else if (v == serviceBtn) {
if (isServiceRunning) {
Log.d(TAG, "stopping sdk...");
PushManager.getInstance().stopService(this.getApplicationContext());
tView.setText(getResources().getString(R.string.no_clientid));
serviceBtn.setText(getResources().getString(R.string.stop));
isServiceRunning = false;
} else {
Log.d(TAG, "reinitializing sdk...");
PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
serviceBtn.setText(getResources().getString(R.string.start));
isServiceRunning = true;
}
} else if (v == bindAliasBtn) {
bindAlias();
// PushManager.getInstance().turnOnPush(this.getApplicationContext());
} else if (v == unbindAliasBtn) {
unBindAlias();
// PushManager.getInstance().turnOffPush(this.getApplicationContext());
} else if (v == transmissionBtn) {
showTransmission();
} else if (v == notifactionBtn) {
showNotification();
} else if (v == btnAddTag) {
addTag();
} else if (v == btnGetCid) {
getCid();
} else if (v == btnSilentime) {
setSilentime();
} else if (v == btnVersion) {
getVersion();
}
}
/**
* 测试addTag接口.
*/
private void addTag() {
final View view = new EditText(this);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setTitle(R.string.add_tag).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
TextView tagText = (TextView) view;
Log.d(TAG, "setTag input tags = " + tagText.getText().toString());
String[] tags = tagText.getText().toString().split(",");
Tag[] tagParam = new Tag[tags.length];
for (int i = 0; i < tags.length; i++) {
Tag t = new Tag();
t.setName(tags[i]);
tagParam[i] = t;
}
int i = PushManager.getInstance().setTag(context, tagParam, "" + System.currentTimeMillis());
int text = R.string.add_tag_unknown_exception;
// 这里的返回结果仅仅是接口调用是否成功, 不是真正成功, 真正结果见{
// com.getui.demo.DemoIntentService.setTagResult 方法}
switch (i) {
case PushConsts.SETTAG_SUCCESS:
text = R.string.add_tag_success;
break;
case PushConsts.SETTAG_ERROR_COUNT:
text = R.string.add_tag_error_count;
break;
case PushConsts.SETTAG_ERROR_FREQUENCY:
text = R.string.add_tag_error_frequency;
break;
case PushConsts.SETTAG_ERROR_NULL:
text = R.string.add_tag_error_null;
break;
default:
break;
}
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}).setView(view);
alertBuilder.create().show();
}
private void getVersion() {
String version = PushManager.getInstance().getVersion(this);
Toast.makeText(this, getResources().getString(R.string.show_version) + version, Toast.LENGTH_SHORT).show();
}
private void getCid() {
String cid = PushManager.getInstance().getClientid(this);
Toast.makeText(this, getResources().getString(R.string.show_cid) + cid, Toast.LENGTH_LONG).show();
Log.d(TAG, getResources().getString(R.string.show_cid) + cid);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
private void initView() {
clearBtn = (Button) findViewById(R.id.btn_clear);
clearBtn.setOnClickListener(this);
serviceBtn = (Button) findViewById(R.id.btn_service);
serviceBtn.setOnClickListener(this);
bindAliasBtn = (Button) findViewById(R.id.btn_bind_alias);
bindAliasBtn.setOnClickListener(this);
unbindAliasBtn = (Button) findViewById(R.id.btn_unbind_alias);
unbindAliasBtn.setOnClickListener(this);
btnAddTag = (Button) findViewById(R.id.btnAddTag);
btnAddTag.setOnClickListener(this);
btnVersion = (Button) findViewById(R.id.btnVersion);
btnVersion.setOnClickListener(this);
btnSilentime = (Button) findViewById(R.id.btnSilentime);
btnSilentime.setOnClickListener(this);
btnGetCid = (Button) findViewById(R.id.btnGetCid);
btnGetCid.setOnClickListener(this);
tView = (TextView) findViewById(R.id.tvclientid);
appKeyView = (TextView) findViewById(R.id.tvappkey);
appSecretView = (TextView) findViewById(R.id.tvappsecret);
masterSecretView = (TextView) findViewById(R.id.tvmastersecret);
appIdView = (TextView) findViewById(R.id.tvappid);
tLogView = (EditText) findViewById(R.id.tvlog);
tLogView.setInputType(InputType.TYPE_NULL);
tLogView.setSingleLine(false);
tLogView.setHorizontallyScrolling(false);
transmissionBtn = (Button) findViewById(R.id.btn_pmsg);
transmissionBtn.setOnClickListener(this);
notifactionBtn = (Button) findViewById(R.id.btn_psmsg);
notifactionBtn.setOnClickListener(this);
}
private void parseManifests() {
String packageName = getApplicationContext().getPackageName();
try {
ApplicationInfo appInfo = getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
if (appInfo.metaData != null) {
appid = appInfo.metaData.getString("PUSH_APPID");
appsecret = appInfo.metaData.getString("PUSH_APPSECRET");
appkey = appInfo.metaData.getString("PUSH_APPKEY");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 判断网络是否连接.
*/
private boolean isNetworkConnected() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo ni : info) {
if (ni.getState() == NetworkInfo.State.CONNECTED) {
Log.d(TAG, "type = " + (ni.getType() == 0 ? "mobile" : ((ni.getType() == 1) ? "wifi" : "none")));
return true;
}
}
}
}
return false;
}
private void setSilentime() {
final View view = LayoutInflater.from(this).inflate(R.layout.silent_setting, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setTitle(R.string.set_silenttime).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
TextView beginText = (TextView) view.findViewById(R.id.beginText);
TextView durationText = (TextView) view.findViewById(R.id.durationText);
try {
int beginHour = Integer.valueOf(String.valueOf(beginText.getText()));
int durationHour = Integer.valueOf(String.valueOf(durationText.getText()));
boolean result = PushManager.getInstance().setSilentTime(context, beginHour, durationHour);
if (result) {
Toast.makeText(context, "begin = " + beginHour + ", duration = " + durationHour, Toast.LENGTH_SHORT).show();
Log.d(TAG, "setSilentime, begin = " + beginHour + ", duration = " + durationHour);
} else {
Toast.makeText(context, "setSilentime failed, value exceeding", Toast.LENGTH_SHORT).show();
Log.d(TAG, "setSilentime failed, value exceeding");
}
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
}
}).setView(view);
alertBuilder.create().show();
}
private void unBindAlias() {
final EditText editText = new EditText(GetuiSdkDemoActivity.this);
new AlertDialog.Builder(GetuiSdkDemoActivity.this).setTitle(R.string.unbind_alias).setView(editText)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String alias = editText.getEditableText().toString();
if (alias.length() > 0) {
PushManager.getInstance().unBindAlias(GetuiSdkDemoActivity.this, alias, false);
Log.d(TAG, "unbind alias = " + editText.getEditableText().toString());
}
}
}).setNegativeButton(android.R.string.cancel, null).show();
}
private void bindAlias() {
final EditText editText = new EditText(GetuiSdkDemoActivity.this);
new AlertDialog.Builder(GetuiSdkDemoActivity.this).setTitle(R.string.bind_alias).setView(editText)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (editText.getEditableText() != null) {
String alias = editText.getEditableText().toString();
if (alias.length() > 0) {
PushManager.getInstance().bindAlias(GetuiSdkDemoActivity.this, alias);
Log.d(TAG, "bind alias = " + editText.getEditableText().toString());
}
}
}
}).setNegativeButton(android.R.string.cancel, null).show();
}
private void showNotification() {
if (isNetworkConnected()) {
// !!!!!!注意:以下为个推服务端API1.0接口,仅供测试。不推荐在现网系统使用1.0版服务端接口,请参考最新的个推服务端API接口文档,使用最新的2.0版接口
Map<String, Object> param = new HashMap<String, Object>();
param.put("action", "pushSpecifyMessage"); // pushSpecifyMessage为接口名,注意大小写
/*---以下代码用于设定接口相应参数---*/
param.put("appkey", appkey);
param.put("type", 2); // 推送类型: 2为消息
param.put("pushTitle", getResources().getString(R.string.push_notification_title)); // pushTitle请填写您的应用名称
// 推送消息类型,有TransmissionMsg、LinkMsg、NotifyMsg三种,此处以LinkMsg举例
param.put("pushType", "LinkMsg");
param.put("offline", true); // 是否进入离线消息
param.put("offlineTime", 72); // 消息离线保留时间
param.put("priority", 1); // 推送任务优先级
List<String> cidList = new ArrayList<String>();
cidList.add(tView.getText().toString()); // 您获取的ClientID
param.put("tokenMD5List", cidList);
param.put("sign", GetuiSdkHttpPost.makeSign(MASTERSECRET, param));// 生成Sign值,用于鉴权,需要MasterSecret,请务必填写
// LinkMsg消息实体
Map<String, Object> linkMsg = new HashMap<String, Object>();
linkMsg.put("linkMsgIcon", "push.png"); // 消息在通知栏的图标
linkMsg.put("linkMsgTitle", getResources().getString(R.string.push_notification_msg_title)); // 推送消息的标题
linkMsg.put("linkMsgContent", getResources().getString(R.string.push_notification_msg_content)); // 推送消息的内容
linkMsg.put("linkMsgUrl", "http://www.igetui.com/"); // 点击通知跳转的目标网页
param.put("msg", linkMsg);
GetuiSdkHttpPost.httpPost(param);
} else {
Toast.makeText(this, R.string.network_invalid, Toast.LENGTH_SHORT).show();
}
}
private void showTransmission() {
if (isNetworkConnected()) {
// !!!!!!注意:以下为个推服务端API1.0接口,仅供测试。不推荐在现网系统使用1.0版服务端接口,请参考最新的个推服务端API接口文档,使用最新的2.0版接口
Map<String, Object> param = new HashMap<String, Object>();
param.put("action", "pushmessage"); // pushmessage为接口名,注意全部小写
/*---以下代码用于设定接口相应参数---*/
param.put("appkey", appkey);
param.put("appid", appid);
// 注:透传内容后面需用来验证接口调用是否成功,假定填写为hello girl~
param.put("data", getResources().getString(R.string.push_transmission_data));
// 当前请求时间,可选
param.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date(System.currentTimeMillis())));
param.put("clientid", tView.getText().toString()); // 您获取的ClientID
param.put("expire", 3600); // 消息超时时间,单位为秒,可选
param.put("sign", GetuiSdkHttpPost.makeSign(MASTERSECRET, param));// 生成Sign值,用于鉴权
GetuiSdkHttpPost.httpPost(param);
} else {
Toast.makeText(this, R.string.network_invalid, Toast.LENGTH_SHORT).show();
}
}
}
4、DemoPushService
package com.getui.demo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.igexin.sdk.GTServiceManager;
/**
* 核心服务, 继承 android.app.Service, 必须实现以下几个接口, 并在 AndroidManifest 声明该服务并配置成
* android:process=":pushservice", 具体参考 {@link com.getui.demo.GetuiSdkDemoActivity}
* PushManager.getInstance().initialize(this.getApplicationContext(), userPushService), 其中
* userPushService 为 用户自定义服务 即 DemoPushService.
*/
public class DemoPushService extends Service {
public static final String TAG = DemoPushService.class.getName();
@Override
public void onCreate() {
// 该行日志在 release 版本去掉
Log.d(TAG, TAG + " call -> onCreate -------");
super.onCreate();
GTServiceManager.getInstance().onCreate(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 该行日志在 release 版本去掉
Log.d(TAG, TAG + " call -> onStartCommand -------");
super.onStartCommand(intent, flags, startId);
return GTServiceManager.getInstance().onStartCommand(this, intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// 该行日志在 release 版本去掉
Log.d(TAG, "onBind -------");
return GTServiceManager.getInstance().onBind(intent);
}
@Override
public void onDestroy() {
// 该行日志在 release 版本去掉
Log.d(TAG, "onDestroy -------");
super.onDestroy();
GTServiceManager.getInstance().onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
GTServiceManager.getInstance().onLowMemory();
}
}
5、DemoIntentService
package com.getui.demo;
import android.content.Context;
import android.os.Message;
import android.util.Log;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.BindAliasCmdMessage;
import com.igexin.sdk.message.FeedbackCmdMessage;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.igexin.sdk.message.SetTagCmdMessage;
import com.igexin.sdk.message.UnBindAliasCmdMessage;
/**
* 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
* onReceiveMessageData 处理透传消息<br>
* onReceiveClientId 接收 cid <br>
* onReceiveOnlineState cid 离线上线通知 <br>
* onReceiveCommandResult 各种事件处理回执 <br>
*/
public class DemoIntentService extends GTIntentService {
private static final String TAG = "GetuiSdkDemo";
/**
* 为了观察透传数据变化.
*/
private static int cnt;
public DemoIntentService() {
}
@Override
public void onReceiveServicePid(Context context, int pid) {
Log.d(TAG, "onReceiveServicePid -> " + pid);
}
@Override
public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
String appid = msg.getAppid();
String taskid = msg.getTaskId();
String messageid = msg.getMessageId();
byte[] payload = msg.getPayload();
String pkg = msg.getPkgName();
String cid = msg.getClientId();
// 第三方回执调用接口,actionid范围为90000-90999,可根据业务场景执行
boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
Log.d(TAG, "call sendFeedbackMessage = " + (result ? "success" : "failed"));
Log.d(TAG, "onReceiveMessageData -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nmessageid = " + messageid + "\npkg = " + pkg
+ "\ncid = " + cid);
if (payload == null) {
Log.e(TAG, "receiver payload = null");
} else {
String data = new String(payload);
Log.d(TAG, "receiver payload = " + data);
// 测试消息为了观察数据变化
if (data.equals(getResources().getString(R.string.push_transmission_data))) {
data = data + "-" + cnt;
cnt++;
}
sendMessage(data, 0);
}
Log.d(TAG, "----------------------------------------------------------------------------------------------");
}
@Override
public void onReceiveClientId(Context context, String clientid) {
Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
sendMessage(clientid, 1);
}
@Override
public void onReceiveOnlineState(Context context, boolean online) {
Log.d(TAG, "onReceiveOnlineState -> " + (online ? "online" : "offline"));
}
@Override
public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
Log.d(TAG, "onReceiveCommandResult -> " + cmdMessage);
int action = cmdMessage.getAction();
if (action == PushConsts.SET_TAG_RESULT) {
setTagResult((SetTagCmdMessage) cmdMessage);
} else if(action == PushConsts.BIND_ALIAS_RESULT) {
bindAliasResult((BindAliasCmdMessage) cmdMessage);
} else if (action == PushConsts.UNBIND_ALIAS_RESULT) {
unbindAliasResult((UnBindAliasCmdMessage) cmdMessage);
} else if ((action == PushConsts.THIRDPART_FEEDBACK)) {
feedbackResult((FeedbackCmdMessage) cmdMessage);
}
}
@Override
public void onNotificationMessageArrived(Context context, GTNotificationMessage message) {
Log.d(TAG, "onNotificationMessageArrived -> " + "appid = " + message.getAppid() + "\ntaskid = " + message.getTaskId() + "\nmessageid = "
+ message.getMessageId() + "\npkg = " + message.getPkgName() + "\ncid = " + message.getClientId() + "\ntitle = "
+ message.getTitle() + "\ncontent = " + message.getContent());
}
@Override
public void onNotificationMessageClicked(Context context, GTNotificationMessage message) {
Log.d(TAG, "onNotificationMessageClicked -> " + "appid = " + message.getAppid() + "\ntaskid = " + message.getTaskId() + "\nmessageid = "
+ message.getMessageId() + "\npkg = " + message.getPkgName() + "\ncid = " + message.getClientId() + "\ntitle = "
+ message.getTitle() + "\ncontent = " + message.getContent());
}
private void setTagResult(SetTagCmdMessage setTagCmdMsg) {
String sn = setTagCmdMsg.getSn();
String code = setTagCmdMsg.getCode();
int text = R.string.add_tag_unknown_exception;
switch (Integer.valueOf(code)) {
case PushConsts.SETTAG_SUCCESS:
text = R.string.add_tag_success;
break;
case PushConsts.SETTAG_ERROR_COUNT:
text = R.string.add_tag_error_count;
break;
case PushConsts.SETTAG_ERROR_FREQUENCY:
text = R.string.add_tag_error_frequency;
break;
case PushConsts.SETTAG_ERROR_REPEAT:
text = R.string.add_tag_error_repeat;
break;
case PushConsts.SETTAG_ERROR_UNBIND:
text = R.string.add_tag_error_unbind;
break;
case PushConsts.SETTAG_ERROR_EXCEPTION:
text = R.string.add_tag_unknown_exception;
break;
case PushConsts.SETTAG_ERROR_NULL:
text = R.string.add_tag_error_null;
break;
case PushConsts.SETTAG_NOTONLINE:
text = R.string.add_tag_error_not_online;
break;
case PushConsts.SETTAG_IN_BLACKLIST:
text = R.string.add_tag_error_black_list;
break;
case PushConsts.SETTAG_NUM_EXCEED:
text = R.string.add_tag_error_exceed;
break;
default:
break;
}
Log.d(TAG, "settag result sn = " + sn + ", code = " + code + ", text = " + getResources().getString(text));
}
private void bindAliasResult(BindAliasCmdMessage bindAliasCmdMessage) {
String sn = bindAliasCmdMessage.getSn();
String code = bindAliasCmdMessage.getCode();
int text = R.string.bind_alias_unknown_exception;
switch (Integer.valueOf(code)) {
case PushConsts.BIND_ALIAS_SUCCESS:
text = R.string.bind_alias_success;
break;
case PushConsts.ALIAS_ERROR_FREQUENCY:
text = R.string.bind_alias_error_frequency;
break;
case PushConsts.ALIAS_OPERATE_PARAM_ERROR:
text = R.string.bind_alias_error_param_error;
break;
case PushConsts.ALIAS_REQUEST_FILTER:
text = R.string.bind_alias_error_request_filter;
break;
case PushConsts.ALIAS_OPERATE_ALIAS_FAILED:
text = R.string.bind_alias_unknown_exception;
break;
case PushConsts.ALIAS_CID_LOST:
text = R.string.bind_alias_error_cid_lost;
break;
case PushConsts.ALIAS_CONNECT_LOST:
text = R.string.bind_alias_error_connect_lost;
break;
case PushConsts.ALIAS_INVALID:
text = R.string.bind_alias_error_alias_invalid;
break;
case PushConsts.ALIAS_SN_INVALID:
text = R.string.bind_alias_error_sn_invalid;
break;
default:
break;
}
Log.d(TAG, "bindAlias result sn = " + sn + ", code = " + code + ", text = " + getResources().getString(text));
}
private void unbindAliasResult(UnBindAliasCmdMessage unBindAliasCmdMessage) {
String sn = unBindAliasCmdMessage.getSn();
String code = unBindAliasCmdMessage.getCode();
int text = R.string.unbind_alias_unknown_exception;
switch (Integer.valueOf(code)) {
case PushConsts.UNBIND_ALIAS_SUCCESS:
text = R.string.unbind_alias_success;
break;
case PushConsts.ALIAS_ERROR_FREQUENCY:
text = R.string.unbind_alias_error_frequency;
break;
case PushConsts.ALIAS_OPERATE_PARAM_ERROR:
text = R.string.unbind_alias_error_param_error;
break;
case PushConsts.ALIAS_REQUEST_FILTER:
text = R.string.unbind_alias_error_request_filter;
break;
case PushConsts.ALIAS_OPERATE_ALIAS_FAILED:
text = R.string.unbind_alias_unknown_exception;
break;
case PushConsts.ALIAS_CID_LOST:
text = R.string.unbind_alias_error_cid_lost;
break;
case PushConsts.ALIAS_CONNECT_LOST:
text = R.string.unbind_alias_error_connect_lost;
break;
case PushConsts.ALIAS_INVALID:
text = R.string.unbind_alias_error_alias_invalid;
break;
case PushConsts.ALIAS_SN_INVALID:
text = R.string.unbind_alias_error_sn_invalid;
break;
default:
break;
}
Log.d(TAG, "unbindAlias result sn = " + sn + ", code = " + code + ", text = " + getResources().getString(text));
}
private void feedbackResult(FeedbackCmdMessage feedbackCmdMsg) {
String appid = feedbackCmdMsg.getAppid();
String taskid = feedbackCmdMsg.getTaskId();
String actionid = feedbackCmdMsg.getActionId();
String result = feedbackCmdMsg.getResult();
long timestamp = feedbackCmdMsg.getTimeStamp();
String cid = feedbackCmdMsg.getClientId();
Log.d(TAG, "onReceiveCommandResult -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nactionid = " + actionid + "\nresult = " + result
+ "\ncid = " + cid + "\ntimestamp = " + timestamp);
}
private void sendMessage(String data, int what) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = data;
DemoApplication.sendMessage(msg);
}
}
6、GetuiSdkHttpPost
package com.getui.demo;
import android.os.AsyncTask;
import org.json.simple.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
public class GetuiSdkHttpPost {
private static final String SERVICEURL = "http://sdk.open.api.igexin.com/service";
private static final int CONNECTION_TIMEOUT_INT = 10000;
private static final int READ_TIMEOUT_INT = 10000;
public static void httpPost(final Map<String, Object> map) {
new AsyncTask<Void, Integer, Void>() {
@Override
protected Void doInBackground(Void... params) {
String param = JSONObject.toJSONString(map);
if (param != null) {
BufferedReader bufferReader = null;
HttpURLConnection urlConn = null;
try {
URL url = new URL(SERVICEURL);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setRequestMethod("POST");
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Charset", "utf-8");
urlConn.setConnectTimeout(CONNECTION_TIMEOUT_INT);
urlConn.setReadTimeout(READ_TIMEOUT_INT);
urlConn.connect();
DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
dop.write(param.getBytes("utf-8"));
dop.flush();
dop.close();
bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String result = "";
String readLine;
while ((readLine = bufferReader.readLine()) != null) {
result += readLine;
}
System.out.println("result: " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConn != null) {
urlConn.disconnect();
}
if (bufferReader != null) {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
System.out.println("param is null");
}
return null;
}
}.execute();
}
public static String makeSign(String masterSecret, Map<String, Object> params) throws IllegalArgumentException {
if (masterSecret == null || params == null) {
throw new IllegalArgumentException("masterSecret and params can not be null.");
}
if (!(params instanceof SortedMap)) {
params = new TreeMap<String, Object>(params);
}
StringBuilder input = new StringBuilder(masterSecret);
for (Entry<String, Object> entry : params.entrySet()) {
Object value = entry.getValue();
if (value instanceof String || value instanceof Integer || value instanceof Long) {
input.append(entry.getKey());
input.append(entry.getValue());
}
}
return getMD5Str(input.toString());
}
private static String getMD5Str(String sourceStr) {
byte[] source = sourceStr.getBytes();
char hexDigits[] = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
java.security.MessageDigest md = null;
try {
md = java.security.MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (md == null) {
return null;
}
md.update(source);
byte tmp[] = md.digest();
char str[] = new char[16 * 2];
int k = 0;
for (int i = 0; i < 16; i++) {
byte byte0 = tmp[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
}
Log信息如下:
08-22 14:37:56.321 25780-25780/? D/GetuiSdkDemo: DemoApplication onCreate
08-22 14:37:56.322 25780-25780/? D/com.getui.demo.DemoPushService: com.getui.demo.DemoPushService call -> onCreate -------
08-22 14:37:56.323 25780-25780/? D/com.getui.demo.DemoPushService: com.getui.demo.DemoPushService call -> onStartCommand -------
08-22 14:37:56.350 25780-25780/? D/com.getui.demo.DemoPushService: com.getui.demo.DemoPushService call -> onStartCommand -------
08-22 14:37:56.416 25760-25806/? D/GetuiSdkDemo: onReceiveServicePid -> 25780
08-22 14:37:58.529 25760-25818/? E/GetuiSdkDemo: onReceiveClientId -> clientid = 12e61ad2aa6c63b76fbc16e3b3aab108
08-22 14:37:58.546 25760-25819/? D/GetuiSdkDemo: onReceiveOnlineState -> online
08-22 14:38:01.592 25760-25760/? D/GetuiSdkDemo: type = wifi
08-22 14:38:01.796 25760-25834/? D/GetuiSdkDemo: call sendFeedbackMessage = success
08-22 14:38:01.797 25760-25834/? D/GetuiSdkDemo: onReceiveMessageData -> appid = H0Xa3xONOp9hxBeZRyTeG8
taskid = msg_0822_5b7d8b96b1f44fffbd5cf4b28f3c3eb0
messageid = 5b7d8b96b1f44fffbd5cf4b28f3c3eb0
pkg = com.getui.demo
cid = 12e61ad2aa6c63b76fbc16e3b3aab108
08-22 14:38:01.797 25780-25780/? D/com.getui.demo.DemoPushService: com.getui.demo.DemoPushService call -> onStartCommand -------
08-22 14:38:01.797 25760-25834/? D/GetuiSdkDemo: receiver payload = 收到一条透传测试消息
08-22 14:38:01.797 25760-25834/? D/GetuiSdkDemo: ----------------------------------------------------------------------------------------------
08-22 14:38:06.554 25760-25760/? D/GetuiSdkDemo: bind alias = 测试
08-22 14:38:06.554 25780-25780/? D/com.getui.demo.DemoPushService: com.getui.demo.DemoPushService call -> onStartCommand -------
08-22 14:38:06.659 25760-25848/? D/GetuiSdkDemo: onReceiveCommandResult -> com.igexin.sdk.message.BindAliasCmdMessage@390c52
08-22 14:38:06.660 25760-25848/? D/GetuiSdkDemo: bindAlias result sn = bindAlias_1534919886548, code = 0, text = 绑定别名成功
08-22 14:38:11.939 25760-25760/? D/GetuiSdkDemo: onStop()
08-22 14:41:41.274 25780-25780/? D/com.getui.demo.DemoPushService: onDestroy -------