2015-09-09 24 views
0

我刷新活動時遇到了一些問題。我已將GCM偵聽器服務添加到我的應用程序中。它的監聽器服務應該讓我的活動在從GCM服務獲取「信息」時進行刷新。我不想建立通知。另外我不想用Timer()定期刷新我的活動。如何刷新GCM偵聽器服務的活動

有代碼:

MyGcmListenerService.java

public void onMessageReceived(String from, Bundle data) { 
    String message = data.getString("message"); 
    String theme = data.getString("theme"); 
    sendNotification(message,theme); 
} 

private void sendNotification(String message, String theme) { 
    Messages mess = new Messages(); 
    mess.message=message; 
    //what I have to do here to make my FirstLayout.java refresh? 
} 

FirstLayout.java

package com.notif.rasulbek.notifyme; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.widget.TextView; 
import java.util.Timer; 
import java.util.TimerTask; 



public class FirstLayout extends AppCompatActivity { 
    TextView mes; 
    protected void onCreate(Bundle savedInstanceState){ 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.first_layout); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     mes = (TextView)findViewById(R.id.firstMes); 

我想替換以下行:

 Timer autoUpdate = new Timer(); 
     autoUpdate.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       runOnUiThread(new Runnable() { 
        public void run() { 
         mes.setText(Messages.message); 
        } 
       }); 
      } 
     }, 0, 2000); 
     }//this approach doesn't like me :(

} 

同樣,我想從MyGcmListenerService.java發送一個像signal一樣的東西,刷新我的Activity。請任何人幫助我解決這個問題。事先感謝。

回答

2

最簡單的方法之一是使用LocalBroadcastManager發送廣播,然後在您的活動中使用BroadcastReceiver來收聽廣播。一旦聽衆「聽到」廣播,它可以觸發必要的活動更新。

您可以看到this示例應用程序,它在向GCM註冊時更新活動。

+0

謝謝,非常好的樣品。一切都很清晰 –

0

有兩種實現方法。其中一個與@Arthur提到的非常相似,我使用一組不同的API進一步擴展了這個概念。

  • 在GCMIntentService呼叫displayMessage其具有的代碼被接收GCM通知時廣播消息的方法onReceive
  • MainActivity'sonCreate註冊一個接收器來解決這個廣播消息。
  • 最後,BroadcastReceiver的onReceive將使用mHandleMessageReceiver調用更新I。

另一個更簡單的方法是直接用布爾變量更新onResume中的UI。剩下的idology與上面的策略相同,當收到GCM通知並收到它來更新UI時,您會聽廣播。

這裏是一個示例代碼:

protected void onResume() 
{ 
    super.onResume(); 

    update = true;; 
} 

protected void onPause() 
{ 
    super.onPause(); 

    update = false; 
} 

確保update布爾是靜態/全局。

+0

嗨AniV,非常感謝您的回答。但是,不幸的是它不工作。更具體的'mes.setText()'當它被'MyGcmListenerService'改變時不能得到'Message.message'變量 –