1. 程式人生 > >【Android】Service通過廣播更新UI

【Android】Service通過廣播更新UI

定義一個activity,在activity中定義一個內部廣播接收器,並且動態註冊該廣播接收器:
package com.zzj.ui.serviceUpdateUIDemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

import com.zzj.ui.R;

public class MainActivity extends Activity {
	private TextView textView;
	public static final String ACTION_UPDATEUI = "action.updateUI";
	UpdateUIBroadcastReceiver broadcastReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.service_update_ui);
		textView = (TextView) findViewById(R.id.count_txt);

		// 動態註冊廣播
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_UPDATEUI);
		broadcastReceiver = new UpdateUIBroadcastReceiver();
		registerReceiver(broadcastReceiver, filter);

		// 啟動服務
		Intent intent = new Intent(this, ServiceUpdateUI.class);
		startService(intent);
	}

	/**
	 * 定義廣播接收器(內部類)
	 * 
	 * @author lenovo
	 * 
	 */
	private class UpdateUIBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			textView.setText(String.valueOf(intent.getExtras().getInt("count")));
		}

	}

	@Override
	protected void onDestroy() {
		System.out.println("onDestroy");
		super.onDestroy();
		// 登出廣播
		unregisterReceiver(broadcastReceiver);
	}
}

activity佈局檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="當前人數:" />

    <TextView
        android:id="@+id/count_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
定義一個後臺service,該service定時傳送廣播:
package com.zzj.ui.serviceUpdateUIDemo;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class ServiceUpdateUI extends Service {
	private Timer timer;
	private TimerTask task;
	private int count;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

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

		final Intent intent = new Intent();
		intent.setAction(MainActivity.ACTION_UPDATEUI);

		timer = new Timer();
		task = new TimerTask() {

			@Override
			public void run() {
				intent.putExtra("count", ++count);
				sendBroadcast(intent);
			}
		};
		timer.schedule(task, 1000, 1000);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		timer.cancel();
	}

}

介面效果:



即使Activity退出再啟動,仍然能通過廣播接收器得到當前人數。

相關推薦

AndroidService通過廣播更新UI

定義一個activity,在activity中定義一個內部廣播接收器,並且動態註冊該廣播接收器:package com.zzj.ui.serviceUpdateUIDemo; import andr

android音樂播放器之UI設計的點點滴滴

       學習Android有一個多月,看完了《第一行程式碼》以及mars老師的第一期視訊通過音樂播放器小專案加深對知識點的理解。從本文開始,將詳細的介紹簡單仿多米音樂播放器的實現,以及網路解析資料獲取百度音樂最新排行音樂以及下載功能。         功能介紹如下

AndroidAn activity without a UI must call finish() before onResume() complete

今天遇到這樣的一個bug,我的測試機是Android 7.0,經過追蹤得到一下關鍵出錯資訊: An activity without a UI must call finish() before onResume() completes 很明顯這是因為當

Android動態註冊廣播接收器

從本質來說,Android 系統的廣播機制是一種訊息訂閱/釋出機制,因此,使用這種訊息驅動模型的第一步便是訂閱訊息;而對 Android 應用程式來說,訂閱訊息其實就是註冊廣播接收器。     註冊的方法有兩種,一種是靜態註冊,一種是動態註冊。在 Android 的廣播機

androidService中新建TextView

top 結果 turn parse layout onstop xtend relative ret 在Activity中new TextView的時候,發現傳入的參數是Context,不是必須為Activity,就想:在Service中新建一個View的話能否正常使用?

Android一、Progress進度條實現的三種方式:主執行緒實現,Service載入,動態建立

前言 更新版本,上傳資料到服務端,都是需要進度顯示的,Android進度顯示兩種方式 ProgressDialog 和 ProgressBar 新版本中ProgressDialog不被推薦使用,所以專案採用ProgressBar 分為三種實現方式: 1、MainAct

AndroidAndroid Studio的使用(六)--如何更新Android Studio

