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;
}
}

如图:


Android使用DigitalClock进行定时抢购_第1张图片

源码下载:http://download.csdn.net/detail/mxbhxx/5596357


你可能感兴趣的:(java,android,cache,ListView,imageview)