總網頁瀏覽量

顯示具有 Android-adroid 標籤的文章。 顯示所有文章
顯示具有 Android-adroid 標籤的文章。 顯示所有文章

2013年8月15日 星期四

Android(java) 使用cmd

Android中,透過APK直接使用cmd指令與device溝通

private Process process = null;

String[] cmd1 = { "/system/bin/sh", "-c", "echo hello > /data/temp.txt"};
process = Runtime.getRuntime().exec(cmd1);

String[] cmd2 = { "/system/bin/sh", "-c", "echo hello > /data/temp.txt"};

process = Runtime.getRuntime().exec(cmd2);

2013年1月28日 星期一

Android suspend resume code

使用service定時發出broadcast,當接收者收到intent後,即啟動resume,隔15sec後release wakelock,讓系統自動進入sleep狀態

MainActivity.java
package com.example.alarmmain;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
    Receive receive = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Intent intent = new Intent(MainActivity.this, MainService.class);
        startService(intent);
    }

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

    }

    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


MainService.java
package com.example.alarmmain;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MainService extends Service{
    private AlarmManager am;
    public void onCreate(){
        super.onCreate();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

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

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

        Intent it = new Intent();
        it.setAction("com.asus.alarmWake");
        
        PendingIntent sender = PendingIntent.getBroadcast(MainService.this, 0, it, 0);
        am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000, sender);
        Toast.makeText(getApplicationContext(), "Alarm Send",Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
}


Receive.java
package com.example.alarmmain;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.widget.Toast;

public class Receive extends BroadcastReceiver {
    private Handler handler = null;
    private PowerManager pm;
    private WakeLock wakeLock;
    
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "onReceive",Toast.LENGTH_LONG).show();
        
        handler = new Handler();
        pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "MainService");
        handler.postDelayed(wake, 0);

    }
    
    private Runnable wake = new Runnable() {
        public void run() {
            wakeLock.acquire();
            handler.postDelayed(sleep, 15000);
        }
    };
    private Runnable sleep = new Runnable() {
        public void run() {
            if (wakeLock != null && wakeLock.isHeld()) {
                wakeLock.release();
                wakeLock = null;
            }
        }
    };
}

2012年10月9日 星期二

Android 測試Android ProximityAlertReciever類別

測試Android ProximityAlertReciever類別
設定好監聽事件後,再更新座標,並接收警告或通知



Source code:

package com.example.addproximityalert;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String PROXIMITY_ALERT_ACTION_NAME = "com.test"; 
    private static final String TEST_MOCK_PROVIDER_NAME = "test_provider";
    private Button btnOut, btnIn;
    private TextView longitude_txt, latitude_txt;
    private LocationManager mLocationManager;
    private ProximityAlertReciever par;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        String locService = Context.LOCATION_SERVICE;   
        mLocationManager = (LocationManager) getSystemService(locService); 
        par = new ProximityAlertReciever();
        LocationProvider lp = mLocationManager.getProvider(TEST_MOCK_PROVIDER_NAME);
        if (lp != null) {
            mLocationManager.removeTestProvider(TEST_MOCK_PROVIDER_NAME);
        }
        addTestProvider(TEST_MOCK_PROVIDER_NAME);
        set();

    }
    public void findViews(){
        longitude_txt = (TextView)findViewById(R.id.longitude);
        latitude_txt = (TextView)findViewById(R.id.latitude);
        
        btnOut = (Button) findViewById(R.id.btn1); 
        btnOut.setOnClickListener(new OnClickListener() {  
            public void onClick(View arg0) {  
               updateLocation(30, 30);   
            }  
        });
        
        btnIn = (Button) findViewById(R.id.btn2); 
        btnIn.setOnClickListener(new OnClickListener() {  
            public void onClick(View arg0) {  
               updateLocation(0, 0);   
            }  
        });
    }
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    private void updateLocation(final double latitude, final double longitude){
        updateLocation(TEST_MOCK_PROVIDER_NAME, latitude, longitude);
    }
    
    private void updateLocation(final String providerName, final double latitude, final double longitude) {
        Location location = new Location(providerName);
        location.setLatitude(latitude);
        location.setLongitude(longitude);
        location.setTime(java.lang.System.currentTimeMillis());
        mLocationManager.setTestProviderLocation(providerName, location);
    }
    
    private void set(){
        double lat = 0;  
        double lng = 0;   
        float radius = 1000;    
        long expiration = -1;  
        Intent intent = new Intent(PROXIMITY_ALERT_ACTION_NAME);

        PendingIntent pi = PendingIntent.getBroadcast(this, -1, intent, PendingIntent.FLAG_ONE_SHOT);  
        mLocationManager.addProximityAlert(lat, lng, radius, expiration, pi);  
        IntentFilter filter = new IntentFilter(PROXIMITY_ALERT_ACTION_NAME);
        registerReceiver(new ProximityAlertReciever(), filter);
    }
    
    private void addTestProvider(final String providerName) {
        mLocationManager.addTestProvider(providerName, true, false, true, false, false, false, false, Criteria.POWER_MEDIUM, Criteria.ACCURACY_FINE);
        mLocationManager.setTestProviderEnabled(providerName, true);
    }
    
    
    class ProximityAlertReciever extends BroadcastReceiver {    
        @Override  
        public void onReceive(Context context, Intent intent) {    
            String key = LocationManager.KEY_PROXIMITY_ENTERING;  
            boolean isEnter = intent.getBooleanExtra(key, false);  
            if(isEnter){
                Toast.makeText(context, "以進入區域", Toast.LENGTH_LONG).show();  
            }
           
        }  
    } 
}

