当我的应用程序使用Google Firebase云消息时,我怎么能收到推送消息
我将Google Firebase云消息集成到了我的应用程序中。当我的应用程序处于前台或后台时,它可以接收来自Google服务器的消息推送,但是如果我的应用程序已经停用,它将无法收到来自Google服务器的消息推送。我想要的是,如果我的应用程序已经死了,它仍然可以从谷歌服务器收到消息。这里是我的代码:当我的应用程序使用Google Firebase云消息时,我怎么能收到推送消息
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FirebaseMsgServiceDemo";
@Override
public void onMessageReceived(RemoteMessage remotemsg) {
Log.d(TAG, "Demo Notification Body -> " + remotemsg.getNotification().getBody());
sendNotification(remotemsg.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Demo Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
Logger.e("TESTTTTT111111111", token);
sendRegistrationToServer(token);
}
private void sendRegistrationToServer(String token) {
}
}
<service
android:name="com.linkus.fcm.MyFirebaseInstanceIDService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name="com.linkus.fcm.MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
你在找什么是Services。建议大家阅读Android Studio here的文档。
服务将允许您的应用程序的一个非常特定的部分在任何时候都能够存活。即使用户重新启动设备,并且再也不会运行应用程序。有很多感知有关服务,但在那一刻,我相信一个片段将是最有帮助你,这里是一个小码,
创建一个名为HelloService的
类和粘贴下面的代码与适当的进口*
public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "servicestarting",Toast.LENGTH_SHORT).show();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
@Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}
“这是过度的”你可能认为自己。然而,这恰恰相反。
示例服务+火力地堡
而不是推动从火力地堡的消息,让我们说你要通知用户只要修改你的数据库
第一个出现,早在创建databasereference在OnCreate中
mDatabaseLike=FirebaseDatabase.getInstance().getReference().child("Likes");
去 '的handleMessage方法',并添加以下
@Override
public void handleMessage(Message msg) {
mDatabaseLike.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
notifyUserOfDBupdate()
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//stopSelf(msg.arg1);
}
}
这里是notifyUserOfDBupdate方法以及如何通知用户
private void notifyUserOfDBupdate() {
//Intents
Intent Pdf_view = new Intent(this, //class to throw the user when they hit on notification\\.class);
PendingIntent pdf_view = PendingIntent.getActivity(this, 0, Pdf_view, 0);
//Notification Manager
NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
//The note
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification noti = new NotificationCompat.Builder(getApplicationContext())
.setTicker("TickerTitle")
.setContentTitle("content title")
.setSound(soundUri)
.setContentText("content text")
.setContentIntent(pdf_view).getNotification();
//Execution
noti.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(0, noti);
}
现在你的真实的设备和模拟器上进行第二次上一次运行应用程序。一旦两者中的任何一个修改了您的Firebase数据库,另一方会立即通知。
修改HandleMessage方法中您喜欢的任何方法。这将是永恒的,除非你能赚钱。
最诚挚的问候
谢谢你你回答!我会试试看 – quanyi
你是什么意思“当应用程序死了”? –
最有可能你正在寻找这个:http://stackoverflow.com/questions/39504805/android-app-not-receiving-firebase-notification-when-app-is-stopped-from-multi-t –