Android使用DigitalClock進行定時搶購

代碼如下:


package com.easaa.adapter;



import java.util.Calendar;


import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.AttributeSet;
import android.widget.DigitalClock;


public class MylockAdapter  extends DigitalClock{


/**
* 要實現定時。得重寫Android系統的時鐘
* @author 明邦良  
*/
Calendar  mCalendar;//定義時間對象

private final static String m12="h:mm aa";//12時間制
private final static String m24="k:mm";//24小時時間制
private final static String stopTime="0天00時00分00秒";
private FormatChangeObserver mFormatChangeObserver;

private Runnable mTicker;  //線程
private Handler mHandler;//消息機制

private long endTime;//結束時間
public static long distanceTime;//持續時間
private ClockListener mClockListener; //時鐘事件
private static boolean isFirst;//是否是第一次運行
private boolean mTickerStopped;//時間結束


private String mFormat;//字符串格式


public MylockAdapter(Context context){

super(context);//傳入上下文對象
initClock(context);//初始化時鐘
}

public MylockAdapter(Context context, AttributeSet attrs) {
super(context, attrs);//屬性
initClock(context);
}

private void initClock(Context context){

/**
* 首先判斷對象是否爲空。否則實例化
*/

if(mCalendar==null){

mCalendar = Calendar.getInstance();//實例化
}


mFormatChangeObserver = new FormatChangeObserver();

getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);

setFormat();
}