2012年5月22日 星期二

Android ADB

Slog.w(TAG, "");
Slog 要用: adb logcat -v time -b system
adb logcat > xxxx.log 

eclipse進行android開發中經常遇到logcat無任何資訊輸出
解決辦法:window-->show view-->選擇android下的devices,打開devices,點擊右邊的截屏圖片。等到出現截圖的時候,logcat就出來資訊了

找到一個可以把log保存下來的方法,這樣如果不接USB線時操作手機發生問題就能看見log
1. 連接USB 
2. 執行adb shell登到手機 
3. logcat -v time -f /sdcard/locker.log *:W & 

ADB 系統除錯與連結工具指令
$adb devices (顯示目前有多少個模擬器正在執行)

$adb -s (指定模擬器來操作)  
ex: adb -s emulator-5554 install email.apk

$adb install apkfile (安裝 APK 應用程式套件)  
ex: adb install email.apk

$adb uninstall package (移除 APK 應用程式套件)  
ex: adb uninstall com.android.email

$adb shell (進入 Android 系統指令列模式)

$dmesg (查看 Android Linux Kernel 運作訊息) ls - 顯示檔案目錄 cd - 進入目錄 rm - 刪除檔案 mv - 移動檔案 mkdir - 產生目錄 rmdir - 刪除目錄

$adb push (複製檔案到 SD )  
ex: adb push mp3 /sdcard

