java - 更新始终位于顶部的 Android View

标签 java android service view

我想制作一个更新其内容并定期显示在窗口顶部的 View 。我找到了一个在窗口顶部创建 View 的示例( http://blog.daum.net/mailss/18 )。该 Activity 创建一个 UI,如果我触摸启动服务按钮, View 将显示其文本。但是当 View 创建后,它不会更新其内容。我尝试添加简单的代码来计算 View 更新的次数,但它不起作用。如何定期更改 View 的内容?我应该在服务中添加循环代码吗?我需要您的建议,谢谢。

1.AlwaysOnTopActivity.java

public class AlwaysOnTopActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    findViewById(R.id.start).setOnClickListener(this);  //start button  
    findViewById(R.id.end).setOnClickListener(this);    //stop button       
}

@Override
public void onClick(View v) {
    int view = v.getId();
    if(view == R.id.start)
        startService(new Intent(this, AlwaysOnTopService.class));   
    else
        stopService(new Intent(this, AlwaysOnTopService.class));    
}

}

2.AlwaysOnTopService.java

public class AlwaysOnTopService extends Service {
private TextView tv;                                            
@Override
public IBinder onBind(Intent arg0) { return null; }

@Override
public void onCreate() {
    super.onCreate();

    tv = new TextView(this);        //creating view
    tv.setText("This view is always on top.");
    tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    tv.setTextColor(Color.BLUE);


    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, //to always on top
        WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,//for touch event
        PixelFormat.TRANSLUCENT);                                                   

    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);    
    wm.addView(tv, params);//We must configure the permission in the manifest
}

@Override
public void onDestroy() {
    super.onDestroy();
    if(tv != null)      //terminating the view
    {
        ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(tv);
        tv = null;
    }
}

}

最佳答案

按照描述使用 LocalBroadcastManager here 。在 onReceive 方法中更新您的 UI

关于java - 更新始终位于顶部的 Android View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24504759/

相关文章:

android - 如何在线性布局中按下特定 TextView 时更改文本颜色

android - 有没有办法将 Google 表单集成到 Android 应用程序中?

android - flutter 应用在​​后台时调用 onMessage 方法

javascript - Angular2 服务呈现 HTML

java - 在Android上运行闹钟后台服务?

java - 在 Apache HttpClient 4.x 中多次读取响应主体

Java:要删除的正则表达式:%j 或 %f

java - 直接从Array中删除元素

C# 控制台/服务器访问网站

java - wsimport 绑定(bind) xsd :int to Integer instead of int