2016-11-29 65 views
0

我將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> 
+0

你是什麼意思「當應用程序死了」? –

+1

最有可能你正在尋找這個:http://stackoverflow.com/questions/39504805/android-app-not-receiving-firebase-notification-when-app-is-stopped-from-multi-t –

回答

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(); 
} 
} 

「這是過度的」你可能認爲自己。然而,這恰恰相反。

示例服務+火力地堡

而不是推動從火力地堡的消息,讓我們說你要通知用戶只要修改你的數據庫

第一個出現,早在創建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方法中您喜歡的任何方法。這將是永恆的,除非你能賺錢。

最誠摯的問候

+0

謝謝你你回答!我會試試看 – quanyi

相關問題