$adb pull . ( Android 系統下載檔案
ex: adb pull /data/app/com.android.email

$adb logcat (監控模擬器運作紀錄,以Ctrl + c 離開監控模式)

$adb bugreport (產生 adb 除錯報告)
ex: adb bugreport > 123.txt 輸出log到123.txt

$adb get-state (獲得 adb 伺服器運作狀態)

$adb start-server (啟動 adb 伺服器

$adb kill-server (關掉 adb 伺服器)

$adb forward tcp:6100 tcp:7100 (更改模擬器網路 TCP 通訊埠)

$adb shell ps -x (顯示 Android 上所有正在執行的行程)

$adb version (顯示 adb 版本

$adb help (顯示 adb 指令參數)

$adb remount 重新獲得一個設置,對檔案可讀可寫

2012年5月20日 星期日

eclipse 快捷鍵


快捷鍵
ctrl + D: 刪除行
shift + ctrl + F 縮排

搜尋,快速跳到下一個關鍵字, 
反白字串後按
ctrl + K
往下找下一個
ctrl + shift + K
往下找下一個
(
類似UltraEdit上的 F3, Ctrl+F3)

2012年4月22日 星期日

Android範例(2) GPS

package com.kent.gps;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class GpsTestActivity extends Activity implements LocationListener { 
private LocationManager mLocationManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);     
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, this);
TextView mTextView00 = (TextView)findViewById(R.id.TextView00);  
mTextView00.setText("GPS Information");
}

@Override 
public void onResume(){
if (mLocationManager != null) {

}               
super.onResume();
}

@Override    
protected void onPause() {        
if (mLocationManager != null) {            
mLocationManager.removeUpdates((LocationListener) this);        
}                
super.onPause();    
}  

public void onLocationChanged(Location location) {        
TextView mTextView01 = (TextView)findViewById(R.id.TextView01);
TextView mTextView02 = (TextView)findViewById(R.id.TextView02);
TextView mTextView03 = (TextView)findViewById(R.id.TextView03);
TextView mTextView04 = (TextView)findViewById(R.id.TextView04);
TextView mTextView05 = (TextView)findViewById(R.id.TextView05);
TextView mTextView06 = (TextView)findViewById(R.id.TextView06);
TextView mTextView07 = (TextView)findViewById(R.id.TextView07);
mTextView01.setText("Latitude:  " + String.valueOf(location.getLatitude()));
mTextView02.setText("Longitude:  " + String.valueOf(location.getLongitude()));
mTextView03.setText("Accuracy:  " + String.valueOf(location.getAccuracy()));
mTextView04.setText("Latitude:  " + String.valueOf(location.getAltitude()));
mTextView05.setText("Time:  " + String.valueOf(location.getTime()));
mTextView06.setText("Speed:  " + String.valueOf(location.getSpeed()));
mTextView07.setText("Bearing:  " + String.valueOf(location.getBearing()));   
}

public void onProviderDisabled(String provider) {

}
public void onProviderEnabled(String provider) {

}
public void onStatusChanged(String provider, int status, Bundle extras) {

}   
}

2012年4月8日 星期日

android 記錄

綁定監聽器:
listener1 = new onClickListener(){
  public void onClick(View v){
     TextView text_view = (TextView) findViewById(R.id.TextView01);
  }
}

setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.Button01);
button1.setOnClickListener(listener1);

另一種寫法
button.setOnClickListener(new View.OnClickListener(){
      public void onClick(View v){
      }
   });

對話框
1. Toast
Toast.makeText(this, "顯示字串", Toast.LENGTH_SHORT).show();

2.popupWindow
final PopupWindow popupWindow = new PopupWindow(PopupActivity.this);
popupWindow.setContentView(button);
popupWindow.setFocusable(true);
popupWindow.setWidth(200);
popupWindow.setHeight(100);
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
//按下對話視窗關閉PopupWindow視窗
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
popupWindow.dismiss();
}
});

3.dialog

final Dialog dialog = new Dialog(PopupActivity.this);
dialog.setTitle("這裡可以用來顯示Dialog信息!");
dialog.setContentView(button);
dialog.show();
//按下對話視窗上的按鈕來關閉Dialog視窗
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});

4.AlertDialog
Builder builder = new Builder(PopupActivity.this);
builder.setTitle("AlertDialog");
builder.setMessage("這裡可以用來顯示Alert信息,按[關閉]鍵會自動關閉");
builder.setPositiveButton("關閉", null);
builder.show();
break;

5.ProgressDialog
final ProgressDialog progressDialog = ProgressDialog.show(PopupActivity.this, "處理中...", "請等一會,處理完畢會自動結束...");
final Handler handler = new Handler();
//建立處理程式callback
final Runnable callback = new Runnable() {
public void run() {
     progressDialog.dismiss();
     }
};
//建立一個Thread來Run,當處理進度完畢時,執行callback程式來關閉ProgreeDialog視窗
Thread thread = new Thread() {
@Override
     public void run() {
     try {
           Thread.sleep(5000);
     } catch (InterruptedException e) {
           e.printStackTrace();
     }
           handler.post(callback);
     }
};
thread.start();



