Scenes
There are often background services that push notifications to Android.
achieve
First create a new Android application in Android Studio
Jcenter is configured in the build.gradle of the project root directory, and support is configured by default
Then add the relevant dependencies in the build.gradle of the app under the module
implementation 'cn.jiguang.sdk:jpush:3.3.4' // 此处以JPush 3.3.4 版本为例。
implementation 'cn.jiguang.sdk:jcore:2.1.0' // 此处以JCore 2.1.0 版本为例。
Add the location as follows
Then replace the variables in the manifest
defaultConfig {
applicationId "com.badao.pushdemo"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
ndk {
//选择要添加的对应cpu类型的.so库。
abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64', 'mips', 'mips64'
}
manifestPlaceholders = [
JPUSH_PKGNAME : applicationId,
JPUSH_APPKEY : "Push上注册的包名对应的appkey", //JPush上注册的包名对应的appkey.
JPUSH_CHANNEL : "developer-default", //暂时填写默认值即可.
]
}
Replacement location
Pay attention to two places here:
applicationId is the same package name when you create a new application on the Jiguang development platform.
Then the JPUSH_APPKEY below is the corresponding appkey of the newly created application
Then open the project's AndroidManifest.xml to add permissions
<!-- Required -->
<permission
android:name="com.badao.pushdemo.permission.JPUSH_MESSAGE"
android:protectionLevel="signature" />
<!-- Required -->
<uses-permission android:name="com.badao.pushdemo.permission.JPUSH_MESSAGE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Optional. Required for location feature -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <!-- 用于开启 debug 版本的应用在 6.0 系统上的层叠窗口权限 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.VIBRATE" />
Note that the package name in front of the first permission here must be the same
Then register another service that inherits JCommonService in AndroidManifest.xml
<!-- 注册继承JCommonService的服务 -->
<service
android:name=".PushService"
android:enabled="true"
android:exported="false"
android:process=":pushcore">
<intent-filter>
<action android:name="cn.jiguang.user.service.action" />
</intent-filter>
</service>
Then create a new PushService under the package path
code show as below
package com.badao.pushdemo;
import cn.jpush.android.service.JCommonService;
public class PushService extends JCommonService {
}
Then customize a receiver in AndroidManifest.xml to replace the native Jiguang push receiver
<!-- 替换原生极光推送接收器 -->
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" />
<category android:name="com.badao.pushdemo" /> <!--JPush上注册的包名 -->
</intent-filter>
</receiver>
Note that the package name here is the same as the one registered on JPush
Then create a new MyReceiver under the package path
Modify the code as follows
package com.badao.pushdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;
public class MyReceiver extends JPushMessageReceiver {
private static final String TAG = "JIGUANG";
private Intent intent;
@Override
public void onConnected(Context context, boolean b) {
super.onConnected(context, b);
Log.e(TAG, "onConnected");
}
@Override
public void onRegister(Context context, String s) {
super.onRegister(context, s);
Log.e(TAG, "onRegister" + s);
}
@Override
public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
Log.i("bieming","bieming:"+jPushMessage.getAlias());
super.onAliasOperatorResult(context, jPushMessage);
Log.e(TAG, jPushMessage.toString());
}
/**
* 可以利用附加字段(notificationMessage.notificationExtras)来区别Notication,指定不同的动作,附加字段是个json字符串
* 通知(Notification),指在手机的通知栏(状态栏)上会显示的一条通知信息
*/
@Override
public void onNotifyMessageArrived(Context context, NotificationMessage notificationMessage) {
super.onNotifyMessageArrived(context, notificationMessage);
Log.e(TAG, notificationMessage.toString());
}
/**
* notificationMessage.notificationExtras(附加字段)的内容处理代码
* 比如打开新的Activity, 打开一个网页等..
*/
@Override
public void onNotifyMessageOpened(Context context, NotificationMessage notificationMessage) {
super.onNotifyMessageOpened(context, notificationMessage);
Log.e(TAG, notificationMessage.notificationExtras);
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}
/**
* 自定义消息不是通知,默认不会被SDK展示到通知栏上,极光推送仅负责透传给SDK。其内容和展示形式完全由开发者自己定义。
* 自定义消息主要用于应用的内部业务逻辑和特殊展示需求
*/
@Override
public void onMessage(Context context, CustomMessage customMessage) {
super.onMessage(context, customMessage);
Log.e(TAG, "onMessage");
}
}
Rewrite some methods in the custom receiver to implement related callbacks
Then initialize Jpush in MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化极光推送
JPushInterface.setDebugMode(true);
JPushInterface.init(this);
if (!isNotificationEnabled(this)) {
gotoSet();//去设置开启通知
} else {
//当前app允许消息通知
}
}
Then make a judgment on whether to set up notifications later, where
//是否允许通知
private boolean isNotificationEnabled (Context context){
boolean isOpened = false;
try {
isOpened = NotificationManagerCompat.from(context).areNotificationsEnabled();
} catch (Exception e) {
e.printStackTrace();
isOpened = false;
}
return isOpened;
}
then
//去设置允许通知
private void gotoSet () {
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= 26) {
// android 8.0引导
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
} else if (Build.VERSION.SDK_INT >= 21) {
// android 5.0-7.0
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", getPackageName());
intent.putExtra("app_uid", getApplicationInfo().uid);
} else {
// 其他
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package", getPackageName(), null));
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Then run the project, log in to the Jiguang Developer Platform to find the push message
The premise is to perform the following operations
Find the developer service on the Jpush official website and enter the developer platform
Then click create app
Set a package name when creating a new application, remember that this package name will be used in the code
Then select push service
Click Next, and then you can select the vendor channel to be integrated
Choose to integrate Android
Then the official provides integrated documentation and SDK downloads and demos. When we integrate in Android, we can integrate dependencies through jcenter. After the new application is completed
Copy out the application package name and AppKey,
The target group chooses everyone
You will receive a push in the App
Push through the designated device by alias setting
The above is to push all devices, if you need to push to the specified device
This can be achieved by setting the alias of the device.
Pay attention to the difference with the label, the label is a type of device, and the alias is the designated device
First add two buttons on the main page
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="注册别名"
tools:layout_editor_absoluteX="210dp"
tools:layout_editor_absoluteY="462dp" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="解除注册别名"
tools:layout_editor_absoluteX="210dp"
tools:layout_editor_absoluteY="462dp"
android:layout_below="@id/button1"/>
</RelativeLayout>
Then set the click event in onCreate in MainActivity to set alias and delete alias respectively.
//设置别名-一般在登录时
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
JPushInterface.setAlias(getApplicationContext(),0000000001,"badaodechengxvyuan");
Log.i("setAlias","setAlias");
}
});
//删除别名一般在注销登录时
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
JPushInterface.deleteAlias(getApplicationContext(),0000000001);
Log.i("deleteAlias","deleteAlias");
}
});
The alias setting is generally set when the App is logged in
Then delete the alias generally after logout and login. Here, setting the alias and deleting the alias are implemented using button events.
Then start the project and click the Register Alias button.
In addition, the onAliasOperatorResult in the custom receiver can implement callbacks for alias registration and deletion.
Then log in to the Jiguang developer background and set the device alias in the target selection in the message push
Then you will receive the push in the specified app device
Then you can see in the log that you have entered the callback of the alias setting
Then click the delete alias registration button again, then the push message will not be received on the device, and it will be prompted in the background of Jiguang Developer
Then also output in the callback method
Sample code download
https://download.csdn.net/download/BADAO_LIUMANG_QIZHI/15435342