我有一个应用程序,它从基于php的服务器接收推送通知,推送通知是一个数据负载,其中包含一个url,单击时会自动在网络视图中打开。
我的应用程序可以工作,但不是按照我希望的方式工作。我可以从我的php服务器发送推送通知,但只有当应用程序在前台时,通知才会显示,但当它在后台时,它不会显示。
当我检查logcat时,我发现json数据是从服务器发送的,即使应用程序在后台当应用程序处于后台或被终止时,是什么阻止了推送通知的显示
下面是我的FirebaseMessaging类
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脚本
<?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
,直到您完成了一些工作中的活动
要解决您的问题,您需要在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;
}
不要忘记在MyFirebaseMessagingService中定义方法private void showNotification(String title, String message)