Intent採取動作或資料處理
Action: MAIN、VIEW、EDIT、CALL
資料處理: URI、MIME

畫面切換
Intent intent = new Intent(Main.this, Chatter.class);
startActivity(intent);
畫面切換後,等待回應訊息
Intent intent = new Intent(Main.this, Chatter.class);
startActivityForResult(intent, SHOW_EDITOR);

Intent之間資料傳遞
EditText editText = (EditText)findViewById(R.id.EditText01);
CharSequence text = editText.getText();
intent.putExtra("TEXT", text);

TEXT = "Sending Data"

Bundle extras = getIntent().getExtra();
if(extras != null){
   EditText editText = (EditText)findViewById(R.id.EditText01);
   editText.setText(extras.getcharSequence("TEXT"));
}

Spinner選單
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.actions, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner)findViewById(R.id.Spinner01);
spinner.setAdapter(adapter);

Spinner spinner = (Spinner)findViewById(R.id.Spinner01);
//設定Intent的動作(Action)和Uri
Intent intent = new Intent(spinner.getSelectedItem().toString(), Uri.parse(editText.getText().toString()));

try {
EditText editText = (EditText)findViewById(R.id.EditText01);
Spinner spinner = (Spinner)findViewById(R.id.Spinner01);
//設定Intent的動作(Action)和Uri
Intent intent = new Intent(spinner.getSelectedItem().toString(),Uri.parse(editText.getText().toString()));
//Start Activity,執行Browser
startActivity(intent);
} catch (Exception e) {
TextView textView = new TextView(Main.this);
textView.setText(e.getMessage());
Dialog dialog = new Dialog(Main.this);
dialog.setTitle(e.getClass().getName());
dialog.setContentView(textView);
dialog.show();
}

list選項放入陣列 設定選擇

final String[] layouts = {"A" , "B" , "C" , "D",};

//將4個範例選單名稱layouts安置在畫面佈局ListView01
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1, layouts);
ListView listView = (ListView)findViewById(R.id.ListView01);
listView.setAdapter(adapter);

//按下選單名稱指向相關的應用程式Class
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
Intent intent = new Intent(LayoutExample.this,    Class.forName(getClass().getPackage().getName()
         + "." + layouts[position] + "Activity"));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});


list表單
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1, list);
ListView listView = (ListView)findViewById(R.id.ListView01);
listView.setAdapter(adapter);

//按下選單名稱指向相關的應用程式Class
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Widgets.this, (Class<?>)activities[position * 2 + 1]);
startActivity(intent);
}
});


Menu選單()
<menu
   <item  android:id = "@+id/new_item01"
              android:title = "MENU_ITEM_1"/>
   <item  android:id = "@+id/new_item02"
              android:title = "MENU_ITEM_2"/> 
</menu>

掛載選單
public boolean onCreateOptionsMenu(Menu menu)
{
     MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.options_menu, menu);
     return true;
}

判斷選擇項目
publci boolean onOptionsItemSelected(MenuItem item)
{
     switch(item.getItemId())
     {
           case Menu_ITEM_ID1:
                   newHandle01();
                   return true;
           case Menu_ITEM_ID2:
                   newHandle02();
                   return true;   
     }
     return true;
}


分享優先資料 Shared Preferences
寫入:
public String SETTING_PREF = "SETTING_Pref"; //定義SharedPreferences內容檔名
public String SHARED_MSG1 = "Shared_Msg1"; //定義字串變數-1
public String SHARED_MSG2 = "Shared_Msg2";
SharedPreferences settings = getSharedPreferences(SETTING_PREF, 0);
int int2 = Integer.parseInt(mEditText02.getText().toString());

settings.edit()
           .putString(SHARED_MSG1, mEditText01.getText().toString())
           .putInt(SHARED_MSG2, int2)
           .commit();

讀取:

SharedPreferences settings = getSharedPreferences(SETTING_PREF, 0);
String msg1 = settings.getString(SHARED_MSG1, "");
mEditText01.setText(msg1);


int defint2 = 0;  //存取int型別資料
int msg2_int = settings.getInt(SHARED_MSG2, defint2);
String msg2 = String.valueOf(msg2_int);
mEditText02.setText(msg2);

