//將時間顯示在這裏面
@Override
protected void onAttachedToWindow() {


mTickerStopped = false;//此時時間沒有停止
super.onAttachedToWindow();
mHandler = new Handler();//使用異步消息


mTicker=new Runnable(){


@Override
public void run() {



if(mTickerStopped)
return ;
long currentTime=System.currentTimeMillis();

if(currentTime/1000==endTime/1000-5*60){
mClockListener.remainFiveMinutes();

}
distanceTime = endTime - currentTime;
distanceTime /= 1000;
if (distanceTime == 0) {
setText(stopTime);
onDetachedFromWindow();




} else if (distanceTime < 0) {
setText(stopTime);
onDetachedFromWindow();
} else {
setText(dealTime(distanceTime));
}
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}

/**
* 處理詳細的時間

* Spanned處理文本
*/

public static Spanned dealTime(long time) {
Spanned str;
StringBuffer returnString = new StringBuffer();
long day = time / (24 * 60 * 60);
long hours = (time % (24 * 60 * 60)) / (60 * 60);
long minutes = ((time % (24 * 60 * 60)) % (60 * 60)) / 60;
long second = ((time % (24 * 60 * 60)) % (60 * 60)) % 60;
String dayStr = String.valueOf(day);
String hoursStr = timeStrFormat(String.valueOf(hours));
String minutesStr = timeStrFormat(String.valueOf(minutes));
String secondStr = timeStrFormat(String.valueOf(second));




returnString.append(dayStr).append("天").append(hoursStr).append("小時")
.append(minutesStr).append("分鐘").append(secondStr).append("秒");
str = Html.fromHtml(returnString.toString());
if (day >= 10) {
((Spannable) str).setSpan(new AbsoluteSizeSpan(16), 2, 3,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
((Spannable) str).setSpan(new AbsoluteSizeSpan(16), 5, 7,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
((Spannable) str).setSpan(new AbsoluteSizeSpan(16), 9, 11,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
((Spannable) str).setSpan(new AbsoluteSizeSpan(16), 13, 14,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
((Spannable) str).setSpan(new AbsoluteSizeSpan(16), 1, 2,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
((Spannable) str).setSpan(new AbsoluteSizeSpan(16), 4, 6,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
((Spannable) str).setSpan(new AbsoluteSizeSpan(16), 8, 10,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
((Spannable) str).setSpan(new AbsoluteSizeSpan(16), 12, 13,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}




// return returnString.toString();
return str;
}


//處理時間格式
private static String timeStrFormat(String timeStr){

switch(timeStr.length()){

case 1:
timeStr="0"+timeStr;
break;
}
return timeStr;
}


@Override
protected void onDetachedFromWindow() {


super.onDetachedFromWindow();
mTickerStopped = true;//時間停止
}


//設置結束時間
public void setEndTime(long endTime) {
this.endTime = endTime;


}

//24小時時間處理
private boolean get24HourMode() {
return android.text.format.DateFormat.is24HourFormat(getContext());
}

//設置格式
private void setFormat() {
if (get24HourMode()) {
mFormat = m24;
} else {
mFormat = m12;
}
}



/**
* ContentObserver——內容觀察者,目的是觀察(捕捉)特定Uri引起的數據庫的變化,繼而做一些相應的處理
* 重寫方法
*/

private class FormatChangeObserver extends ContentObserver{


public FormatChangeObserver() {
super(new Handler());
}


@Override
public void onChange(boolean selfChange) {
setFormat();
}


}
public void setClockListener(ClockListener clockListener){
this.mClockListener = clockListener;
}
public interface ClockListener {

void timeEnd();
void remainFiveMinutes();
}

}


2.自定義適配器顯示圖片


package com.easaa.adapter;


import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.List;


import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;


import com.easaa.demo.R;
import com.easaa.vo.ProductItem;


/**
 * 自定義一個Adapter用來顯示數據
 * @author 明邦良
 *
 */


public class ProductAdapter  extends BaseAdapter{


private Context mContext;//上下文
private List<ProductItem> mItems;//用於存放ProductItem對象
private LayoutInflater  inflater;//佈局提取器
private BufferedInputStream  bufferis;//一個緩存
private AssetManager  assetManager;//爲了獲取Asset文件下的資源


public ProductAdapter(Context context, List<ProductItem> mItems) {
this.mContext = context;
this.mItems = mItems;

/**
* 初始化佈局提取器和AssetManager對象
*/
inflater=LayoutInflater.from(mContext);
assetManager=mContext.getAssets();
}


@Override
public int getCount() {
// TODO Auto-generated method stub
return mItems.size();
}


@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}


@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
/**
* 判斷convertView是否爲空,並提取佈局

*/
if(convertView==null){

convertView=inflater.inflate(R.layout.lock_time_sale_item, null);
}

ImageView imageView=(ImageView) convertView.findViewById(R.timeSale.image);

MylockAdapter  mylockAdapter=(MylockAdapter) convertView.findViewById(R.timeSale.remainTime);

try {
bufferis=new BufferedInputStream(assetManager.open(mItems.get(position).getImageUrl()));
imageView.setImageBitmap(BitmapFactory.decodeStream(bufferis));


} catch (IOException e) {
e.printStackTrace();
}

mylockAdapter.setEndTime(mItems.get(position).getRemainTime());

mylockAdapter.setClockListener(new MylockAdapter.ClockListener() {

@Override
public void timeEnd() {
// TODO Auto-generated method stub

}

@Override
public void remainFiveMinutes() {
// TODO Auto-generated method stub

}
} );



return convertView;
}


}


Activity活動:

package com.easaa.demo;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;


import com.easaa.adapter.ProductAdapter;
import com.easaa.vo.ProductItem;




/**
 *使用適配器 將數據顯示在View中
 * @author 明邦良
 *
 */




public class MainActivity extends Activity {


private ListView listView;
private ProductAdapter productAdapter;

Random  random=new Random();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lock_time_sale);
        
        
        initData();
    }
    
    
    private void initData(){
   
    listView=(ListView) findViewById(R.timeSale.listView);
    List<ProductItem> items=new ArrayList<ProductItem>();
    ProductItem item = null;
     
    for(int i=0;i<10;i++){
     
    item=new ProductItem();
    item.setId(System.currentTimeMillis()+30*1000*24*24);
    item.setImageUrl("images/"+getImages()[random.nextInt(7)]);
     
        item.setRemainTime(getRandomTime());
          items.add(item);
    }
    productAdapter=new ProductAdapter(this,items);
    listView.setAdapter(productAdapter);
    
    }
    
  //隨機取時間
private long getRandomTime(){

long curTime=System.currentTimeMillis();
long []t=new long[]{500,200,640,120,300,450,100,1000,1540,2500};//定義時間

return curTime+t[random.nextInt(9)]*1000;//在裏面隨機抽並*1000
}




//取圖片


private String [] getImages(){

String images[]=null;


try {
images=this.getApplicationContext().getAssets().list("images");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return images;


}


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

一個實體,用於裝數據

package com.easaa.vo;


public class ProductItem {


/**
* 一個實體
* 用於裝載圖片及時間
*/


private long id;
private String imageUrl;
private  long remainTime;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public long getRemainTime() {
return remainTime;
}
public void setRemainTime(long remainTime) {
this.remainTime = remainTime;
}
}

如圖:



源碼下載:http://download.csdn.net/detail/mxbhxx/5596357


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章