Firebase通知,在后台或被杀死时不显示,但已发送数据

时间:2018-11-04 10:33:15

标签: php android firebase firebase-cloud-messaging android-volley

我有这个应用程序,该应用程序从基于php的服务器接收推送通知,该推送通知是一种数据有效负载,其中包含一个URL,当单击该URL时,它会自动在web视图中打开。

我的应用程序可以运行,但是不能以我希望的方式运行。 我能够从我的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 TuneMe 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));
}


 }

1 个答案:

答案 0 :(得分:0)

通过查看代码,建议您不要从事LocalBroadcastManager,直到您从事一些活动中的工作。
要解决您的问题,您需要在showNotification中编写MyFirebaseMessagingService方法并直接调用。

如果您仍在从事一些工作,则需要使用以下代码块进行操作

  

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)