### Server-Side Push Sender Example Source: https://github.com/taoweiji/mixpush/blob/master/README.md Example of initializing and using the MixPushSender to send notification messages. Configure sender details for various platforms and build the message with optional configurations. ```java class MixPushServerExample { public static void main(String[] args) { MixPushSender sender = new MixPushSender.Builder() .packageName("") .mi("",false) .meizu("", "") .huawei("", "") .oppo("", "") .vivo("", "", "") .miAPNs("") .test(true) .build(); MixPushMessageConfig activitiesMessageConfig = new MixPushMessageConfig.Builder() // OPPO 必须在“通道配置 → 新建通道”模块中登记通道,再在发送消息时选择 .oppoPushChannelId("activities") .build(); MixPushMessage message = new MixPushMessage.Builder() .title("这里是标题") .description("这里是副标题") .payload("{\"url\":\"http://github.com/taoweiji\"}") .config(activitiesMessageConfig) .build(); MixPushTarget target = MixPushTarget.single("mi","xxxx"); sender.sendNotificationMessage(message,target); } } ``` -------------------------------- ### MixPushClient.getInstance() - Get Push Client Singleton Source: https://context7.com/taoweiji/mixpush/llms.txt Obtain the singleton instance of the MixPush client. This is the core entry point for initializing the push service, setting listeners, and performing other client-side operations. ```APIDOC ## MixPushClient.getInstance() ### Description Get the singleton instance of the MixPush client. This instance is used to initialize the push service, set listeners, and obtain the registration ID. ### Method `MixPushClient.getInstance()` ### Usage Example (in Application class) ```java public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // 1. Set logger listener (optional) MixPushClient.getInstance().setLogger(new MixPushLogger() { @Override public void log(String tag, String content, Throwable throwable) { Log.e(tag, content); if (throwable != null) { throwable.printStackTrace(); } } @Override public void log(String tag, String content) { Log.e(tag, content); } }); // 2. Set push message receiver MixPushClient.getInstance().setPushReceiver(new MyMixPushReceiver()); // 3. Register push service (automatically identifies manufacturer and registers) MixPushClient.getInstance().register(this); } } ``` ``` -------------------------------- ### Get Registration ID Source: https://github.com/taoweiji/mixpush/blob/master/README.md Retrieve the registration ID for push notifications. It's recommended to call this in your homepage's onCreate method and report the ID to your server. ```java MixPushClient.getInstance().getRegisterId(this, new GetRegisterIdCallback() { public void callback(MixPushPlatform platform) { if (platform != null) { Log.e("GetRegisterIdCallback", platform.toString()); // TODO 上报regId给服务端 } } }); ``` -------------------------------- ### Get Push Registration ID (regId) Asynchronously Source: https://context7.com/taoweiji/mixpush/llms.txt Asynchronously retrieve the push registration ID (regId) for notification or transparent messages. This method has a 60-second timeout and should ideally be called in an Activity's onCreate method. Remember to upload the obtained regId and platform name to your server. ```java // 在 Activity 中获取 regId 并上报服务端 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 获取通知栏推送的 regId MixPushClient.getInstance().getRegisterId(this, new GetRegisterIdCallback() { @Override public void callback(MixPushPlatform platform) { if (platform != null) { String platformName = platform.getPlatformName(); // 如 "mi"、"huawei" String regId = platform.getRegId(); // 推送注册ID Log.d("MixPush", "平台: " + platformName + ", regId: " + regId); // TODO: 上报 regId 和 platformName 到服务端 uploadRegIdToServer(platformName, regId); } else { Log.e("MixPush", "获取 regId 超时或失败"); } } }); // 获取透传推送的 regId(第三个参数为 true) MixPushClient.getInstance().getRegisterId(this, new GetRegisterIdCallback() { @Override public void callback(MixPushPlatform platform) { if (platform != null) { Log.d("MixPush", "透传 regId: " + platform.getRegId()); } } }, true); } } ``` -------------------------------- ### MixPushClient.getRegisterId() - Get Push Registration ID Source: https://context7.com/taoweiji/mixpush/llms.txt Asynchronously retrieve the push registration ID (regId). This ID is used for server-side push operations. The method has a 60-second timeout and is recommended to be called in the `onCreate` method of your main activity. ```APIDOC ## MixPushClient.getRegisterId() ### Description Asynchronously get the push registration ID (regId). This ID is essential for reporting to your server to enable push notifications. The method includes a 60-second timeout and is best invoked during the activity's `onCreate` phase. ### Method `MixPushClient.getRegisterId(Context context, GetRegisterIdCallback callback)` `MixPushClient.getRegisterId(Context context, GetRegisterIdCallback callback, boolean isTransparent)` ### Parameters #### `MixPushClient.getRegisterId(Context context, GetRegisterIdCallback callback)` - **context** (Context) - Required - The application context. - **callback** (GetRegisterIdCallback) - Required - A callback interface to receive the registration ID and platform information. #### `MixPushClient.getRegisterId(Context context, GetRegisterIdCallback callback, boolean isTransparent)` - **context** (Context) - Required - The application context. - **callback** (GetRegisterIdCallback) - Required - A callback interface to receive the registration ID and platform information. - **isTransparent** (boolean) - Optional - If `true`, retrieves the registration ID for transparent messages; otherwise, retrieves the ID for notification messages. Defaults to `false`. ### Callback Interface `GetRegisterIdCallback` - `callback(MixPushPlatform platform)`: This method is called when the registration ID is successfully obtained or if an error occurs. `platform` contains details like `platformName` and `regId`. ### Usage Example (in Activity) ```java public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get regId for notification push MixPushClient.getInstance().getRegisterId(this, new GetRegisterIdCallback() { @Override public void callback(MixPushPlatform platform) { if (platform != null) { String platformName = platform.getPlatformName(); // e.g., "mi", "huawei" String regId = platform.getRegId(); // Push registration ID Log.d("MixPush", "Platform: " + platformName + ", regId: " + regId); // TODO: Upload regId and platformName to your server uploadRegIdToServer(platformName, regId); } else { Log.e("MixPush", "Failed to get regId or timed out"); } } }); // Get regId for transparent push (third parameter is true) MixPushClient.getInstance().getRegisterId(this, new GetRegisterIdCallback() { @Override public void callback(MixPushPlatform platform) { if (platform != null) { Log.d("MixPush", "Transparent regId: " + platform.getRegId()); } } }, true); } } ``` ``` -------------------------------- ### Configure Root build.gradle Source: https://github.com/taoweiji/mixpush/blob/master/README.md Add the necessary repositories and Huawei AGConnect classpath to the project's root build.gradle file. ```groovy buildscript { repositories { ... mavenCentral() maven { url 'http://developer.huawei.com/repo/' } } dependencies { ... classpath 'com.huawei.agconnect:agcp:1.6.0.300' } } allprojects { repositories { ... mavenCentral() jcenter() maven { url 'http://developer.huawei.com/repo/' } } } ``` -------------------------------- ### Configure and Send Push Notifications with MixPushSender Source: https://context7.com/taoweiji/mixpush/llms.txt Demonstrates initializing the MixPushSender with vendor credentials and implementing methods for single, batch, and broadcast push notifications. ```java public class PushService { private MixPushSender sender; public PushService() { this.sender = new MixPushSender.Builder() .packageName("com.example.myapp") .mi("mi_secret_key", false) .huawei("huawei_app_id", "huawei_app_secret") .oppo("oppo_app_key", "oppo_master_secret") .vivo("vivo_app_id", "vivo_app_key", "vivo_app_secret") .meizu("meizu_app_id", "meizu_secret_key") .test(false) .build(); } // 推送给单个用户 public MixPushResult pushToUser(String platformName, String regId, String title, String content, String payload) { MixPushMessageConfig config = new MixPushMessageConfig.Builder() .oppoPushChannelId("default") .vivoSystemMessage(false) .build(); MixPushMessage message = new MixPushMessage.Builder() .title(title) .description(content) .payload(payload) .config(config) .build(); MixPushTarget target = MixPushTarget.single(platformName, regId); MixPushResult result = sender.sendMessage(message, target); // 处理推送结果 if (result.isSucceed()) { System.out.println("推送成功, messageId: " + result.getMessageId()); } else { System.out.println("推送失败: " + result.getReason()); System.out.println("状态码: " + result.getStatusCode()); if (result.getError() != null) { result.getError().printStackTrace(); } } return result; } // 批量推送(分组推送) public MixPushResult pushToUsers(List users, String title, String content, String payload) { List platforms = new ArrayList<>(); for (UserPushInfo user : users) { platforms.add(new MixPushPlatform(user.getPlatformName(), user.getRegId())); } MixPushMessageConfig config = new MixPushMessageConfig.Builder() .oppoPushChannelId("activities") .vivoSystemMessage(false) .timeToLive(72 * 3600 * 1000) // 72小时有效期 .build(); MixPushMessage message = new MixPushMessage.Builder() .title(title) .description(content) .payload(payload) .config(config) .build(); MixPushTarget target = MixPushTarget.list(platforms); return sender.sendMessage(message, target); } // 全局推送(小米、VIVO、魅族支持,华为和OPPO需要用分组推送替代) public MixPushResult broadcastToAll(String title, String content, String payload) { MixPushMessageConfig config = new MixPushMessageConfig.Builder() .oppoPushChannelId("broadcast") .vivoSystemMessage(false) .build(); MixPushMessage message = new MixPushMessage.Builder() .title(title) .description(content) .payload(payload) .config(config) .build(); MixPushTarget target = MixPushTarget.broadcastAll(); MixPushResult result = sender.sendMessage(message, target); // 全局推送会返回多个平台的结果 for (MixPushResult subResult : result.getResults()) { System.out.println(subResult.getPlatformName() + ": " + (subResult.isSucceed() ? "成功" : subResult.getReason())); } return result; } } ``` -------------------------------- ### Configure App build.gradle Source: https://github.com/taoweiji/mixpush/blob/master/README.md Apply the Huawei plugin, set manifest placeholders for vendor credentials, and add the required MixPush dependencies. ```groovy apply plugin: 'com.huawei.agconnect' android { compileSdkVersion 31 defaultConfig { ... manifestPlaceholders["VIVO_APP_ID"] = "" manifestPlaceholders["VIVO_APP_KEY"] = "" manifestPlaceholders["MI_APP_ID"] = "" manifestPlaceholders["MI_APP_KEY"] = "" manifestPlaceholders["OPPO_APP_KEY"] = "" manifestPlaceholders["OPPO_APP_SECRET"] = "" manifestPlaceholders["MEIZU_APP_ID"] = "" manifestPlaceholders["MEIZU_APP_KEY"] = "" } } dependencies { def mixpush_version = '2.4.0' implementation "io.github.mixpush:mixpush-core:$mixpush_version" // 核心包 implementation "io.github.mixpush:mixpush-mi:$mixpush_version" // 小米推送 implementation "io.github.mixpush:mixpush-meizu:$mixpush_version" // 魅族推送 implementation "io.github.mixpush:mixpush-huawei:$mixpush_version" // 华为推送 implementation "io.github.mixpush:mixpush-oppo:$mixpush_version" // OPPO推送 implementation "io.github.mixpush:mixpush-vivo:$mixpush_version" // VIVO推送 } ``` -------------------------------- ### MixPush Client Initialization Source: https://github.com/taoweiji/mixpush/blob/master/README.md Instructions for initializing the MixPush SDK in an Android application, including setting up the receiver and registering the device. ```APIDOC ## Client Initialization ### Description Initialize the MixPush SDK in the Application class and define a custom receiver to handle push events. ### Implementation ```java // In Application class MixPush.getInstance().setPushReceiver(new MyPushReceiver()); MixPush.getInstance().register(this); // Get Register ID MixPushClient.getInstance().getRegisterId(this, new GetRegisterIdCallback() { public void callback(MixPushPlatform platform) { if (platform != null) { // TODO: Report regId to server } } }); ``` ``` -------------------------------- ### Initialize MixPush SDK in Application Class Source: https://context7.com/taoweiji/mixpush/llms.txt Initialize the MixPush client by setting a logger and a push receiver, then register the push service. This should be done in your Application class's onCreate method. ```java public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // 1. 设置日志监听器(可选) MixPushClient.getInstance().setLogger(new MixPushLogger() { @Override public void log(String tag, String content, Throwable throwable) { Log.e(tag, content); if (throwable != null) { throwable.printStackTrace(); } } @Override public void log(String tag, String content) { Log.e(tag, content); } }); // 2. 设置推送消息接收器 MixPushClient.getInstance().setPushReceiver(new MyMixPushReceiver()); // 3. 注册推送服务(自动识别手机厂商并注册对应推送平台) MixPushClient.getInstance().register(this); } } ``` -------------------------------- ### Initialize MixPush in Application Source: https://github.com/taoweiji/mixpush/blob/master/README.md Initialize MixPush in your Application class. This registers the custom receiver and defaults to initializing five push platforms, with Xiaomi as the default. ```java // 开启日志 //MixPush.getInstance().setLogger(new PushLogger(){}); MixPush.getInstance().setPushReceiver(new MyPushReceiver()); // 默认初始化5个推送平台(小米推送、华为推送、魅族推送、OPPO推送、VIVO推送),以小米推荐作为默认平台 MixPush.getInstance().register(this); ``` -------------------------------- ### Configure MixPushSender with Builder Source: https://context7.com/taoweiji/mixpush/llms.txt Use the MixPushSender.Builder to configure authentication details for various push platforms like Xiaomi, Huawei, Meizu, OPPO, and VIVO. This builder pattern allows for flexible and centralized configuration of the push sender. ```java // 创建推送发送器 MixPushSender sender = new MixPushSender.Builder() // 设置 APP 包名(必填) .packageName("com.example.myapp") // 配置小米推送(appSecretKey, 是否使用透传) .mi("your_mi_app_secret_key", false) // 配置华为推送(appId, appSecret) .huawei("your_huawei_app_id", "your_huawei_app_secret") // 配置魅族推送(appId, appSecretKey) .meizu("your_meizu_app_id", "your_meizu_app_secret_key") // 配置 OPPO 推送(appKey, masterSecret) .oppo("your_oppo_app_key", "your_oppo_master_secret") // 配置 VIVO 推送(appId, appKey, appSecret) .vivo("your_vivo_app_id", "your_vivo_app_key", "your_vivo_app_secret") // 配置小米 APNs 服务(用于 iOS 推送) .miAPNs("your_mi_apns_app_secret_key") // 测试模式(测试环境无法执行全局推送) .test(true) // 是否拦截测试数据(防止测试数据推送给所有用户) .interceptTestData(true) .build(); ``` -------------------------------- ### Android Client Gradle Dependencies Source: https://context7.com/taoweiji/mixpush/llms.txt Configure Gradle dependencies for the Android client, including the core package and vendor-specific push modules. Ensure to set manifest placeholders for each vendor's App ID and Key. ```groovy // 根目录 build.gradle buildscript { repositories { google() mavenCentral() maven { url 'http://developer.huawei.com/repo/' } } dependencies { classpath 'com.android.tools.build:gradle:7.0.0' classpath 'com.huawei.agconnect:agcp:1.6.0.300' } } allprojects { repositories { google() mavenCentral() jcenter() maven { url 'http://developer.huawei.com/repo/' } } } // app 目录 build.gradle apply plugin: 'com.android.application' apply plugin: 'com.huawei.agconnect' android { compileSdkVersion 31 defaultConfig { applicationId "com.example.myapp" minSdkVersion 21 targetSdkVersion 31 // 配置各厂商推送的 APP_ID 和 APP_KEY manifestPlaceholders["MI_APP_ID"] = "your_mi_app_id" manifestPlaceholders["MI_APP_KEY"] = "your_mi_app_key" manifestPlaceholders["VIVO_APP_ID"] = "your_vivo_app_id" manifestPlaceholders["VIVO_APP_KEY"] = "your_vivo_app_key" manifestPlaceholders["OPPO_APP_KEY"] = "your_oppo_app_key" manifestPlaceholders["OPPO_APP_SECRET"] = "your_oppo_app_secret" manifestPlaceholders["MEIZU_APP_ID"] = "your_meizu_app_id" manifestPlaceholders["MEIZU_APP_KEY"] = "your_meizu_app_key" } } dependencies { def mixpush_version = '2.4.0' // 核心包(必选) implementation "io.github.mixpush:mixpush-core:$mixpush_version" // 小米推送(推荐,支持所有 Android 设备) implementation "io.github.mixpush:mixpush-mi:$mixpush_version" // 华为推送(仅华为设备) implementation "io.github.mixpush:mixpush-huawei:$mixpush_version" // OPPO 推送(OPPO和一加手机) implementation "io.github.mixpush:mixpush-oppo:$mixpush_version" // VIVO 推送(仅VIVO手机) implementation "io.github.mixpush:mixpush-vivo:$mixpush_version" // 魅族推送(仅魅族手机) implementation "io.github.mixpush:mixpush-meizu:$mixpush_version" } ``` -------------------------------- ### Build MixPushMessage with Configuration Source: https://context7.com/taoweiji/mixpush/llms.txt Constructs a MixPushMessage including channel-specific configurations like OPPO, Huawei, and Mi push channel IDs. Ensure channel IDs are valid and created in the respective platform's backend. The message can include a title, description, payload, and other options. ```java // 构建消息配置(设置推送渠道等) MixPushMessageConfig config = new MixPushMessageConfig.Builder() // OPPO 渠道ID(必填,需在 OPPO 后台创建) .oppoPushChannelId("activities") // 华为渠道ID(可选) .huaweiPushChannelId("default") // 小米渠道ID(可选,IM/订单类消息需申请) .miPushChannelId("high_priority") // VIVO 系统消息标识(true=系统消息无限制,false=运营消息每日5条限制) .vivoSystemMessage(false) // 消息有效期(最长72小时,单位毫秒) .timeToLive(24 * 3600 * 1000) .build(); // 构建推送消息 MixPushMessage message = new MixPushMessage.Builder() // 通知栏标题(必填) .title("您有一个新订单") // 通知栏副标题(必填) .description("订单号: 20231201001,请及时处理") // 附加数据(必须是 JSON 格式) .payload("{\"type\":\"order\",\"orderId\":\"20231201001\",\"url\":\"myapp://order/detail?id=20231201001\"}") // 消息配置 .config(config) // 是否为透传消息(默认 false) .passThrough(false) // 仅打开 APP(不携带额外数据) .justOpenApp(false) // 自定义消息ID(可选,默认自动生成 UUID) .messageId("custom_msg_id_001") .build(); ``` -------------------------------- ### MixPushSender.Builder - Server-side Configuration Source: https://context7.com/taoweiji/mixpush/llms.txt Builder pattern to configure authentication credentials for various push platforms. ```APIDOC ## MixPushSender.Builder ### Description Configures credentials for Xiaomi, Huawei, Meizu, OPPO, VIVO, and APNs to create a unified push sender instance. ### Configuration Methods - **packageName(String)**: Required. Sets the app package name. - **mi(String, boolean)**: Configures Xiaomi push. - **huawei(String, String)**: Configures Huawei push. - **meizu(String, String)**: Configures Meizu push. - **oppo(String, String)**: Configures OPPO push. - **vivo(String, String, String)**: Configures VIVO push. - **miAPNs(String)**: Configures Xiaomi APNs for iOS. - **test(boolean)**: Enables test mode. - **interceptTestData(boolean)**: Prevents test data from being sent to all users. ``` -------------------------------- ### Implement MixPushReceiver Source: https://context7.com/taoweiji/mixpush/llms.txt Extend MixPushReceiver to handle push registration success and notification clicks. Upload the registration ID on success and implement logic to open specific app pages or URLs when a notification is clicked. ```java public class MyMixPushReceiver extends MixPushReceiver { /** * 推送注册成功回调 * 建议在此处上传 regId 到服务端 */ @Override public void onRegisterSucceed(Context context, MixPushPlatform platform) { String platformName = platform.getPlatformName(); String regId = platform.getRegId(); Log.d("MixPush", "注册成功 - 平台: " + platformName + ", regId: " + regId); // 上报 regId 到服务端 ApiService.uploadPushToken(platformName, regId); } /** * 通知栏消息被点击回调 * 在此处实现打开具体页面、打开浏览器等操作 */ @Override public void onNotificationMessageClicked(Context context, MixPushMessage message) { String title = message.getTitle(); // 通知标题 String description = message.getDescription(); // 通知副标题 String payload = message.getPayload(); // 附加数据(JSON格式) String platform = message.getPlatform(); // 推送平台 Intent intent = null; if (payload != null && !payload.isEmpty()) { try { JSONObject json = new JSONObject(payload); String url = json.optString("url", ""); if (url.startsWith("http")) { // 打开浏览器或 WebView intent = new Intent(context, WebViewActivity.class); intent.putExtra("url", url); } else if (url.contains("/user")) { // 打开用户详情页 Uri uri = Uri.parse(url); String userId = uri.getQueryParameter("userId"); intent = new Intent(context, UserActivity.class); intent.putExtra("userId", userId); } } catch (JSONException e) { e.printStackTrace(); } } // 默认打开 APP 主页 if (intent == null) { intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); } if (intent != null) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } /** * 通知栏消息到达回调(可选) */ @Override public void onNotificationMessageArrived(Context context, MixPushMessage message) { Log.d("MixPush", "消息到达: " + message.getTitle()); } /** * 打开 APP 回调(可选,用于统计) */ @Override public void openAppCallback(Context context) { Log.d("MixPush", "APP 被打开"); } } ``` -------------------------------- ### MixPushMessage.Builder - Building Push Messages Source: https://context7.com/taoweiji/mixpush/llms.txt Use the Builder pattern to construct push message content, including titles, subtitles, additional data, and channel configurations. ```APIDOC ## MixPushMessage.Builder - Building Push Messages ### Description Use the Builder pattern to construct push message content, including titles, subtitles, additional data, and channel configurations. ### Request Body Example (Java) ```java // Build message configuration (set push channels, etc.) MixPushMessageConfig config = new MixPushMessageConfig.Builder() // OPPO channel ID (required, must be created in OPPO backend) .oppoPushChannelId("activities") // Huawei channel ID (optional) .huaweiPushChannelId("default") // Xiaomi channel ID (optional, requires application for IM/order messages) .miPushChannelId("high_priority") // VIVO system message flag (true = system messages have no limit, false = operational messages have a daily limit of 5) .vivoSystemMessage(false) // Message validity period (max 72 hours, in milliseconds) .timeToLive(24 * 3600 * 1000) .build(); // Build the push message MixPushMessage message = new MixPushMessage.Builder() // Notification title (required) .title("You have a new order") // Notification subtitle (required) .description("Order ID: 20231201001, please process promptly") // Additional data (must be in JSON format) .payload("{\"type\": \"order\", \"orderId\": \"20231201001\", \"url\": \"myapp://order/detail?id=20231201001\"}") // Message configuration .config(config) // Whether it is a transparent message (default false) .passThrough(false) // Only open the APP (without carrying extra data) .justOpenApp(false) // Custom message ID (optional, UUID generated automatically by default) .messageId("custom_msg_id_001") .build(); ``` ``` -------------------------------- ### MixPushTarget - Push Target Source: https://context7.com/taoweiji/mixpush/llms.txt Define the target users for the push. Supports single user, multiple users, and global push modes. ```APIDOC ## MixPushTarget - Push Target ### Description Define the target users for the push. Supports single user, multiple users, and global push modes. ### Request Body Example (Java) ```java // 1. Single user push MixPushTarget singleTarget = MixPushTarget.single("mi", "your_user_reg_id"); // 2. Multiple users push (can cross platforms) MixPushTarget multiTarget = MixPushTarget.values( new MixPushPlatform("mi", "mi_user_reg_id_1"), new MixPushPlatform("mi", "mi_user_reg_id_2"), new MixPushPlatform("huawei", "huawei_user_reg_id_1"), new MixPushPlatform("oppo", "oppo_user_reg_id_1") ); // 3. Build target from a list List platforms = new ArrayList<>(); platforms.add(new MixPushPlatform("mi", "reg_id_1")); platforms.add(new MixPushPlatform("vivo", "reg_id_2")); MixPushTarget listTarget = MixPushTarget.list(platforms); // 4. Global push (Huawei/OPPO/APNs do not support, use group push instead) MixPushTarget broadcastTarget = MixPushTarget.broadcastAll(); ``` ``` -------------------------------- ### Define MixPushTarget from a List Source: https://context7.com/taoweiji/mixpush/llms.txt Constructs a push target from a list of MixPushPlatform objects. This method is flexible for dynamically building target lists based on application logic. ```java // 3. 从列表构建目标 List platforms = new ArrayList<>(); platforms.add(new MixPushPlatform("mi", "reg_id_1")); platforms.add(new MixPushPlatform("vivo", "reg_id_2")); MixPushTarget listTarget = MixPushTarget.list(platforms); ``` -------------------------------- ### Implement MixPushPassThroughReceiver Source: https://context7.com/taoweiji/mixpush/llms.txt Extend MixPushPassThroughReceiver to handle messages that bypass the notification bar. Implement onRegisterSucceed for registration callbacks and onReceivePassThroughMessage to process the message payload directly. ```java public class MyPassThroughReceiver extends MixPushPassThroughReceiver { @Override public void onRegisterSucceed(Context context, MixPushPlatform platform) { Log.d("MixPush", "透传注册成功: " + platform.getRegId()); } @Override public void onReceivePassThroughMessage(Context context, MixPushMessage message) { String payload = message.getPayload(); Log.d("MixPush", "收到透传消息: " + payload); // 处理透传消息,例如更新 IM 消息 try { JSONObject json = new JSONObject(payload); String type = json.getString("type"); if ("new_message".equals(type)) { // 处理新消息 String content = json.getString("content"); String senderId = json.getString("senderId"); // 通知 UI 更新... } } catch (JSONException e) { e.printStackTrace(); } } } // 在 Application 中设置透传接收器 MixPushClient.getInstance().setPassThroughReceiver(new MyPassThroughReceiver()); ``` -------------------------------- ### Define MixPushTarget for Multiple Users Source: https://context7.com/taoweiji/mixpush/llms.txt Defines multiple users across different platforms as targets for a push notification. This allows for sending messages to a specific set of users regardless of their device platform. ```java // 2. 多个用户推送(可跨平台) MixPushTarget multiTarget = MixPushTarget.values( new MixPushPlatform("mi", "mi_user_reg_id_1"), new MixPushPlatform("mi", "mi_user_reg_id_2"), new MixPushPlatform("huawei", "huawei_user_reg_id_1"), new MixPushPlatform("oppo", "oppo_user_reg_id_1") ); ``` -------------------------------- ### Define Push Receiver Source: https://github.com/taoweiji/mixpush/blob/master/README.md Implement MixPushReceiver to handle registration success and notification clicks. Upload the registration ID and platform information to your server in onRegisterSucceed. ```java public class MyPushReceiver extends MixPushReceiver { @Override public void onRegisterSucceed(Context context, MixPushPlatform mixPushPlatform) { // 这里需要实现上传regId和推送平台信息到服务端保存, //也可以通过MixPushClient.getInstance().getRegisterId的方式实现 } @Override public void onNotificationMessageClicked(Context context, MixPushMessage message) { // TODO 通知栏消息点击触发,实现打开具体页面,打开浏览器等。 } } ``` -------------------------------- ### MixPush Server Sender Source: https://github.com/taoweiji/mixpush/blob/master/README.md Documentation for the server-side Java SDK used to send push notifications to various platforms. ```APIDOC ## Server-Side Push Notification ### Description Use the `MixPushSender` to dispatch notifications to specific platforms or targets. ### Request Body - **message** (MixPushMessage) - Required - The notification content (title, description, payload). - **target** (MixPushTarget) - Required - The target platform and device identifier. ### Request Example ```java MixPushSender sender = new MixPushSender.Builder() .packageName("") .mi("", false) .huawei("", "") .build(); MixPushMessage message = new MixPushMessage.Builder() .title("Title") .description("Description") .build(); MixPushTarget target = MixPushTarget.single("mi", "xxxx"); sender.sendNotificationMessage(message, target); ``` ``` -------------------------------- ### Define MixPushTarget for Broadcast Source: https://context7.com/taoweiji/mixpush/llms.txt Creates a target for a global broadcast push. Note that global push is not supported for all platforms like Huawei, OPPO, and APNs, and may require using group push as an alternative. ```java // 4. 全局推送(华为/OPPO/APNs 不支持,需使用分组推送替代) MixPushTarget broadcastTarget = MixPushTarget.broadcastAll(); ``` -------------------------------- ### MixPushClient.register() - Register Push Service Source: https://context7.com/taoweiji/mixpush/llms.txt Register the push service. This method automatically selects the appropriate push platform based on the device's manufacturer. It supports overloaded methods for default platform specification and transparent message platform specification. ```APIDOC ## MixPushClient.register() ### Description Register the push service. This method automatically detects the device's manufacturer and registers with the corresponding push platform. It supports different initialization strategies. ### Method `MixPushClient.register(Context context)` `MixPushClient.register(Context context, String defaultPlatform)` `MixPushClient.register(Context context, String defaultPlatform, String transparentPlatform)` ### Parameters #### `MixPushClient.register(Context context)` - **context** (Context) - Required - The application context. #### `MixPushClient.register(Context context, String defaultPlatform)` - **context** (Context) - Required - The application context. - **defaultPlatform** (String) - Optional - The name of the default push platform to use (e.g., "mi"). If not specified, Xiaomi push is used as the default. #### `MixPushClient.register(Context context, String defaultPlatform, String transparentPlatform)` - **context** (Context) - Required - The application context. - **defaultPlatform** (String) - Optional - The name of the default push platform for notifications. - **transparentPlatform** (String) - Optional - The name of the push platform for transparent messages. Note: If Xiaomi is used as the transparent platform, global push functionality may be limited. ### Supported Platform Names - `"mi"` - Xiaomi Push (All Android devices) - `"huawei"` - Huawei Push (Huawei devices only) - `"oppo"` - OPPO Push (OPPO and OnePlus devices) - `"vivo"` - VIVO Push (VIVO devices only) - `"meizu"` - Meizu Push (Meizu devices only) ### Usage Examples ```java // Method 1: Default initialization (Xiaomi push as default, supports all Android devices) MixPushClient.getInstance().register(context); // Method 2: Specify default push platform MixPushClient.getInstance().register(context, "mi"); // Method 3: Specify both notification and transparent push platforms MixPushClient.getInstance().register(context, "mi", "mi"); ``` ``` -------------------------------- ### Java Server Gradle Dependency Source: https://context7.com/taoweiji/mixpush/llms.txt Configure the Gradle dependency for the MixPush sender on the server-side. Ensure you use the correct version for your project. ```groovy // Gradle 依赖 dependencies { implementation 'io.github.mixpush:mixpush-sender:2.3.9' } ``` -------------------------------- ### Register MixPush Service with Different Platforms Source: https://context7.com/taoweiji/mixpush/llms.txt Register the MixPush service, automatically selecting the appropriate platform based on the device manufacturer. You can specify a default platform or both a notification and a transparent message platform. ```java // 方式一:默认初始化(小米推送作为默认平台,支持所有 Android 设备) MixPushClient.getInstance().register(context); // 方式二:指定默认推送平台 MixPushClient.getInstance().register(context, "mi"); // 方式三:同时指定通知栏推送平台和透传推送平台 // 注意:如果开启小米作为透传平台,将无法使用全局推送功能 MixPushClient.getInstance().register(context, "mi", "mi"); // 支持的平台名称常量: // "mi" - 小米推送(所有 Android 设备) // "huawei" - 华为推送(仅华为设备) // "oppo" - OPPO推送(OPPO和一加手机) // "vivo" - VIVO推送(仅VIVO手机) // "meizu" - 魅族推送(仅魅族手机) ``` -------------------------------- ### MixPush Proguard Rules Source: https://github.com/taoweiji/mixpush/blob/master/README.md Essential Proguard rules for MixPush and various push providers (Xiaomi, Huawei, OPPO, VIVO, Meizu) to prevent code stripping during release builds. ```proguard # MixPush -keep class com.mixpush.mi.MiPushProvider {*;} -keep class com.mixpush.meizu.MeizuPushProvider {*;} -keep class com.mixpush.huawei.HuaweiPushProvider {*;} -keep class com.mixpush.oppo.OppoPushProvider {*;} -keep class com.mixpush.vivo.VivoPushProvider {*;} # 华为推送 -ignorewarnings -keepattributes *Annotation* -keepattributes Exceptions -keepattributes InnerClasses -keepattributes Signature -keepattributes SourceFile,LineNumberTable -keep class com.huawei.hianalytics.**{*;} -keep class com.huawei.updatesdk.**{*;} -keep class com.huawei.hms.**{*;} # 小米推送 -keep class com.xiaomi.**{*;} # OPPO -keep public class * extends android.app.Service -keep class com.heytap.msp.** { *;} # VIVO -dontwarn com.vivo.push.** -keep class com.vivo.push.**{*; } -keep class com.vivo.vms.**{*; } # 魅族 -keep class com.meizu.**{*;} ``` -------------------------------- ### Java Server Maven Dependency Source: https://context7.com/taoweiji/mixpush/llms.txt Configure the Maven dependency for the MixPush sender on the server-side. Ensure you use the correct version for your project. ```xml io.github.mixpush mixpush-sender 2.3.9 ``` -------------------------------- ### Handle Push Results in Java Source: https://context7.com/taoweiji/mixpush/llms.txt Process the results of a push operation, checking for success, retrieving message IDs, task IDs, platform-specific status codes, reasons, and errors. It also shows how to access sub-results for global or batch pushes and convert the result to JSON. ```java // 处理推送结果 MixPushResult result = sender.sendMessage(message, target); // 判断是否成功 boolean success = result.isSucceed(); // 获取消息ID String messageId = result.getMessageId(); // 获取任务ID(用于某些平台的消息追踪) String taskId = result.getTaskId(); // 获取平台名称 String platformName = result.getPlatformName(); // 获取状态码 String statusCode = result.getStatusCode(); // 状态码说明: // "100" - TEST_ENV_CAN_NOT_BROADCAST: 测试环境无法执行全局推送 // "101" - TEST_DATA_CAN_NOT_BROADCAST: 测试数据无法推送给超过10人 // "102" - NOT_SUPPORT_BROADCAST: 不支持全局推送 // "103" - NOT_SUPPORT: 没有找到对应的注册平台 // "104" - NOT_SUPPORT_PASS_THROUGH: 不支持透传 // 获取错误原因 String reason = result.getReason(); // 获取异常信息 Throwable error = result.getError(); // 获取子结果列表(全局推送或批量推送时) List subResults = result.getResults(); for (MixPushResult subResult : subResults) { System.out.println(String.format("平台: %s, 成功: %s, 原因: %s", subResult.getPlatformName(), subResult.isSucceed(), subResult.getReason())); } // 转换为 JSON 格式 JSONObject json = result.toJSON(); System.out.println(json.toString()); // 输出示例: // { // "succeed": true, // "platformName": "mi", // "statusCode": null, // "reason": null, // "messageId": "550e8400-e29b-41d4-a716-446655440000", // "taskId": null, // "results": [], // "extra": null, // "error": null // } ``` -------------------------------- ### Add MixPush Sender Dependency Source: https://github.com/taoweiji/mixpush/blob/master/README.md Include the MixPush sender dependency in your project's pom.xml or build.gradle file to enable server-side push notification management. ```xml io.github.mixpush mixpush-sender 2.3.9 ``` -------------------------------- ### Define MixPushTarget for Single User Source: https://context7.com/taoweiji/mixpush/llms.txt Specifies a single user as the target for a push notification using their platform and registration ID. This is useful for sending targeted messages to individual users. ```java // 1. 单个用户推送 MixPushTarget singleTarget = MixPushTarget.single("mi", "your_user_reg_id"); ``` -------------------------------- ### MixPushSender.sendMessage() - Send Push Message Source: https://context7.com/taoweiji/mixpush/llms.txt Sends a push message to a specified target. This method automatically distributes the message to the corresponding vendor push services based on the target platform. It handles sending messages to single users, lists of users, or broadcasting to all users. ```APIDOC ## POST /api/mixpush/send ### Description Sends a push message to specified targets. The system automatically routes the message to the appropriate platform-specific push services. ### Method POST ### Endpoint /api/mixpush/send ### Parameters #### Request Body - **message** (MixPushMessage) - Required - The message content and configuration. - **target** (MixPushTarget) - Required - The target for the push notification (single user, list of users, or broadcast). ### Request Example ```json { "message": { "title": "Notification Title", "description": "Notification Content", "payload": "{\"key\": \"value\"}", "config": { "oppoPushChannelId": "default", "vivoSystemMessage": false, "timeToLive": 7200000 } }, "target": { "type": "single", "platformName": "xiaomi", "regId": "user_registration_id" } } ``` ### Response #### Success Response (200) - **MixPushResult** (object) - The result of the push operation, including success status, message ID, and reason for failure if applicable. #### Response Example ```json { "succeed": true, "messageId": "msg_12345abc", "results": [ { "platformName": "xiaomi", "succeed": true, "messageId": "xiaomi_msg_id" } ] } ``` ``` -------------------------------- ### MixPushPassThroughReceiver - Pass-through Message Receiver Source: https://context7.com/taoweiji/mixpush/llms.txt Abstract class for handling pass-through messages that do not appear in the notification bar. ```APIDOC ## MixPushPassThroughReceiver ### Description Used for receiving pass-through messages directly in the app, suitable for real-time communication scenarios. ### Methods - **onRegisterSucceed(Context context, MixPushPlatform platform)**: Triggered when registration is successful. - **onReceivePassThroughMessage(Context context, MixPushMessage message)**: Triggered when a pass-through message is received. The payload can be parsed to perform custom logic like updating IM messages. ```