Android – 機房溫度監測簡單範例

分享一個簡單的 android 程式範例. 主要用 ImageView 顯示某 URL 的圖片. 這算是我第一隻比較有用處的 Android 程式


將手機連接到電腦. 啟用 debug 模式. 執行之後就可以將程式部屬到 android 手機了. 這比起蘋果的 Xcode 方便許多. iphone 系列手機沒破解的話就不能直接在設備上執行. 真是有點令人討厭.


執行 Temperature 程式結果

以下為 Android 各檔案的內容 :
AndroidManifest.xml



    
        
            
                
                
            
        

    
    


 

在這裡要注意是否加入 <uses-permission android:name=”android.permission.INTERNET”></uses-permission>. 如果沒加入的話.程式不能存取 internet. 這個我搞了好久才想起來要這樣弄.

下面檔案主要在描述 UI 部分
layout/main.xml






下列檔案在描述 strings
values/strings.xml



    R937
    Temperature

以下為程式主要的檔案 :
Temperature.java

package tw.liho.temperature;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;

public class Temperature extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ImageView imgView = (ImageView)findViewById(R.id.ImageViewR937);
        Drawable drawable = ImageOperations("http://somewhere/monitoring/temp.jpg");
        imgView.setImageDrawable(drawable);
    }
    
    private Drawable ImageOperations(String url) {
		try {
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is, "src name");
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
    
}

這樣算是勉強能用的程式. 這還需要在改進. 例如, 使用 Timer 定時讀溫度. 然後設定超過多少溫度顯示 Alert. 當然, 要弄個 Setting 介面讓使用者定義 interval & alert temperature. 之後, 在慢慢加入. 暫時先這樣!

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.