如果使用Google Firebase Cloud Message

时间:2016-11-29 09:13:02

标签: android firebase firebase-cloud-messaging

我在自己的应用程序中集成了Google Firebase Cloud Message。当我的应用处于前台或后台时,它可以从Google服务器接收消息推送,但如果我的应用已停止,则无法从谷歌服务器接收任何消息推送。我想要的是,如果我的应用程序已经死了,它仍然可以从谷歌服务器收到一条消息。这是我的代码:

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>

1 个答案:

答案 0 :(得分:0)

您正在寻找的是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();
 }
}

“这令人沮丧”你可能会想到自己。然而,恰恰相反。

服务+ Firebase示例

不是从Firebase推送消息,而是假设您希望在您的某个数据库中发生修改时通知用户

首先,在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方法中修改您喜欢的任何方法。它将是永恒的,除非你让它变得可以杀死。

最亲切的问候