收到推送通知时更新视图

时间:2018-10-04 07:57:07

标签: android

当设备收到推送通知时,我想从打开的活动中更新视图。

收到推送通知后,将执行updateBalance函数, 查询一个mysql数据库并返回一个金额。

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private void updateBalance(String messageBody) {

        h1 = new Handler(Looper.getMainLooper()) {

            @Override
            public void handleMessage(Message msg) {
                bb = msg.getData();
                String str = bb.getString("result");
                Log.d(TAG,str);

                Message msg=handler.obtainMessage()

            }
       };
       t = new Thread(new MyRunnable(h1)); 
       t.start(); 

       try {
           t.sleep(1000);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
}

我还有另外一堂课

public class MyRunnable implements Runnable {
   private Handler h2;

   public MyRunnable(Handler h) {
     this.h2 = h;
  }

   @Override
   public void run() {

      String name = "w12";

      BalanceActivity NB = new BalanceActivity(name);
      Message m = Message.obtain(); 
      Bundle b = new Bundle();
      b.putString("result", "10");
      m.setData(b);
      h2.sendMessage(m);

   }
}

我有一个MainActivity,我想在退还金额后进行更新。我将如何与另一个HandlerRunnable一起使用。

public class MainActivity extends Activity {       
    TextView TV = (TextView) findViewById(package.name.R.id.Balance);
}

2 个答案:

答案 0 :(得分:0)

  • 尝试检查您的活动当前是否处于前台。如果是,则创建一种方法来更新视图。
public static boolean isServiceRunning(Context context) {

    Log.i(TAG, "Checking if service is running");

    ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);

    List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

    boolean isServiceFound = false;

    for (int i = 0; i < services.size(); i++) {

        if (Constants.PACKAGE.equals(services.get(i).service.getPackageName())){

            if (Constants.BACKGROUND_SERVICE_CLASS.equals(services.get(i).service.getClassName())){
                isServiceFound = true;
            }
        }
    }

    Log.i(TAG, "Service was" + (isServiceFound ? "" : " not") + " running");

    return isServiceFound;

}

答案 1 :(得分:0)

使用Broadcast Receivers。在活动中注册本地广播接收器。收到通知时广播数据。