2012年4月7日 星期六

Android GPS framework


GpsLocation結構: 表示定位相關資訊
typedef struct {
    // set to sizeof(GpsLocation)
    size_t             size;
    //旗標位元
    uint16_t           flags;
    //緯度
    double          latitude;
    //經度
    double          longitude;
    //高度
    double          altitude;
    //速度
    float              speed;
    //方位
    float              bearing;
    //精準度
    float              accuracy;
    //時間戳記
    GpsUtcTime            timestamp;
} GpsLocation;


GpsStatusValue定義: 表示GPS晶片狀態
typedef uint16_t GpsStatusValue; //儲存GPS狀態 下面狀態的 0~4
#define GPS_STATUS_NONE             0
#define GPS_STATUS_SESSION_BEGIN    1//啟動導航
#define GPS_STATUS_SESSION_END      2//停止導航
#define GPS_STATUS_ENGINE_ON        3//未啟動導航
#define GPS_STATUS_ENGINE_OFF       4//電源關閉


GpsSvInfo結構: 描述衛星狀態
typedef struct {
    size_t  size;
    int       prn; //偽亂碼 即衛星編號
    float    snr;//衛星訊號
    float    elevation;//高度
    float   azimuth;//方位角
} GpsSvInfo;


GpsInterface結構: 連通上下層 為主要GPS的架構
typedef struct {
    size_t          size;
    int   (*init)( GpsCallbacks* callbacks );//初始化 並設定回調函數
    int   (*start)( void );//啟動導航
    int   (*stop)( void ); //關閉導航
    void  (*cleanup)( void );
    int   (*inject_time)(GpsUtcTime time, int64_t timeReference, int uncertainty);//插入目前時間
    int  (*inject_location)(double latitude, double longitude, float accuracy);//插入位置資訊
    void  (*delete_aiding_data)(GpsAidingData flags);//刪除輔助資訊
    int   (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence, uint32_t   
           min_interval, uint32_t preferred_accuracy, uint32_t preferred_time);//設定位置模式
    const void* (*get_extension)(const char* name);//取得擴充介面
} GpsInterface;





2012年3月27日 星期二

savedInstanceState Bundle 存值取值


savedInstanceState.putParcelable("名稱 A", 物件_A);
savedInstanceState.putInt("名稱 B", 物件_B);
物件_C.writeToBundle(savedInstanceState, "名稱 C");
物件_D.writeToBundle(savedInstanceState, "名稱 D");


super.onRestoreInstanceState(savedInstanceState);
物件_A = savedInstanceState.getParcelable("M名稱 A");
物件_B = savedInstanceState.getInt("名稱 B");
物件_C.readFromBundle(savedInstanceState, "名稱 C");
物件_D.readFromBundle(savedInstanceState, "名稱 D");

2012年3月24日 星期六

Broadcast 設計


Broadcast 廣播機制

//傳送廣播
public class SentBroadcas extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button b1 = (Button) findViewById(R.id.Button01);
//點擊Button後發送廣播
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent().setAction("android.intent.test")
sendBroadcast(intent);
}
});
}
}

//接收廣播
public class BroadcastReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.test")){
}
}
}


//在AndroidManifest.xml註冊
<receiver android:name="BroadcastReciever">
    <intent -filter="">
        <action android:name="android.intent.test">
        </action></intent>
</receiver>

----------------------------------------------------------------------------------------------




2012年3月5日 星期一

Android Handler


Handler
使用Handlerpost方法,將要執行的執行緒物件加到佇列中
handler.post(updateThread); 馬上加入到消息佇列內

創造一個Handler物件
Handler handler = new Handler();

將要執行的功能寫到執行緒物件的run方法中
Runnable updateThread = new Runnable(){
        @override
        public void run(){
        System.out.println(“UpdareThread”);
        handler.postDelayed(updateThread, 3000); 3000毫秒加一次
}
}
Thread移除
handler.removeCallbacks(updateThread);

