我有一个应用程序,它从一个基于php的服务器接收推送通知,推送通知是一个数据负载,其中包含一个url当点击时会自动在webview中打开。
public class MyFirebaseMessagingService extends FirebaseMessagingService{
private final String CHANNEL_ID="notificcation";
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
handleMessage(remoteMessage.getData().get(Config.STR_KEY));
}
private void handleMessage(String message) {
Intent pushNotification=new Intent(Config.STR_PUSH);
pushNotification.putExtra(Config.STR_MESSAGE,message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
}
}
<?php
require "init.php";
$message=$_POST['message'];
$title=$_POST['title'];
$url=$_POST['url'];
$path_to_fcm='https://fcm.googleapis.com/fcm/send';
$server_key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$sql="SELECT fcm_token FROM fcm_info";
$result=mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$key=$row['fcm_token'];
}
$headers=array(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);
$fields=array(
'to'=>$key,
'data'=>array('title'=>$title,'body'=>$message,'webUrl'=>$url));
$payload=json_encode($fields);
$curl_session=curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
$result=curl_exec($curl_session);
mysqli_close($con);
?>
我的主要活动
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressDialog dialog;
private BroadcastReceiver mRegistrationBroadcastReciever;
private final String CHANNEL_ID="notificcation";
String app_server_url="http:/xxxxxxxxxxx/insert.php";
@Override
public void onBackPressed() {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
if(webView.canGoBack()){
webView.goBack();
}else{
builder.setTitle("Do you want to leave the App?");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog=builder.show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences=getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
final String token=sharedPreferences.getString(getString(R.string.FCM_TOKEN),"");
StringRequest stringRequest=new StringRequest(Request.Method.POST, app_server_url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String>params=new HashMap<String,String>();
params.put("fcm_token",token);
return params;
}
};
MySingleton.getmInstance(MainActivity.this).addToRequestque(stringRequest);
webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("http://default_website");
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
if(dialog.isShowing())
dialog.dismiss();
}
});
mRegistrationBroadcastReciever=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Config.STR_PUSH))
{
String message=intent.getStringExtra(Config.STR_MESSAGE);
showNotification("Article",message);
}
}
};
onNewIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
dialog=new ProgressDialog(this);
if(intent.getStringExtra(Config.STR_KEY)!=null)
{
dialog.show();
dialog.setMessage("Please Wait");
webView.loadUrl(intent.getStringExtra(Config.STR_KEY));
}
}
private void showNotification(String title, String message) {
notificationChannel();
Bitmap picture = BitmapFactory.decodeResource(getResources(),R.mipmap.app_launcher);
Intent intent =new Intent(getBaseContext(),MainActivity.class);
intent.putExtra(Config.STR_KEY,message);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent=PendingIntent.getActivity(getBaseContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder=new NotificationCompat.Builder(getBaseContext(),CHANNEL_ID);
builder.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_sms_black_24dp)
.setContentTitle(title)
.setContentText(message)
.setLargeIcon(picture)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
private void notificationChannel (){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
CharSequence name="Personal Notificaiton";
String description="include";
int importance=NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,name,importance);
notificationChannel.setDescription(description);
NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReciever);
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReciever,new IntentFilter("registration Complete"));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReciever,new IntentFilter(Config.STR_PUSH));
}
}
通过查看您的代码,我建议您不要使用LocalBroadcastManager
,直到您在Activity中完成某些工作。
要解决您的问题,您需要在MyFireBaseMessagingService
中编写ShowNotification
方法并直接调用它。
如果仍有一些工作在活动中,则需要使用以下代码块
MyFireBaseMessagingService=>OnMessageReceived()
if (!isAppIsInBackground(getApplicationContext())) {
Intent pushNotification=new Intent(Config.STR_PUSH);
pushNotification.putExtra(Config.STR_MESSAGE,message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
} else {
showNotification("Article",message);
}
并添加以下检查应用程序是否在后台的方法
public static boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
isInBackground = false;
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}
return isInBackground;
}
不要忘记在MyFirebaseMessagingServiceprivate void showNotification(字符串标题,字符串消息)
中定义方法
index.js中的代码 bgmessaging.js中的代码负责应用程序在后台时的推送 为了在应用程序处于前台时带来图像,我使用了下面的代码:-
我正在尝试构建一个实时聊天应用程序。 我已经整合了https://pub.dev/packages/flutter_local_notifications用于推送通知的软件包,这是有效的。 我没有使用Firebase,我正在使用我自己的自定义后端,使用https://socket.io/进行实时聊天。 我想在用户发送聊天信息时接收推送通知。推送通知在应用程序处于前台或后台时起作用。但是,当我从进程
根据Firebase文档: 我的问题是,当应用程序在后台时,通知系统不显示通知。 我没有使用Firebase控制台,因为我无法将数据添加到通知负载中。所以我使用了RESTful客户机API,但还是同样的问题。 请求:
我想为一个聊天应用程序实现FCM推送通知服务,我遵循Firebase文档中的步骤,当通知从Firebase控制台发送到我的设备时,我会得到通知。当我尝试使用http post to https://FCM.googleapis.com/FCM/send通过FCM将通知通过服务器端发送到设备时: 当应用程序处于活动状态并且我正在将此通知发送到我的设备时,Im在我的控制台日志中收到以下消息,所以我认为
通知通道的新代码在旧的和最新的奥利奥设备上运行良好,但当我在API 28(android P)设备上测试时,它没有在通知栏中显示通知,这是我用来启动前台通知的行。
这是舱单 这是我的注册令牌类 这是我的Firebase服务类