一、前文 Android Studio系列文章,主要講解如何使用這個IDE,原文釋出與部落格園,請多多支援原作者。 二、原文 原文出處: 部落格園 原文作者: StephenHe 原文連結: https://www.cnblogs.com/begin1949/p/496660

Android解決Android Studio 中SDK manager無法更新的問題

不久前Google剛剛釋出了基於intellij平臺的Android Studio1.0正式版,經過了Google眾多大神兩年多的辛勤耕耘,反覆迭代更新,可以說Studio已經是一個功能強大且相當穩定的IDE了,程式碼補全功能秒殺Eclipse,但是唯一讓我感覺比較撓頭的就

Android判斷應用Application、Activity、Service是否處於活動狀態

通過ActivityManager我們可以獲得系統里正在執行的activities,包括程序(Process)等、應用程式/包、服務(Service)、任務(Task)資訊。 1、判斷應用App是

Android程式的安裝、解除安裝和更新詳解

安裝程式的方法: 通過Intent機制,調出系統安裝應用,重新安裝應用的話,會保留原應用的資料。 String fileName = Environment.getExternalStorageDirectory() +apkName; Uri uri

AndroidAndroid Camera實時資料採集及通過MediaCodec硬編碼編碼資料的流程

// video device. private Camera camera; private MediaCodec vencoder; private MediaCodecInfo vmci; private MediaCodec.BufferInfo vebi; private byte[] vbuff

Android開機自啟動Service

之前我們有篇關於介紹 Android 如何實現開機自啟動,不過都寫的是關於如何啟動 Activity,本篇文章將介紹如何啟動 Service。 Service 的啟動相比 Acitivty 而言較為繁瑣,其實都是通過別的類去呼叫被啟動類,只不過可能 Activity 大

AndroidServiceActivity和Service是否同一程序

如果Service沒有設定屬性android:process=”:remote” Service會和Activity是在同一個程序中的,而且都是主執行緒 如果Service設定屬性android:process=”:remote” 那麼就會建立新程序,這時

Android13.0 UI開發(四)——列表控件RecyclerView的橫向布局排列實現

andro 上海市 tro source 構造 類繼承 ima libs ted 1.0 新建項目,由於ListView的局限性,RecyclerView是一種很好取代ListView的控件,可以靈活實現多種布局。 2.0 新建項目RecyclerviewTest,目錄如下

Android15.0 UI開發(六)——列表控件RecyclerView的網格布局排列實現

dir test pro 繼承 http 香港 bin too app 1.0 列表控件RecyclerView的網格布局排列實現,關鍵詞GridLayoutManager。 LinearLayoutManager 實現順序布局 GridLayoutManager 實現網格

android音樂播放器之service服務設計

       學習Android有一個多月,看完了《第一行程式碼》以及mars老師的第一期視訊通過音樂播放器小專案加深對知識點的理解。從本文開始,將詳細的介紹簡單仿多米音樂播放器的實現,以及網路解析資料獲取百度音樂最新排行音樂以及下載功能。         功能介紹如下

mysqlservice mysql start出錯,mysql啟動不了,解決mysql: unrecognized service錯誤

開機 init.d starting 設置 tin 執行 rest root lan service MySQL start出錯,mysql啟動不了,解決mysql: unrecognized service錯誤的方法如下: [[email protected]/

AndroidAndroid聊天機器人實現

小米 div bottom 曾經 圖靈 .9.png sdn http 歡迎界面 昨天看到一個Android視頻教程講圖靈機器人。那個API接口用起來還是挺方便的,就準備自己動手做一個了。另外自己還使用了高德地圖的API接口用於定位(曾經用過高德的接口,比X度方便) 大

AndroidEclipse自己主動編譯NDK/JNI的三種方法

comm tro mman gnu tex android項目 syn color ng- 【Android】Eclipse自己主動編譯NDK/JNI的三種方法 SkySeraph Sep. 18th 2014 Email:[email protec

androiduses-permission和permission具體解釋

.com 新的 -i weight bsp htm fin article 程序 1.<uses-permission>: 官方描寫敘述: If an application needs access to a feature prote