ProgressBar加入到Handler
根據控制鍵ID取的代表控制鍵的物件,並為按鈕設置監聽器
Runnable updateThread = new Runnable(){
int i = 0 ;
        @Override
        public void run() {
            System.out.println("Begin Thread");
            i = i + 10 ;
                //取的一個消息物件,Message類別由Android操作系統提供
            Message msg = updateBarHandler.obtainMessage();
                //msg物件的arg1參數設置為I,用arg1arg2這兩個成員資料傳遞消息,優點為系統  性能消耗較少
            msg.arg1 = i ;
            try {
                        //設置當前執行緒睡眠1
                        Thread.sleep(1000);
            } catch (InterruptedException e) {
                        e.printStackTrace();
            }
                //msg物件加入到消息佇列中
                updateBarHandler.sendMessage(msg);
            if( i == 100){ //i值為100時,將執行緒物件從Handler中移除
                        updateBarHandler.removeCallbacks(updateThread);
            }
        }
};

//使用匿名內部類別來覆寫Handler中的handleMessage方法
Handler updateBarHandler = new Handler(){
@Override
public void handleMessage(Message msg) { //取得Message msg
bar.setProgress(msg.arg1);
updateBarHandler.post(updateThread);
}

sendMessage(msg); msg到佇列
handleMessage(Message msg) 從佇列取msg

Handler不是產生一個thread來執行而是直接使用runnable方法

Bundle 類似鍵值對


HandlerThread 實作了looper來處理消息佇列功能
這個類別由Android應用程序框架提供
HandlerThread  handlerThread = new HandlerThread(“handler_thread”);
handlerThread.start();
MyHandler myHandler = new MyHandler(handlerThread.getLooper());
Message msg = myHandler.obtainMessage(); //得到消息
Msg.sendToTarget(); //msg發送到目標物件,所謂的目標物件就是生成msg物件的handler物件

class MyHandler exteands Handler{
        public MyHandler(){
}
Public MyHandler(Looper looper){ //handler綁定到looper
        super(looper);
}
}

傳送資料與取得資料
msg.obj=”abc”;
String s = (String)msg.obj;

傳送大量資料利用Bundle
Bundle b = new Bundle();
b.putInt(“age”, 20);
b.putString(“name”, “Jhon”);
msg.setData(b);
msg.sendToTarget();

取資料
Bundle b = msg.getData();
Int ag = b.getInt(“age”);
String name = b.getString(“name”);

2012年1月29日 星期日

Android筆記

Google! Android 3(gasolin著)中的一些筆記

android:orientation 版面走向
fill_parent 填滿整個上層元件
wrap_content 包住內容, 隨文字欄位行數的不同而改變介面元件的高度

<EditText android:id="@+id/height" />
@ 提示XML解析器應該把後面的字串解析成識別符號
+  代表新建一個識別符號
id/  識別符號會被歸類在id類別下

string.xml
<string name="識別符號">文字敘述</string>
<string name="bmi_height">身高(cm)</string>

main.xml
<TextView android:text ="@string/bmi_height" />

重構模式:
好處為方便修改程式與整理,
 findViews();
 setListensers();

在android上設計對話框:
 private void openOptionDialog(){
    AlertDialog.Builder dialog = new AlertDialog.Builder(Main.this);
    dialog.setTitle("");
    dialog.setMessage("");
    dialog.show();

解決產生實體時所造成的記憶體消耗, 使用匿名方法, 並加入確認按鍵

    private void openOptionDialog(){
    new AlertDialog.Builder(Main.this)
    .setTitle(R.string.about_title)
    .setMessage(R.string.about_msg)
    .setPositiveButton("確認", new DialogInterface.OnClickListener(){
    public void onClick(DialogInterface dialoginterface, int i){
    }
    })
    .show();
    }

使用Toast函式對話框:
    private void openOptionDialog(){
    /*Toast popup = Toast.makeText(Main.this, "BMI 計算器", Toast.LENGTH_SHORT);
    popup.show();*/
    //匿名呼叫
    Toast.makeText(Main.this, "BMI 計算器", Toast.LENGTH_SHORT).show();
    }