code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.besttone.search; import java.io.InputStream; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.amap.cn.apis.util.ConstantsAmap; import com.amap.mapapi.core.AMapException; import com.amap.mapapi.geocoder.Geocoder; import com.amap.mapapi.location.LocationManagerProxy; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.location.Address; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.os.Bundle; import android.os.Handler; import android.os.IInterface; import android.os.Message; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.WindowManager; import android.widget.Toast; public class Client { // ------------------------------------------------------------------------- private static Client instance; private static String screenSize = ""; private static String deviceId = ""; private static float dencyRate = 1.0f; private static DisplayMetrics display; private Handler mHd; private ThreadPoolExecutor mThreadPoorForLocal; private ThreadPoolExecutor mThreadPoorForDownload; private ThreadPoolExecutor mThreadPoorForRequest; private Context mContext; private final static String Tag = "Client"; private Geocoder coder; private String addressName; private LocationManagerProxy locationManager = null; public String area; public String cityName; private GetLocationAdressListener mLoactionDlistener = null; public boolean bChangeCity=true; public final String iflytech_APP_ID = "508eafc2"; public void setmLoactionDlistener(GetLocationAdressListener mLoactionDlistener) { this.mLoactionDlistener = mLoactionDlistener; } // ------------------------------------------------------------------------- private Client() { instance = this; mHd = new Handler(); mThreadPoorForLocal = new ThreadPoolExecutor(3, 6, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); mThreadPoorForRequest = new ThreadPoolExecutor(4, 8, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); mThreadPoorForDownload = new ThreadPoolExecutor(2, 5, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); } // ------------------------------------------------------------------------- public static void release() { try { instance.mThreadPoorForLocal.shutdownNow(); instance.mThreadPoorForRequest.shutdownNow(); instance.mThreadPoorForDownload.shutdownNow(); } catch (Exception e) { e.printStackTrace(); } instance = null; } // ------------------------------------------------------------------------- public static Client getInstance() { if (instance == null) { instance = new Client(); } return instance; } // ------------------------------------------------------------------------- public static Handler getHandler() { return getInstance().mHd; } // ------------------------------------------------------------------------- public static void postRunnable(Runnable r) { getInstance().mHd.post(r); } // ------------------------------------------------------------------------- public static ThreadPoolExecutor getThreadPoolForLocal() { return getInstance().mThreadPoorForLocal; } // ------------------------------------------------------------------------- public static ThreadPoolExecutor getThreadPoolForRequest() { Log.d(Tag, "request"); return getInstance().mThreadPoorForRequest; } // ------------------------------------------------------------------------- public static ThreadPoolExecutor getThreadPoolForDownload() { return getInstance().mThreadPoorForDownload; } // ------------------------------------------------------------------------- public static void initWithContext(Context context) { getInstance().mContext = context; display = new DisplayMetrics(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (null != wm) { wm.getDefaultDisplay().getMetrics(display); screenSize = display.widthPixels < display.heightPixels ? display.widthPixels + "x" + display.heightPixels : display.heightPixels + "x" + display.widthPixels; dencyRate = display.density / 1.5f; } TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (null != tm) { deviceId = tm.getDeviceId(); if (null == deviceId) deviceId = ""; } getInstance().locationManager = LocationManagerProxy.getInstance(Client.getContext()); } // ------------------------------------------------------------------------- public static Context getContext() { return getInstance().mContext; } // ------------------------------------------------------------------------- public static String getDeviceId() { return deviceId; } // ------------------------------------------------------------------------- public static String getScreenSize() { return screenSize; } // ------------------------------------------------------------------------- public static float getDencyParam() { return dencyRate; } // ------------------------------------------------------------------------- public static DisplayMetrics getDisplayMetrics() { return display; } // ------------------------------------------------------------------------- public static boolean decetNetworkOn() { try { ConnectivityManager cm = (ConnectivityManager) getInstance().mContext .getSystemService(Context.CONNECTIVITY_SERVICE); if (null != cm) { NetworkInfo wi = cm.getActiveNetworkInfo(); if (null != wi) return wi.isConnected(); } } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean decetNetworkOn(Context c) { ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); if (null != cm) { NetworkInfo info = cm.getActiveNetworkInfo(); if (null != info) return info.isConnected(); } return false; } public static Bundle getAppInfoBundle(Context context) { Bundle bundle = null; try { ApplicationInfo appInfo = ((Activity) context).getPackageManager().getApplicationInfo( ((Activity) context).getPackageName(), PackageManager.GET_META_DATA); if (appInfo != null) { bundle = appInfo.metaData; } PackageInfo pinfo = ((Activity) context).getPackageManager().getPackageInfo( ((Activity) context).getPackageName(), PackageManager.GET_CONFIGURATIONS); if (pinfo != null) { bundle.putString("versionName", pinfo.versionName); bundle.putInt("versionCode", pinfo.versionCode); } } catch (NameNotFoundException e) { e.printStackTrace(); } return bundle; } /** * 应用程序版本 * * @param context * @return */ public static String getVersion(Context context) { String uVersion = ""; Bundle bundle = getAppInfoBundle(context); if (bundle != null) { uVersion = bundle.getString("versionName"); } return uVersion; } // 高德定位 // 地理编码 public void getAddress(final double mLat, final double mLon) { this.getThreadPoolForRequest().execute(new Runnable() { public void run() { try { coder = new Geocoder(Client.getContext()); List<Address> address = coder.getFromLocation(mLat, mLon, 3); Log.d("adress", "" + address.size()); if (address != null && address.size() > 0) { Address addres = address.get(0); addressName = addres.getAdminArea() + addres.getSubLocality() + addres.getFeatureName() + "附近"; String ad = addres.getAdminArea(); String su = addres.getSubLocality(); if (ad.contains("市")) area = ad; else area = su; Log.d("adress", "" + addressName); Log.d("area", "" + area); mLoactionDlistener.onGetLocationAdress(); } } catch (AMapException e) { // TODO Auto-generated catch block Log.e("adress", ""+e.toString()); // mLoactionDlistener.onFialedGetLocationAdress(); } catch (Exception e) { // TODO Auto-generated catch block Log.e("adress", ""+e.toString()); // mLoactionDlistener.onFialedGetLocationAdress(); } } }); } public void tryGetAddress(final double mLat, final double mLon) { this.getThreadPoolForRequest().execute(new Runnable() { public void run() { try { coder = new Geocoder(Client.getContext()); List<Address> address = coder.getFromLocation(mLat, mLon, 3); Log.d("adress", "" + address.size()); if (address != null && address.size() > 0) { Address addres = address.get(0); addressName = addres.getAdminArea() + addres.getSubLocality() + addres.getFeatureName() + "附近"; Log.d("adress", "" + addressName); Log.d("area", "" + area); } } catch (AMapException e) { // TODO Auto-generated catch block Log.e("adress", ""+e.toString()); mLoactionDlistener.onFialedGetLocationAdress(); } catch (Exception e) { // TODO Auto-generated catch block Log.e("adress", ""+e.toString()); mLoactionDlistener.onFialedGetLocationAdress(); } } }); } public boolean enableMyLocation() { boolean result; result = true; try { Criteria cri = new Criteria(); cri.setAccuracy(Criteria.ACCURACY_COARSE); cri.setAltitudeRequired(false); cri.setBearingRequired(false); cri.setCostAllowed(false); String bestProvider = locationManager.getBestProvider(cri, true); Log.d("bestProvider",bestProvider); locationManager.requestLocationUpdates(bestProvider, 60000, 100, locationListener); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public void disableMyLocation() { try { locationManager.removeUpdates(locationListener); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } LocationListener locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub Toast.makeText(Client.getContext(), "定位失败,请检查网络和GPS", Toast.LENGTH_SHORT); } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub if (location != null) { Double geoLat = location.getLatitude(); Double geoLng = location.getLongitude(); String str = ("定位成功:(" + geoLat + "," + geoLng + ")"); Message msg = new Message(); msg.obj = str; Log.d("location",str); // getAddress(30.783298, 120.376826); // getAddress(38.844814, 105.706442);//阿拉善盟 // getAddress(52.335262, 124.711526);//大兴安岭地区 // getAddress(42.904823, 129.513228);//延边朝鲜族自治州 getAddress(geoLat,geoLng); } } }; public static interface GetLocationAdressListener { public void onGetLocationAdress(); public void onFialedGetLocationAdress(); } /** * 读取语法文件 * @return */ public static String readAbnfFile() { int len = 0; byte []buf = null; String grammar = ""; try { InputStream in = getContext().getAssets().open("gm_continuous_digit.abnf"); len = in.available(); buf = new byte[len]; in.read(buf, 0, len); grammar = new String(buf,"gbk"); } catch (Exception e1) { e1.printStackTrace(); } return grammar; } }
Java
package com.besttone.search; import android.app.Application; public class Ch114NewApplication extends Application { @Override public void onCreate() { //appContext = getApplicationContext(); super.onCreate(); Client.getInstance(); } }
Java
package com.besttone.search.sql; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class NativeDBHelper extends SQLiteOpenHelper { public static final String AREA_CODE = "AREA_CODE"; public static final int AREA_CODE_INDEX = 9; public static final String BUSINESS_FLAG = "BUSINESS_FLAG"; public static final int BUSINESS_FLAG_INDEX = 12; public static final int DATABASE_VERSION = 1; public static final String ENG_NAME = "ENG_NAME"; public static final int ENG_NAME_INDEX = 7; public static final String FIRST_PY = "FIRST_PY"; public static final int FIRST_PY_INDEX = 6; public static final String ID = "ID"; public static final int ID_INDEX = 0; public static final String IS_FREQUENT = "IS_FREQUENT"; public static final int IS_FREQUENT_INDEX = 10; public static final String NAME = "NAME"; public static final int NAME_INDEX = 4; public static final String PARENT_REGION = "PARENT_REGION"; public static final int PARENT_REGION_INDEX = 2; public static final String REGION_CODE = "REGION_CODE"; public static final int REGION_CODE_INDEX = 1; public static final String SHORT_NAME = "SHORT_NAME"; public static final int SHORT_NAME_INDEX = 5; public static final String SORT_VALUE = "SORT_VALUE"; public static final int SORT_VALUE_INDEX = 11; public static final String TEL_LENGTH = "TEL_LENGTH"; public static final int TEL_LENGTH_INDEX = 8; public static final String TYPE = "TYPE"; public static final String TYPE_CITY = "2"; public static final String TYPE_DISTRICT = "3"; public static final int TYPE_INDEX = 3; public static final String TYPE_PROVINCE = "1"; private static NativeDBHelper sInstance; private final String[] mColumns; private NativeDBHelper(Context paramContext) { super(paramContext, "native_database.db", null, 1); String[] arrayOfString = new String[8]; arrayOfString[0] = "ID"; arrayOfString[1] = "REGION_CODE"; arrayOfString[2] = "PARENT_REGION"; arrayOfString[3] = "TYPE"; arrayOfString[4] = "SHORT_NAME"; arrayOfString[5] = "FIRST_PY"; arrayOfString[6] = "AREA_CODE"; arrayOfString[7] = "BUSINESS_FLAG"; this.mColumns = arrayOfString; } public static NativeDBHelper getInstance(Context paramContext) { if (sInstance == null) sInstance = new NativeDBHelper(paramContext); return sInstance; } public void onCreate(SQLiteDatabase paramSQLiteDatabase) { } public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int paramInt1, int paramInt2) { } public Cursor select(String[] paramArrayOfString1, String paramString, String[] paramArrayOfString2) { return getReadableDatabase().query("PUB_LOCATION", paramArrayOfString1, paramString, paramArrayOfString2, null, null, null); } public Cursor selectAllCity() { String[] arrayOfString = new String[1]; arrayOfString[0] = "2"; return select(this.mColumns, "TYPE=?", arrayOfString); } public Cursor selectCodeByName(String paramString) { String[] arrayOfString = new String[1]; arrayOfString[0] = paramString; return select(this.mColumns, "SHORT_NAME=?", arrayOfString); } public Cursor selectDistrict(String paramString) { String[] arrayOfString = new String[2]; arrayOfString[0] = "3"; arrayOfString[1] = paramString; return select(this.mColumns, "TYPE=? AND PARENT_REGION like ?", arrayOfString); } public Cursor selectNameByCode(String paramString) { String[] arrayOfString = new String[1]; arrayOfString[0] = paramString; return select(this.mColumns, "REGION_CODE=?", arrayOfString); } }
Java
package com.besttone.search; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PoiResultData { public static List<Map<String, Object>> getData() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); return list; } }
Java
package com.besttone.search; import java.util.ArrayList; import com.besttone.adapter.LetterListAdapter; import com.besttone.search.CityListBaseActivity.AutoCityAdapter; import com.besttone.search.model.City; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.Constants; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; public abstract class CityListBaseActivity extends Activity implements AbsListView.OnScrollListener { private Context mContext; protected ArrayList<City> citylist = new ArrayList(); private Handler handler; protected ArrayAdapter<String> mAutoAdapter; protected EditText mAutoTextView; protected ArrayList<String> autoCitylist = new ArrayList<String>(); protected String[] autoArray; protected String[] mCityFirstLetter; private TextView mDialogText; protected int mHotCount = 0; protected Cursor mHotCursor; private String mLetter = ""; protected LetterListAdapter mListAdapter; protected ListView mListView; private RemoveWindow mRemoveWindow; private int mScroll; private boolean mShowing = false; private NativeDBHelper mDB; private WindowManager windowManager; protected AutoCityAdapter mAutoCityAdapter; protected ListView mAutoListView; private final TextWatcher textWatcher = new TextWatcher() { private int selectionEnd; private int selectionStart; private CharSequence temp; public void afterTextChanged(Editable paramEditable) { this.selectionStart = CityListBaseActivity.this.mAutoTextView .getSelectionStart(); this.selectionEnd = CityListBaseActivity.this.mAutoTextView .getSelectionEnd(); if (this.temp.length() > 25) { Toast.makeText(CityListBaseActivity.this, "temp 长度大于25", Toast.LENGTH_SHORT).show(); paramEditable.delete(this.selectionStart - (-25 + this.temp.length()), this.selectionEnd); int i = this.selectionStart; CityListBaseActivity.this.mAutoTextView.setText(paramEditable); CityListBaseActivity.this.mAutoTextView.setSelection(i); } //获取mAutoTextView结果 String str = temp.toString(); Cursor localCursor = null; String[] arrayParm = new String[2]; arrayParm[0] = "2"; arrayParm[1] = (str + "%"); autoCitylist = new ArrayList<String>(); String[] mColumns = {"FIRST_PY", "SHORT_NAME"}; // Log.d("selectCity", "search"); // Log.i("arrayParm[0]", "search"+arrayParm[0]); // Log.i("arrayParm[q]", "search"+arrayParm[1]); if(Constants.isAlphabet(str)) { localCursor =mDB.select(mColumns, "TYPE=? AND FIRST_PY like ?",arrayParm); } else { localCursor =mDB.select(mColumns, "TYPE=? AND SHORT_NAME like ?",arrayParm); } if (localCursor!=null && localCursor.getCount()>0) { localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { localCursor.close(); break; } autoCitylist.add(localCursor.getString(0) + "," + localCursor.getString(1)); // Log.i("result", localCursor.getString(0) + "," + localCursor.getString(1)); localCursor.moveToNext(); } } autoArray = autoCitylist.toArray(new String[autoCitylist.size()]); // mAutoAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_dropdown_item_1line, autoArray); // mAutoTextView.setAdapter(mAutoAdapter); // for(int i=0;i<autoArray.length;i++) // Log.i("autoArray[i]", "result"+autoArray[i]); if(str.length()>0&&autoArray.length>0) { mAutoListView.setVisibility(View.VISIBLE); } else { mAutoListView.setVisibility(View.GONE); } mAutoCityAdapter.notifyDataSetChanged(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { this.temp = s; } public void onTextChanged(CharSequence s, int start, int count, int after) { } }; private void init() { this.mDialogText = ((TextView) ((LayoutInflater) getSystemService("layout_inflater")).inflate(R.layout.select_city_position_dialog, null)); this.mDialogText.setVisibility(4); this.mRemoveWindow = new RemoveWindow(); this.handler = new Handler(); this.windowManager = getWindowManager(); setAdapter(); this.mListView.setOnScrollListener(this); this.mListView.setFastScrollEnabled(true); initAutoData(); mAutoTextView = (EditText)this.findViewById(R.id.change_city_auto_text); // this.mAutoTextView.setAdapter(this.mAutoAdapter); // this.mAutoTextView.setThreshold(1); this.mAutoTextView.addTextChangedListener(this.textWatcher); mDB = NativeDBHelper.getInstance(this); } private void initFirstLetter() { setFirstletter(); initDBHelper(); addLocationCityFirstLetter(); addHotCityFirstLetter(); this.mHotCount = this.citylist.size(); addCityFirstLetter(); } private void removeWindow() { if (!this.mShowing) ; while (true) { this.mShowing = false; this.mDialogText.setVisibility(4); return; } } public abstract void addCityFirstLetter(); public abstract void addHotCityFirstLetter(); public abstract void addLocationCityFirstLetter(); public abstract void initAutoData(); public abstract void initDBHelper(); protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); requestWindowFeature(1); setTheContentView(); mContext = this.getApplicationContext(); initFirstLetter(); init(); setListViewOnItemClickListener(); setAutoCompassTextViewOnItemClickListener(); // mAutoTextView.setAdapter(mAutoCityAdapter); } public void onScroll(AbsListView paramAbsListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { this.mScroll = (1 + this.mScroll); if (this.mScroll >= 2) { while (true) { int i = firstVisibleItem - 1 + visibleItemCount / 2; String str = ((City) this.mListView.getAdapter().getItem(i)) .getFirstLetter(); if (str == null) continue; this.mShowing = true; this.mDialogText.setVisibility(0); this.mDialogText.setText(str); this.mLetter = str; this.handler.removeCallbacks(this.mRemoveWindow); this.handler.postDelayed(this.mRemoveWindow, 3000L); return; } } } public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) { } protected void onStart() { super.onStart(); WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams( -1, -1, 2, 24, -3); this.windowManager.addView(this.mDialogText, localLayoutParams); this.mScroll = 0; } protected void onStop() { super.onStop(); try { this.mScroll = 0; this.windowManager.removeView(this.mDialogText); return; } catch (Exception localException) { while (true) localException.printStackTrace(); } } public abstract void setAdapter(); public abstract void setAutoCompassTextViewOnItemClickListener(); public abstract void setFirstletter(); public abstract void setListViewOnItemClickListener(); public abstract void setTheContentView(); final class RemoveWindow implements Runnable { private RemoveWindow() { } public void run() { CityListBaseActivity.this.removeWindow(); } } public class AutoCityAdapter extends BaseAdapter { private LayoutInflater mInflater; public AutoCityAdapter(Context context) { this.mInflater = LayoutInflater.from(context); autoArray = new String[1]; } public int getCount() { return autoArray.length; } public Object getItem(int position) { return autoArray[position]; } public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub convertView = mInflater.inflate(R.layout.auto_city_item, null); Log.i("adapt", "getDropDownView"); String searchRecord = autoArray[position]; ((TextView) convertView.findViewById(R.id.auto_city_info)).setText(searchRecord); return convertView; } } }
Java
package com.besttone.search.dialog; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.DecimalFormat; import java.text.NumberFormat; import com.besttone.search.Client; import com.besttone.search.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.StatFs; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class ProgressBarDialog extends Dialog { private ProgressBar mProgress; private TextView mProgressNumber; private TextView mProgressPercent; public static final int M = 1024 * 1024; public static final int K = 1024; private double dMax; private double dProgress; private int middle = K; private int prev = 0; private Handler mViewUpdateHandler; private int fileSize; private int downLoadFileSize; private static final NumberFormat nf = NumberFormat.getPercentInstance(); private static final DecimalFormat df = new DecimalFormat("###.##"); private static final int msg_init = 0; private static final int msg_update = 1; private static final int msg_complete = 2; private static final int msg_error = -1; private String mUrl; private File fileOut; private String downloadPath; public ProgressBarDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(getContext()); mViewUpdateHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (!Thread.currentThread().isInterrupted()) { // Log.i("msg what", String.valueOf(msg.what)); switch (msg.what) { case msg_init: // pbr.setMax(fileSize); mProgress.setMax(100); break; case msg_update: setDProgress((double) downLoadFileSize); break; case msg_complete: setTitle("文件下载完成"); break; case msg_error: String error = msg.getData().getString("更新失败"); setTitle(error); break; default: break; } } double precent = dProgress / dMax; if (prev != (int) (precent * 100)) { mProgress.setProgress((int) (precent * 100)); mProgressNumber.setText(df.format(dProgress) + "/" + df.format(dMax) + (middle == K ? "K" : "M")); mProgressPercent.setText(nf.format(precent)); prev = (int) (precent * 100); } } }; View view = inflater.inflate(R.layout.dialog_progress_bar, null); mProgress = (ProgressBar) view.findViewById(R.id.progress); mProgress.setMax(100); mProgressNumber = (TextView) view.findViewById(R.id.progress_number); mProgressPercent = (TextView) view.findViewById(R.id.progress_percent); setContentView(view); onProgressChanged(); super.onCreate(savedInstanceState); } private void onProgressChanged() { mViewUpdateHandler.sendEmptyMessage(0); } public double getDMax() { return dMax; } public void setDMax(double max) { if (max > M) { middle = M; } else { middle = K; } dMax = max / middle; } public double getDProgress() { return dProgress; } public void setDProgress(double progress) { dProgress = progress / middle; onProgressChanged(); } // String downloadPath = Environment.getExternalStorageDirectory().getPath() // + "/download_cache"; public void downLoadFile(final String httpUrl) { this.mUrl = httpUrl; File sdDir = null; boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在 if (sdCardExist) { sdDir = Environment.getExternalStorageDirectory();// 获取跟目录 if (getAvailableExternalMemorySize() < 50000000) { Toast.makeText(Client.getContext(), "存储空间不足", Toast.LENGTH_SHORT).show(); dismiss(); return; } } else { Toast.makeText(Client.getContext(), "SD卡不存在", Toast.LENGTH_SHORT).show(); dismiss(); return; } downloadPath = sdDir + "/114update"; Client.getThreadPoolForDownload().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub URL url = null; try { url = new URL(mUrl); String fileName = mUrl.substring(mUrl.lastIndexOf("/")); // String downloadPath = sdDir+"/114update"; File tmpFile = new File(downloadPath); if (!tmpFile.exists()) { tmpFile.mkdir(); } fileOut = new File(downloadPath + fileName); // URL url = new URL(appurl); // URL url = new URL(mUrl); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); InputStream in; in = con.getInputStream(); fileSize = con.getContentLength(); setDMax((double) fileSize); FileOutputStream out = new FileOutputStream(fileOut); byte[] bytes = new byte[1024]; downLoadFileSize = 0; setDProgress((double) downLoadFileSize); sendMsg(msg_init); int c; while ((c = in.read(bytes)) != -1) { out.write(bytes, 0, c); downLoadFileSize += c; sendMsg(msg_update);// 更新进度条 } in.close(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); sendMsg(msg_error);// error } sendMsg(msg_complete);// 下载完成 Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub dismiss(); installApk(fileOut); exitApp(); } }); } }); } private void sendMsg(int flag) { Message msg = new Message(); msg.what = flag; mViewUpdateHandler.sendMessage(msg); } private void installApk(File file) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(Intent.ACTION_VIEW); String type = "application/vnd.android.package-archive"; intent.setDataAndType(Uri.fromFile(file), type); Client.getContext().startActivity(intent); Log.e("success", "the end"); } // 彻底关闭程序 protected void exitApp() { Client.release(); System.exit(0); // 或者下面这种方式 // android.os.Process.killProcess(android.os.Process.myPid()); } public static long getAvailableExternalMemorySize() { if (externalMemoryAvailable()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } else { return msg_error; } } public static boolean externalMemoryAvailable() { return android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); } }
Java
package com.besttone.search; import java.io.File; import java.io.IOException; import java.util.List; import com.besttone.http.UpdateRequest; import com.besttone.http.UpdateRequest.UpdateListener; import com.besttone.search.Client.GetLocationAdressListener; import com.besttone.search.dialog.ProgressBarDialog; import com.besttone.search.model.City; import com.besttone.search.model.PhoneInfo; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.CellInfoManager; import com.besttone.search.util.CellLocationManager; import com.besttone.search.util.Constants; import com.besttone.search.util.LogUtils; import com.besttone.search.util.PhoneUtil; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.StringUtils; import com.besttone.search.util.WifiInfoManager; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; //import android.location.Address; //import android.location.Geocoder; import android.location.Address; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.amap.cn.apis.util.ConstantsAmap; import com.amap.mapapi.core.AMapException; import com.amap.mapapi.core.GeoPoint; import com.amap.mapapi.geocoder.Geocoder; import com.amap.mapapi.map.MapActivity; import com.amap.mapapi.map.MapView; public class SplashActivity extends Activity { private final int TIME_UP = 1; protected Context mContext; protected UpdateRequest r; private Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == TIME_UP) { Intent intent = new Intent(); intent.setClass(SplashActivity.this, MainActivity.class); startActivity(intent); overridePendingTransition(R.anim.splash_screen_fade, R.anim.splash_screen_hold); SplashActivity.this.finish(); } } }; public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.splash_screen_view); initApp(); initPhoneInfo(); Client.initWithContext(this); initCity(); // progDialog=new ProgressDialog(this); // // detectUpdate(); new Thread() { public void run() { try { Thread.sleep(500); } catch (Exception e) { } Message msg = new Message(); msg.what = TIME_UP; handler.sendMessage(msg); } }.start(); } private void initApp() { initNativeDB(); } private void initNativeDB() { SharedPreferences localSharedPreferences = getSharedPreferences( "NativeDB", 0); if (1 > localSharedPreferences.getInt("Version", 0)) { Constants.copyNativeDB(this, getResources().openRawResource(R.raw.native_database)); localSharedPreferences.edit().putInt("Version", 1).commit(); } Constants.copyNativeDB(this, getResources().openRawResource(R.raw.native_database)); localSharedPreferences.edit().putInt("Version", 1).commit(); } private boolean isUnSelectedCity() { if ((!SharedUtils.isFirstSelectedCityComplete(this.mContext)) || (StringUtils.isEmpty(SharedUtils .getCurrentCityName(this.mContext))) || (StringUtils.isEmpty(SharedUtils .getCurrentCityCode(this.mContext))) || (StringUtils.isEmpty(SharedUtils .getCurrentProvinceCode(this.mContext)))) { return true; } return false; } private void initCity() { // SharedUtils.setCurrentCity(Client.getContext(), SharedUtils.selectCity()); City localCity = new City(); localCity.setCityName("上海"); localCity.setCityCode("310000"); localCity.setSimplifyCode("31"); localCity.setCityId("75"); localCity.setProvinceCode("310000"); if(SharedUtils.getLastLocationCity()!=null) localCity=SharedUtils.getLastLocationCity(); SharedUtils.setCurrentCity(this, localCity); } public void initPhoneInfo() { TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); String imei = tm.getDeviceId(); //IMEI String provider = tm.getNetworkOperatorName(); //运营商 String imsi = tm.getSubscriberId(); //IMSI PhoneUtil util = new PhoneUtil(); PhoneInfo info = null; try { if(NetWorkStatus()) { //info = util.getPhoneNoByIMSI(imsi); } } catch (Exception e) { e.printStackTrace(); } if(info==null) info = new PhoneInfo(); info.setImei(imei); info.setImsi(imsi); info.setProvider(provider); SharedUtils.setCurrentPhoneInfo(this, info); } private boolean NetWorkStatus() { boolean netSataus = false; ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cwjManager.getActiveNetworkInfo(); if (cwjManager.getActiveNetworkInfo() != null) { netSataus = cwjManager.getActiveNetworkInfo().isAvailable(); } // if (netSataus) { // Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage("是否对网络进行设置?"); // b.setPositiveButton("是", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int whichButton) { // Intent mIntent = new Intent("/"); // ComponentName comp = new ComponentName("com.android.settings", // "com.android.settings.WirelessSettings"); // mIntent.setComponent(comp); // mIntent.setAction("android.intent.action.VIEW"); // startActivityForResult(mIntent,0); // 如果在设置完成后需要再次进行操作,可以重写操作代码,在这里不再重写 // } // }).setNeutralButton("否", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int whichButton) { // dialog.cancel(); // } // }).show(); // } return netSataus; } private void detectUpdate() { r = new UpdateRequest(); r.setListener(new UpdateListener() { @Override public void onUpdateNoNeed(String msg) { gotoLogin(); } public void onUpdateMust(final String msg, final String url) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(SplashActivity.this); b.setTitle("程序必须升级才能继续"); b.setMessage(msg+"\r\n"+url); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setPositiveButton("升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setCancelable(false); b.show(); } }); } public void onUpdateError(short code, Exception e) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(SplashActivity.this); b.setTitle("升级验证失败"); b.setMessage("请检查网络..."); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setCancelable(false); b.show(); } }); } public void onUpdateAvaiable(final String msg, final String url) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(SplashActivity.this); b.setTitle(R.string.update_title); b.setMessage(msg+"\r\n"+url); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoLogin(); } }); b.setPositiveButton("升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setCancelable(false); b.show(); } }); } }); if (Client.decetNetworkOn()) { // Log.d("check","on"); r.checkUpdate(); } else { // Log.d("check","off"); gotoLogin(); Toast.makeText(SplashActivity.this, "网络异常,没有可用网络", Toast.LENGTH_SHORT).show(); } } private void gotoLogin() { getLoacation(); } private void gotoUpdate(String url) { if (TextUtils.isEmpty(url)) { Toast.makeText(this, "升级的地址有误", Toast.LENGTH_SHORT).show(); finish(); System.gc(); return; } // url = url.toLowerCase(); if (url.startsWith("www")) { url = "http://" + url; } if (url.startsWith("http")) { try { // Uri u = Uri.parse(url); ProgressBarDialog pbd=new ProgressBarDialog(SplashActivity.this); pbd.setTitle("下载中"); pbd.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub gotoLogin(); } }); pbd.show(); pbd.downLoadFile(url); // Intent i = new Intent( Intent.ACTION_VIEW, u ); // startActivity( i ); // finish(); System.gc(); } catch(Exception e) { e.printStackTrace(); } } } private ProgressDialog progDialog = null; private Geocoder coder; private String addressName; private double mLat = 31.130704; private double mLon = 121.5334131; public void getLoacation(){ Client.getInstance().setmLoactionDlistener(new GetLocationAdressListener() { @Override public void onGetLocationAdress() { // TODO Auto-generated method stub Client.getInstance().disableMyLocation(); initCity(); new Thread() { public void run() { try { Thread.sleep(500); } catch (Exception e) { } Message msg = new Message(); msg.what = TIME_UP; handler.sendMessage(msg); } }.start(); } @Override public void onFialedGetLocationAdress() { // TODO Auto-generated method stub Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub showExitAlert(); } }); } }); Client.getInstance().enableMyLocation(); // Client.getInstance().tryGetAddress(30.783298, 120.376826); // CellInfoManager cellManager = new CellInfoManager(this) // // WifiInfoManager wifiManager = new WifiInfoManager(this); // // Log.d("location","init"); // // coder = new Geocoder(Client.getContext()); // // CellLocationManager locationManager = new CellLocationManager(this, cellManager, wifiManager) { // // @Override // // public void onLocationChanged() { // // Log.d("location",this.latitude() + "-" + this.longitude()); // // Client.getInstance().getAddress(this.latitude(),this.longitude()); // // this.stop(); // // } // // }; // // locationManager.start(); } private void showExitAlert() { new AlertDialog.Builder(this) .setTitle(R.string.prompt) .setMessage(R.string.quit_without_connection) .setCancelable(false) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { exitApp(); } }).show(); } //彻底关闭程序 protected void exitApp() { super.onDestroy(); Client.release(); System.exit(0); // 或者下面这种方式 // android.os.Process.killProcess(android.os.Process.myPid()); } }
Java
package com.besttone.search; import java.util.List; public interface ServerListener { void serverDataArrived(List list, boolean isEnd); }
Java
package com.besttone.search; import com.besttone.app.SuggestionProvider; import com.besttone.http.UpdateRequest; import com.besttone.http.UpdateRequest.UpdateListener; import com.besttone.search.Client.GetLocationAdressListener; import com.besttone.search.R.color; import com.besttone.search.dialog.ProgressBarDialog; import com.besttone.search.model.City; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.LogUtils; import com.besttone.search.util.SharedUtils; import com.besttone.widget.scroll.MyScrollLayout; import com.besttone.widget.scroll.OnViewChangeListener; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.provider.SearchRecentSuggestions; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private GridView grid; private DisplayMetrics localDisplayMetrics; private View mainView; private View swithViewContainer; private Button btn_city_search; private Button mSearchBtn; private SearchRecentSuggestions suggestions; private City lastLocationCity; private MyScrollLayout mScrollLayout; private ImageView[] mImageViews; private int mViewCount; private int mCurSel; private final boolean bMultiTag = false; public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); if(bMultiTag) { swithViewContainer = this.getLayoutInflater().inflate(R.layout.switch_view, null); setContentView(R.layout.switch_view); initChildView(); } else { mainView = this.getLayoutInflater().inflate(R.layout.main, null); setContentView(mainView); initMainView(); } detectUpdate(); } private void initMainView() { btn_city_search = (Button) mainView.findViewById(R.id.btn_city); btn_city_search.setOnClickListener(searchCityListner); String str = null; String cityName = (String) this.btn_city_search.getText(); SharedPreferences sharedPreferences = this.getSharedPreferences("Location_City_Data", 0); str=sharedPreferences.getString("Location_City", "上海"); Log.d("main", "new city:" + str); Log.d("main", "old city:" + cityName); this.btn_city_search.setText(str); mSearchBtn = ((Button)mainView.findViewById(R.id.start_search)); mSearchBtn.setOnClickListener(searchHistroyListner); localDisplayMetrics = getResources().getDisplayMetrics(); suggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); grid = (GridView)mainView.findViewById(R.id.my_grid); ListAdapter adapter = new GridAdapter(this); grid.setAdapter(adapter); grid.setOnItemClickListener(mOnClickListener); } //------------------------------ 多tag切换 --------------------------------- private void initChildView() { LinearLayout linearLayout = (LinearLayout) findViewById(R.id.llayout); mScrollLayout = (MyScrollLayout)findViewById(R.id.mScrollLayout); mainView = this.getLayoutInflater().inflate(R.layout.main, mScrollLayout); initMainView(); // mScrollLayout.addView(mainView); View child = new ImageView(this); mScrollLayout.addView(child); mViewCount = mScrollLayout.getChildCount(); mImageViews = new ImageView[mViewCount]; for (int i = 0; i < mViewCount; i++) { mImageViews[i] = (ImageView) linearLayout.getChildAt(i); mImageViews[i].setEnabled(true); mImageViews[i].setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub int pos = (Integer) (v.getTag()); setCurPoint(pos); mScrollLayout.snapToScreen(pos); } }); mImageViews[i].setTag(i); } mCurSel = 0; mImageViews[mCurSel].setEnabled(false); mScrollLayout.SetOnViewChangeListener(new OnViewChangeListener() { @Override public void OnViewChange(int view) { // TODO Auto-generated method stub setCurPoint(view); } }); } private void setCurPoint(int index) { if (index < 0 || index > mViewCount - 1 || mCurSel == index) { return; } mImageViews[mCurSel].setEnabled(true); // if(index!=mViewCount - 1) // mImageViews[index].setEnabled(true); // else mImageViews[index].setEnabled(false); mCurSel = index; } //----------------------------------------------------------------- private void updateLocaton() { Client.getInstance().setmLoactionDlistener(new GetLocationAdressListener() { @Override public void onGetLocationAdress() { // TODO Auto-generated method stub try { String curCityName=SharedUtils.getCurrentCityName(Client.getContext()); lastLocationCity=SharedUtils.selectCity(); String lastLocationCityName=lastLocationCity.getCityName(); if(!curCityName.equals("")&&!curCityName.equals(lastLocationCityName)) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if(Client.getInstance().bChangeCity) openAlertChangeCityDialog(); } }); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onFialedGetLocationAdress() { // TODO Auto-generated method stub Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Toast.makeText(Client.getContext(), "请检查网络连接!", Toast.LENGTH_SHORT); } }); } }); Client.getInstance().enableMyLocation(); // Thread t=new Thread(new Runnable() // { // // @Override // public void run() // { // // TODO Auto-generated method stub // do // { // try // { // Thread.sleep(60000); // } // catch (InterruptedException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // } // Client.getInstance().enableMyLocation(); // } // while (true); // } // }); // t.start(); } private void openAlertChangeCityDialog() { Client.getInstance().disableMyLocation(); String str=getString(R.string.change_city_by_location).replace("[]", SharedUtils.getLastLocationCity().getCityName()); new AlertDialog.Builder(MainActivity.this).setTitle(R.string.prompt) .setMessage(str) .setCancelable(false) .setPositiveButton(R.string.switch_text, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialoginterface, int i) { SharedUtils.setCurrentCity(Client.getContext(), lastLocationCity); btn_city_search.setText(lastLocationCity.getCityName()); // Client.getInstance().enableMyLocation(); } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialoginterface, int i) { Client.getInstance().bChangeCity = false; // Client.getInstance().enableMyLocation(); } }).show(); } private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, SearchActivity.class); startActivity(intent); } }; private Button.OnClickListener searchCityListner = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, SelectCityActivity.class); intent.putExtra("SelectCityName", btn_city_search.getText().toString()); startActivityForResult(intent, 100); } }; protected void onActivityResult(int requestCode, int resultCode, Intent data) { LogUtils.i("resultCode:" + resultCode + ", requestCode:" + requestCode); String str = null; String cityName = (String) this.btn_city_search.getText(); if (resultCode == RESULT_OK) { str = data.getStringExtra("cityName"); LogUtils.d(LogUtils.LOG_TAG, "new city:" + str); LogUtils.d(LogUtils.LOG_TAG, "old city:" + cityName); super.onActivityResult(requestCode, resultCode, data); this.btn_city_search.setText(str); } } private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position,long id) { TextView text = (TextView)v.findViewById(R.id.activity_name); String keyword = text.getText().toString(); Intent intent = new Intent(); if (keyword != null) { if ("更多".equals(keyword)) { intent.setClass(MainActivity.this, MoreKeywordActivity.class); startActivity(intent); } else { intent.setClass(MainActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("keyword", keyword); intent.putExtras(bundle); suggestions.saveRecentQuery(keyword, null); startActivity(intent); } } } }; public class GridAdapter extends BaseAdapter { private LayoutInflater inflater; public GridAdapter(Context context) { inflater = LayoutInflater.from(context); } public final int getCount() { return 6; } public final Object getItem(int paramInt) { return null; } public final long getItemId(int paramInt) { return paramInt; } public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) { paramView = inflater.inflate(R.layout.activity_label_item, null); TextView text = (TextView)paramView.findViewById(R.id.activity_name); text.setTextSize(15); text.setTextColor(color.text_color_grey); switch(paramInt) { case 0: { text.setText("KTV"); Drawable draw = getResources().getDrawable(R.drawable.ktv); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 1: { text.setText("宾馆"); Drawable draw = getResources().getDrawable(R.drawable.hotel); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 2: { text.setText("加油站"); Drawable draw = getResources().getDrawable(R.drawable.gas); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 3: { text.setText("川菜"); Drawable draw = getResources().getDrawable(R.drawable.chuan); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 4: { text.setText("快递"); Drawable draw = getResources().getDrawable(R.drawable.kuaidi); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 5: { text.setText("更多"); Drawable draw = getResources().getDrawable(R.drawable.more); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } // case 6: // { // text.setText("最近浏览"); // Drawable draw = getResources().getDrawable(R.drawable.home_button_history); // draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); // text.setCompoundDrawables(null, draw, null, null); // break; // } // // case 7: // { // text.setText("个人中心"); // Drawable draw = getResources().getDrawable(R.drawable.home_button_myzone); // draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); // text.setCompoundDrawables(null, draw, null, null); // break; // } // case 8: // { // text.setText("更多"); // Drawable draw = getResources().getDrawable(R.drawable.home_button_more); // draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); // text.setCompoundDrawables(null, draw, null, null); // break; // } } paramView.setMinimumHeight((int)(96.0F * localDisplayMetrics.density)); paramView.setMinimumWidth(((-12 + localDisplayMetrics.widthPixels) / 3)); return paramView; } } protected static final int MENU_ABOUT = Menu.FIRST; protected static final int MENU_Quit = Menu.FIRST+1; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_ABOUT, 0, " 关于 ..."); menu.add(0, MENU_Quit, 0, " 结束 "); return true; } public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_ABOUT: openOptionsDialog(); break; case MENU_Quit: showExitAlert(); break; } return true; } private void openOptionsDialog() { new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.about_title) .setMessage(R.string.about_msg) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialoginterface, int i) {} }) .setNegativeButton(R.string.homepage_label, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialoginterface, int i){ //go to url Uri uri = Uri.parse(getString(R.string.homepage_uri)); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }) .show(); } public boolean onKeyDown(int keyCode, KeyEvent event) { // 按下键盘上返回按钮 if(keyCode == KeyEvent.KEYCODE_BACK ){ showExitAlert(); return true; } else { return super.onKeyDown(keyCode, event); } } private void showExitAlert() { new AlertDialog.Builder(this) .setTitle(R.string.prompt) .setMessage(R.string.quit_desc) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {} }) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { exitApp(); } }).show(); } //彻底关闭程序 protected void exitApp() { super.onDestroy(); Client.release(); System.exit(0); // 或者下面这种方式 // android.os.Process.killProcess(android.os.Process.myPid()); } //检测更新 protected UpdateRequest r; private void detectUpdate() { r = new UpdateRequest(); r.setListener(new UpdateListener() { @Override public void onUpdateNoNeed(String msg) { gotoLogin(); } public void onUpdateMust(final String msg, final String url) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this); b.setTitle("程序必须升级才能继续"); b.setMessage(msg+"\r\n"+url); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setPositiveButton("升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setCancelable(false); b.show(); } }); } public void onUpdateError(short code, Exception e) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this); b.setTitle("升级验证失败"); b.setMessage("请检查网络..."); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setCancelable(false); b.show(); } }); } public void onUpdateAvaiable(final String msg, final String url) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this); b.setTitle(R.string.update_title); b.setMessage(msg+"\r\n"+url); b.setPositiveButton("现在升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setNegativeButton("以后再说", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoLogin(); } }); b.setCancelable(false); b.show(); } }); } }); if (Client.decetNetworkOn()) { // Log.d("check","on"); r.checkUpdate(); } else { // Log.d("check","off"); gotoLogin(); Toast.makeText(MainActivity.this, "网络异常,没有可用网络", Toast.LENGTH_SHORT).show(); } } private void gotoLogin() { updateLocaton(); // getLoacation(); } private void gotoUpdate(String url) { if (TextUtils.isEmpty(url)) { Toast.makeText(this, "升级的地址有误", Toast.LENGTH_SHORT).show(); finish(); System.gc(); return; } // url = url.toLowerCase(); if (url.startsWith("www")) { url = "http://" + url; } if (url.startsWith("http")) { try { // Uri u = Uri.parse(url); ProgressBarDialog pbd=new ProgressBarDialog(MainActivity.this); pbd.setTitle("下载中"); pbd.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub gotoLogin(); } }); pbd.show(); pbd.downLoadFile(url); // Intent i = new Intent( Intent.ACTION_VIEW, u ); // startActivity( i ); // finish(); System.gc(); } catch(Exception e) { e.printStackTrace(); } } } }
Java
package com.besttone.search; import java.util.ArrayList; import java.util.List; import com.besttone.widget.AlphabetBar; import android.R.integer; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.besttone.adapter.CityListAdapter; import com.besttone.search.model.City; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.LogUtils; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.SharedUtils.LocationCityListener; public class SelectCityActivity extends CityListBaseActivity { private ImageButton btn_back; private Context mContext; private NativeDBHelper mDB; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); //this.imm = ((InputMethodManager)getSystemService("input_method")); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); } private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private void selectComplete(City paramCity) { String simplifyCode = ""; if(paramCity!=null && paramCity.getCityCode()!=null) { simplifyCode = paramCity.getCityCode(); if(simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length()-2); } if(simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length()-2); } } paramCity.setSimplifyCode(simplifyCode); SharedUtils.setCurrentCity(this.mContext, paramCity); Intent localIntent = getIntent(); localIntent.putExtra("cityName", paramCity.getCityName()); setResult(RESULT_OK, localIntent); finish(); } @Override public void addCityFirstLetter() { if (this.mCityFirstLetter.length <= 0) return; String str = null; Cursor localCursor = null; for (int i = 1; i < this.mCityFirstLetter.length; i++) { str = this.mCityFirstLetter[i]; String[] arrayParm = new String[2]; arrayParm[0] = "2"; arrayParm[1] = (str + "%"); localCursor = this.mDB.select(null, "TYPE=? AND FIRST_PY like ?", arrayParm); if (localCursor != null) if (localCursor.moveToNext()) { City localCity1 = new City(); localCity1.setCityName("-1"); localCity1.setFirstLetter(str); this.citylist.add(localCity1); } while (true) { if (localCursor.isAfterLast()) { localCursor.close(); break; } City localCity2 = new City(); localCity2.setBusinessFlag(localCursor.getString(12)); localCity2.setCityCode(localCursor.getString(1)); localCity2.setCityId(localCursor.getString(0)); localCity2.setCityName(localCursor.getString(5)); localCity2.setFirstPy(localCursor.getString(6)); localCity2.setAreaCode(localCursor.getString(9)); localCity2.setProvinceCode(localCursor.getString(2)); localCity2.setFirstLetter(str); this.citylist.add(localCity2); localCursor.moveToNext(); } } } public void addHotCityFirstLetter() { if (this.mCityFirstLetter.length <= 0) return; String str; do { str = this.mCityFirstLetter[1]; } while (this.mHotCursor == null); if (this.mHotCursor.moveToNext()) { City localCity1 = new City(); localCity1.setCityName("-1"); localCity1.setFirstLetter(str); this.citylist.add(localCity1); } while (true) { if (this.mHotCursor.isAfterLast()) { this.mHotCursor.close(); break; } City localCity2 = new City(); localCity2.setBusinessFlag(this.mHotCursor.getString(12)); localCity2.setCityCode(this.mHotCursor.getString(1)); localCity2.setCityId(this.mHotCursor.getString(0)); localCity2.setCityName(this.mHotCursor.getString(5)); localCity2.setFirstPy(this.mHotCursor.getString(6)); localCity2.setAreaCode(this.mHotCursor.getString(9)); localCity2.setProvinceCode(this.mHotCursor.getString(2)); localCity2.setFirstLetter(str); this.citylist.add(localCity2); this.mHotCursor.moveToNext(); } } public void addLocationCityFirstLetter() { if (this.mCityFirstLetter.length <= 0) return; String str; str = this.mCityFirstLetter[0]; City localCity1 = new City(); localCity1.setCityName("-1"); localCity1.setFirstLetter(str); this.citylist.add(localCity1); City localCity2=null; localCity2=SharedUtils.getLastLocationCity(); // Log.d("initLocationCity","="+(localCity2==null)); // Log.d("initLocationCity","="+(localCity2.getCityName())); if(localCity2==null) { localCity2=new City(); localCity2.setCityName(getString(R.string.locating)); } localCity2.setFirstLetter(str); this.citylist.add(localCity2); } public void initAutoData() { ArrayList localArrayList = new ArrayList(); for (int i = this.mHotCount;; i++) { if (i >= this.citylist.size()) { this.mAutoAdapter = new ArrayAdapter(this, R.id.selected_item, R.id.city_info, localArrayList); return; } City localCity = (City) this.citylist.get(i); if ((localCity.getFirstPy() == null) || (localCity.getCityName() == null)) continue; localArrayList.add(localCity.getCityName()); localArrayList.add(localCity.getFirstPy() + "," + localCity.getCityName()); } } public void initDBHelper() { this.mAutoTextView = ((EditText) findViewById(R.id.change_city_auto_text)); this.mDB = NativeDBHelper.getInstance(this); this.mHotCursor = this.mDB.select(null, "IS_FREQUENT = '1' ORDER BY CAST(SORT_VALUE AS INTEGER)", null); } public void setAdapter() { this.mListView = ((ListView) findViewById(R.id.city_list)); this.mListAdapter = new CityListAdapter(this, this.citylist); this.mListView.setAdapter(this.mListAdapter); SharedUtils.setmLocationCityListener(new LocationCityListener() { @Override public void onLocationCityChange() { // TODO Auto-generated method stub Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub // Log.d("setAdapter","onLocationCityChange"); citylist.set(1, SharedUtils.getLastLocationCity()); mListAdapter.setmCitylist(citylist); mListAdapter.notifyDataSetChanged(); } }); } }); this.mAutoListView = ((ListView) findViewById(R.id.auto_city_list)); this.mAutoCityAdapter = new AutoCityAdapter(this); this.mAutoListView.setAdapter(this.mAutoCityAdapter); this.mAutoListView.setVisibility(View.GONE); } public void setAutoCompassTextViewOnItemClickListener() { mAutoListView.setOnItemClickListener(cityAutoTvOnClickListener); // this.mAutoTextView.setOnItemClickListener(cityAutoTvOnClickListener); } public void setFirstletter() { this.mCityFirstLetter = getResources().getStringArray( R.array.city_first_letter); } public void setListViewOnItemClickListener() { this.mListView.setOnItemClickListener(cityLvOnClickListener); } public void setTheContentView() { requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.select_city); } private AdapterView.OnItemClickListener cityLvOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ListView listView = (ListView) parent; City localCity = (City) listView.getItemAtPosition(position); if(localCity.getCityName().equals(getString(R.string.locating))) return; if (!"-1".equals(localCity.getCityName())) { // Toast.makeText(SelectCityActivity.this, // "你选择的城市是" + localCity.getCityName(), Toast.LENGTH_SHORT) // .show(); selectComplete(localCity); } } }; private AdapterView.OnItemClickListener cityAutoTvOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { String str1 = (String) mAutoCityAdapter.getItem(position); if (str1.contains(",")) { for (String str2 = str1.split(",")[1];; str2 = str1) { String[] arrayOfString = new String[2]; arrayOfString[0] = "2"; arrayOfString[1] = str2.trim(); Cursor localCursor = mDB.select(null, "TYPE=? AND SHORT_NAME=?", arrayOfString); if (localCursor.moveToFirst()) { City localCity = new City(); localCity.setAreaCode(localCursor.getString(9)); localCity.setCityCode(localCursor.getString(1)); localCity.setCityId(localCursor.getString(0)); localCity.setCityName(localCursor.getString(5)); localCity.setProvinceCode(localCursor.getString(2)); selectComplete(localCity); } return; } } } }; protected void onPause() { super.onPause(); //this.imm.hideSoftInputFromInputMethod(this.mAutoTextView.getWindowToken(), 0); } protected void onResume() { super.onResume(); //this.imm.hideSoftInputFromInputMethod(this.mAutoTextView.getWindowToken(), 0); } public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) { } }
Java
package com.besttone.search; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.SearchRecentSuggestions; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.iflytek.speech.*; import com.iflytek.ui.RecognizerDialog; import com.iflytek.ui.RecognizerDialogListener; import com.besttone.app.SuggestionProvider; import com.besttone.http.WebServiceHelper; import com.besttone.http.WebServiceHelper.WebServiceListener; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.StringUtils; import com.besttone.widget.EditSearchBar; import com.besttone.widget.EditSearchBar.OnKeywordChangeListner; import java.util.ArrayList; import java.util.List; public class SearchActivity extends Activity implements EditSearchBar.OnKeywordChangeListner{ private View view; private ImageButton btn_back; private ListView histroyListView; private EditText field_keyword; private Button mSearchBtn; private ImageButton mClearBtn; private EditSearchBar editSearchBar; private HistoryAdapter historyAdapter; private ArrayList<String> historyData = new ArrayList<String>(); private ArrayList<String> keywordList = new ArrayList<String>(); private ArrayList<String> keywordCountList = new ArrayList<String>(); private SearchRecentSuggestions suggestions; private Handler mhandler=new Handler(); private ImageButton mMicBtn; private RecognizerDialog recognizerDialog = null; private String grammar = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); view = this.getLayoutInflater().inflate(R.layout.search_histroy, null); setContentView(view); suggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); histroyListView = (ListView) findViewById(R.id.search_histroy); historyAdapter = new HistoryAdapter(this); histroyListView.setAdapter(historyAdapter); histroyListView.setOnItemClickListener(mOnClickListener); field_keyword = (EditText) findViewById(R.id.search_edit); mSearchBtn = (Button) findViewById(R.id.begin_search); mSearchBtn.setOnClickListener(searchListner); // mClearBtn = (ImageButton) findViewById(R.id.search_clear); // mClearBtn.setOnClickListener(clearListner); mMicBtn = (ImageButton) findViewById(R.id.btn_mic); mMicBtn.setOnClickListener(micListner); grammar = Client.readAbnfFile(); recognizerDialog = new RecognizerDialog(this,"appid="+Client.getInstance().iflytech_APP_ID); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); editSearchBar = (EditSearchBar)findViewById(R.id.search_bar); editSearchBar.setOnKeywordChangeListner(this); } private ImageButton.OnClickListener micListner = new ImageButton.OnClickListener() { public void onClick(View v) { EditText tmsg = (EditText)findViewById(R.id.search_edit); // tmsg.setText(grammar); recognizerDialog.setListener(mRecoListener); recognizerDialog.setEngine(null, "grammar_type=abnf", grammar); recognizerDialog.show(); } }; /** * 识别监听回调 */ private RecognizerDialogListener mRecoListener = new RecognizerDialogListener() { @Override public void onResults(ArrayList<RecognizerResult> results,boolean isLast) { String text = ""; for(int i = 0; i < results.size(); i++) { RecognizerResult result = results.get(i); text += result.text + " confidence=" + result.confidence + "\n"; } EditText tmsg = (EditText)findViewById(R.id.search_edit); tmsg.setText(text); tmsg.setSelection(tmsg.getText().length()); } @Override public void onEnd(SpeechError error) { } }; private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private ImageButton.OnClickListener clearListner = new ImageButton.OnClickListener() { public void onClick(View v) { mClearBtn.setVisibility(View.GONE); field_keyword.setHint(R.string.search_hint); } }; private Button.OnClickListener searchListner = new Button.OnClickListener() { public void onClick(View v) { if(NetWorkStatus()) { String keyword = field_keyword.getText().toString(); if(keyword!=null && !"".equals(keyword)) { String simplifyCode = SharedUtils.getCurrentSimplifyCode(SearchActivity.this); Log.v("simplifyCode", simplifyCode); Intent intent = new Intent(); intent.setClass(SearchActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("simplifyCode", simplifyCode); bundle.putString("keyword", keyword); intent.putExtras(bundle); suggestions.saveRecentQuery(keyword, null); finish(); startActivity(intent); } else { Toast.makeText(SearchActivity.this, "搜索关键词为空", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(SearchActivity.this, "网络异常,没有可用网络", Toast.LENGTH_SHORT).show(); } } }; private ListView.OnItemClickListener mOnClickListener = new ListView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ListView listView = (ListView) parent; String searchHistory = (String) listView.getItemAtPosition(position); if(searchHistory!=null && "清空搜索记录".equals(searchHistory)){ suggestions.clearHistory(); finish(); } else if(!"没有搜索记录".equals(searchHistory)){ Intent intent = new Intent(); intent.setClass(SearchActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("keyword", searchHistory); intent.putExtras(bundle); finish(); startActivity(intent); } } }; public class HistoryAdapter extends BaseAdapter { private LayoutInflater mInflater; public HistoryAdapter(Context context) { this.mInflater = LayoutInflater.from(context); historyData = getData(); } public int getCount() { return historyData.size(); } public Object getItem(int position) { return historyData.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(R.layout.search_history_item, null); String searchRecord = historyData.get(position); String searchRecordCount=""; String str= getString(R.string.associate_count); if(keywordCountList.size()>0) { searchRecordCount = keywordCountList.get(position); // .replace("+", ""); searchRecordCount=str.replace("[]", searchRecordCount); } else searchRecordCount=""; ((TextView) convertView.findViewById(R.id.history_text1)).setText(searchRecord); ((TextView) convertView.findViewById(R.id.history_text2)).setText(searchRecordCount); return convertView; } } public ArrayList<String> getData() { historyData = new ArrayList<String>(); String sortStr = " _id desc"; ContentResolver contentResolver = getContentResolver(); Uri quri = Uri.parse("content://" + SuggestionProvider.AUTHORITY + "/suggestions"); Cursor localCursor = contentResolver.query(quri, SuggestionProvider.COLUMNS, null, null, sortStr); if (localCursor!=null && localCursor.getCount()>0) { localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { localCursor.close(); break; } historyData.add(localCursor.getString(1)); localCursor.moveToNext(); } } return historyData; } private boolean NetWorkStatus() { boolean netSataus = false; ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cwjManager.getActiveNetworkInfo(); if (cwjManager.getActiveNetworkInfo() != null) { netSataus = cwjManager.getActiveNetworkInfo().isAvailable(); } return netSataus; } public void onKeywordChanged(final String paramString) { //获取联想关键词 final WebServiceHelper serviceHelper = new WebServiceHelper(); if(paramString!=null && !"".equals(paramString)){ Client.getThreadPoolForRequest().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub keywordList=serviceHelper.getAssociateList(paramString,SharedUtils.getCurrentCityCode(Client.getContext())); keywordCountList=serviceHelper.getResultAsociateCountList(); if(keywordList!=null && keywordList.size()>0){ historyData = keywordList; }else{ historyData = getData(); keywordCountList.removeAll(keywordCountList); } Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub // for(int i=0;i<historyData.size();i++) // { // Log.d("historyData",""+historyData.get(i)); // } historyAdapter.notifyDataSetChanged(); } }); } }); } else { historyData = getData(); keywordCountList.removeAll(keywordCountList); historyAdapter.notifyDataSetChanged(); } // ArrayList<String> keywordList = new ArrayList<String>(); // WebServiceHelper serviceHelper = new WebServiceHelper(); // if(paramString!=null && !"".equals(paramString)){ // keywordList = serviceHelper.getAssociateList(paramString); // } else { // historyData = getData(); // } // // if(keywordList!=null && keywordList.size()>0){ // historyData = keywordList; // }else{ // historyData = getData(); // } // historyAdapter.notifyDataSetChanged(); } }
Java
package com.besttone.search.util; import com.besttone.search.model.RequestInfo; public class XmlHelper { public static String getRequestXml(RequestInfo info) { StringBuilder sb = new StringBuilder(""); if(info!=null) { sb.append("<RequestInfo>"); sb.append("<region><![CDATA["+info.getRegion()+"]]></region>"); sb.append("<deviceid><![CDATA["+info.getDeviceid()+"]]></deviceid>"); sb.append("<imsi><![CDATA["+info.getImsi()+"]]></imsi>"); sb.append("<content><![CDATA["+info.getContent()+"]]></content>"); if(info.getPage()!=null){ sb.append("<Page><![CDATA["+info.getPage()+"]]></Page>"); } if(info.getPageSize()!=null){ sb.append("<PageSize><![CDATA["+info.getPageSize()+"]]></PageSize>"); } if(info.getMobile()!=null){ sb.append("<mobile><![CDATA["+info.getMobile()+"]]></mobile>"); } if(info.getMobguishu()!=null){ sb.append("<mobguishu><![CDATA["+info.getMobguishu()+"]]></mobguishu>"); } sb.append("</RequestInfo>"); } return sb.toString(); } }
Java
package com.besttone.search.util; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; import android.util.Log; public class CellInfoManager { private int asu; private int bid; private int cid; private boolean isCdma; private boolean isGsm; private int lac; private int lat; private final PhoneStateListener listener; private int lng; private int mcc; private int mnc; private int nid; private int sid; private TelephonyManager tel; private boolean valid; private Context context; public CellInfoManager(Context paramContext) { this.listener = new CellInfoListener(this); tel = (TelephonyManager) paramContext.getSystemService(Context.TELEPHONY_SERVICE); this.tel.listen(this.listener, PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_SIGNAL_STRENGTH); context = paramContext; } public static int dBm(int i) { int j; if (i >= 0 && i <= 31) j = i * 2 + -113; else j = 0; return j; } public int asu() { return this.asu; } public int bid() { if (!this.valid) update(); return this.bid; } public JSONObject cdmaInfo() { if (!isCdma()) { return null; } JSONObject jsonObject = new JSONObject(); try { jsonObject.put("bid", bid()); jsonObject.put("sid", sid()); jsonObject.put("nid", nid()); jsonObject.put("lat", lat()); jsonObject.put("lng", lng()); } catch (JSONException ex) { jsonObject = null; Log.e("CellInfoManager", ex.getMessage()); } return jsonObject; } public JSONArray cellTowers() { JSONArray jsonarray = new JSONArray(); int lat; int mcc; int mnc; int aryCell[] = dumpCells(); lat = lac(); mcc = mcc(); mnc = mnc(); if (aryCell == null || aryCell.length < 2) { aryCell = new int[2]; aryCell[0] = cid; aryCell[1] = -60; } for (int i = 0; i < aryCell.length; i += 2) { try { int j2 = dBm(i + 1); JSONObject jsonobject = new JSONObject(); jsonobject.put("cell_id", aryCell[i]); jsonobject.put("location_area_code", lat); jsonobject.put("mobile_country_code", mcc); jsonobject.put("mobile_network_code", mnc); jsonobject.put("signal_strength", j2); jsonobject.put("age", 0); jsonarray.put(jsonobject); } catch (Exception ex) { ex.printStackTrace(); Log.e("CellInfoManager", ex.getMessage()); } } if (isCdma()) jsonarray = new JSONArray(); return jsonarray; } public int cid() { if (!this.valid) update(); return this.cid; } public int[] dumpCells() { int[] aryCells; if (cid() == 0) { aryCells = new int[0]; return aryCells; } List<NeighboringCellInfo> lsCellInfo = this.tel.getNeighboringCellInfo(); if (lsCellInfo == null || lsCellInfo.size() == 0) { aryCells = new int[1]; int i = cid(); aryCells[0] = i; return aryCells; } int[] arrayOfInt1 = new int[lsCellInfo.size() * 2 + 2]; int j = 0 + 1; int k = cid(); arrayOfInt1[0] = k; int m = j + 1; int n = asu(); arrayOfInt1[j] = n; Iterator<NeighboringCellInfo> iter = lsCellInfo.iterator(); while (true) { if (!iter.hasNext()) { break; } NeighboringCellInfo localNeighboringCellInfo = (NeighboringCellInfo) iter.next(); int i2 = localNeighboringCellInfo.getCid(); if ((i2 <= 0) || (i2 == 65535)) continue; int i3 = m + 1; arrayOfInt1[m] = i2; m = i3 + 1; int i4 = localNeighboringCellInfo.getRssi(); arrayOfInt1[i3] = i4; } int[] arrayOfInt2 = new int[m]; System.arraycopy(arrayOfInt1, 0, arrayOfInt2, 0, m); aryCells = arrayOfInt2; return aryCells; } public JSONObject gsmInfo() { if (!isGsm()) { return null; } JSONObject localObject = null; while (true) { try { JSONObject localJSONObject1 = new JSONObject(); String str1 = this.tel.getNetworkOperatorName(); localJSONObject1.put("operator", str1); String str2 = this.tel.getNetworkOperator(); if ((str2.length() == 5) || (str2.length() == 6)) { String str3 = str2.substring(0, 3); String str4 = str2.substring(3, str2.length()); localJSONObject1.put("mcc", str3); localJSONObject1.put("mnc", str4); } localJSONObject1.put("lac", lac()); int[] arrayOfInt = dumpCells(); JSONArray localJSONArray1 = new JSONArray(); int k = 0; int m = arrayOfInt.length / 2; while (true) { if (k >= m) { localJSONObject1.put("cells", localJSONArray1); localObject = localJSONObject1; break; } int n = k * 2; int i1 = arrayOfInt[n]; int i2 = k * 2 + 1; int i3 = arrayOfInt[i2]; JSONObject localJSONObject7 = new JSONObject(); localJSONObject7.put("cid", i1); localJSONObject7.put("asu", i3); localJSONArray1.put(localJSONObject7); k += 1; } } catch (JSONException localJSONException) { localObject = null; } } } public boolean isCdma() { if (!this.valid) update(); return this.isCdma; } public boolean isGsm() { if (!this.valid) update(); return this.isGsm; } public int lac() { if (!this.valid) update(); return this.lac; } public int lat() { if (!this.valid) update(); return this.lat; } public int lng() { if (!this.valid) update(); return this.lng; } public int mcc() { if (!this.valid) update(); return this.mcc; } public int mnc() { if (!this.valid) update(); return this.mnc; } public int nid() { if (!this.valid) update(); return this.nid; } public float score() { float f1 = 0f; int[] aryCells = null; int i = 0; float f2 = 0f; if (isCdma()) { f2 = 1065353216; return f2; } if (isGsm()) { f1 = 0.0F; aryCells = dumpCells(); int j = aryCells.length; if (i >= j) f2 = f1; } if(i <=0 ) { return 1065353216; } int m = aryCells[i]; for (i = 0; i < m; i++) { if ((m < 0) || (m > 31)) f1 += 0.5F; else f1 += 1.0F; } f2 = f1; return f2; } public int sid() { if (!this.valid) update(); return this.sid; } public void update() { this.isGsm = false; this.isCdma = false; this.cid = 0; this.lac = 0; this.mcc = 0; this.mnc = 0; CellLocation cellLocation = this.tel.getCellLocation(); int nPhoneType = this.tel.getPhoneType(); if (nPhoneType == 1 && cellLocation instanceof GsmCellLocation) { this.isGsm = true; GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation; int nGSMCID = gsmCellLocation.getCid(); if (nGSMCID > 0) { if (nGSMCID != 65535) { this.cid = nGSMCID; this.lac = gsmCellLocation.getLac(); } } } try { String strNetworkOperator = this.tel.getNetworkOperator(); int nNetworkOperatorLength = strNetworkOperator.length(); if (nNetworkOperatorLength != 5) { if (nNetworkOperatorLength != 6) ; } else { this.mcc = Integer.parseInt(strNetworkOperator.substring(0, 3)); this.mnc = Integer.parseInt(strNetworkOperator.substring(3, nNetworkOperatorLength)); } if (this.tel.getPhoneType() == 2) { this.valid = true; Class<?> clsCellLocation = cellLocation.getClass(); Class<?>[] aryClass = new Class[0]; Method localMethod1 = clsCellLocation.getMethod("getBaseStationId", aryClass); Method localMethod2 = clsCellLocation.getMethod("getSystemId", aryClass); Method localMethod3 = clsCellLocation.getMethod("getNetworkId", aryClass); Object[] aryDummy = new Object[0]; this.bid = ((Integer) localMethod1.invoke(cellLocation, aryDummy)).intValue(); this.sid = ((Integer) localMethod2.invoke(cellLocation, aryDummy)).intValue(); this.nid = ((Integer) localMethod3.invoke(cellLocation, aryDummy)).intValue(); Method localMethod7 = clsCellLocation.getMethod("getBaseStationLatitude", aryClass); Method localMethod8 = clsCellLocation.getMethod("getBaseStationLongitude", aryClass); this.lat = ((Integer) localMethod7.invoke(cellLocation, aryDummy)).intValue(); this.lng = ((Integer) localMethod8.invoke(cellLocation, aryDummy)).intValue(); this.isCdma = true; } } catch (Exception ex) { Log.e("CellInfoManager", ex.getMessage()); } } class CellInfoListener extends PhoneStateListener { CellInfoListener(CellInfoManager manager) { } public void onCellLocationChanged(CellLocation paramCellLocation) { CellInfoManager.this.valid = false; } public void onSignalStrengthChanged(int paramInt) { CellInfoManager.this.asu = paramInt; } } }
Java
package com.besttone.search.util; public class LogUtils { public static final boolean IF_LOG = false; public static final String LOG_TAG = "zwj-code"; public static void d(String paramString) { } public static void d(String paramString1, String paramString2) { } public static void e(String paramString) { } public static void e(String paramString1, String paramString2) { } public static void e(String paramString, Throwable paramThrowable) { } public static void i(String paramString) { } public static void i(String paramString1, String paramString2) { } }
Java
package com.besttone.search.util; public class StringUtils { public static String getDateByTime(String paramString) { if ((isEmpty(paramString)) || (paramString.length() < 16)); while (true) { paramString = paramString.substring(0, 10); } } public static String getString(String paramString) { if ((paramString == null) || ("null".equals(paramString)) || ("NULL".equals(paramString))) paramString = ""; return paramString; } public static boolean isEmpty(String paramString) { if (paramString == null) return true; if (paramString!=null && paramString.trim().length() == 0) return true; return false; } public static String toZero(String paramString) { if (paramString == null) paramString = "0"; return paramString; } }
Java
package com.besttone.search.util; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import com.besttone.search.Client; import com.besttone.search.model.City; import com.besttone.search.model.PhoneInfo; import com.besttone.search.sql.NativeDBHelper; public class SharedUtils { public static final String Custom_Channel = "custom_channel"; public static final String Data_Selected_City = "Data_Selected_City"; public static final String First_Selected_City = "First_Selected_City"; public static final String Location_AreaCode = "Location_AreaCode"; public static final String Location_City = "Location_City"; public static final String Location_CityCode = "Location_CityCode"; public static final String Location_CityId = "Location_CityId"; public static final String Location_ProvinceCode = "Location_ProvinceCode"; public static final String NOTIFICATION_SET = "notification_set"; public static final String SHORT_CUT_INSTALLED = "short_cut_installed"; public static final String Switch_City_Notice = "Switch_City_Notice"; public static final String Total_Channel = "total_channel"; public static SharedPreferences mPreference; private static LocationCityListener mLocationCityListener=null; public static void setmLocationCityListener(LocationCityListener mLocationCityListener) { SharedUtils.mLocationCityListener = mLocationCityListener; } public interface LocationCityListener { public void onLocationCityChange(); } public static String getCurrentCityCode(Context paramContext) { return getPreference(paramContext).getString("Location_CityCode", ""); } public static String getCurrentCityId(Context paramContext) { return getPreference(paramContext).getString("Location_CityId", ""); } public static String getCurrentCityName(Context paramContext) { return getPreference(paramContext).getString("Location_City", ""); } public static String getCurrentProvinceCode(Context paramContext) { return getPreference(paramContext).getString("Location_ProvinceCode", ""); } public static String getCurrentAreaCode(Context paramContext) { return getPreference(paramContext).getString("Location_AreaCode", ""); } public static String getCurrentSimplifyCode(Context paramContext) { return getPreference(paramContext).getString("Location_SimplifyCode", ""); } public static long getNotificationHistory(Context paramContext, String paramString) { return getPreference(paramContext).getLong(paramString, 0L); } public static int getNotificationSet(Context paramContext) { return getPreference(paramContext).getInt("notification_set", 0); } public static SharedPreferences getPreference(Context paramContext) { if (mPreference == null) mPreference = PreferenceManager .getDefaultSharedPreferences(paramContext); return mPreference; } public static String getUseVersion(Context paramContext) { return getPreference(paramContext).getString("USE_VERSION", ""); } public static String getVersionChannelList(Context paramContext) { String str1 = getUseVersion(paramContext); String str2 = getPreference(paramContext).getString( "CHANNEL_VERSION_" + str1, ""); LogUtils.d("getCityChannelList: CHANNEL_VERSION_" + str1 + ", " + str2); return str2; } public static boolean hasShowHelp(Context paramContext) { return getPreference(paramContext).getBoolean("SHOW_HELP", false); } public static boolean isFirstSelectedCityComplete(Context paramContext) { return getPreference(paramContext).getBoolean("First_Selected_City", false); } public static boolean isShortCutInstalled(Context paramContext) { return getPreference(paramContext).getBoolean("short_cut_installed", false); } public static boolean isShowSwitchCityNotice(Context paramContext) { return getPreference(paramContext).getBoolean("Switch_City_Notice", true); } public static void setCurrentCity(Context paramContext, City paramCity) { SharedPreferences localSharePreferences = getPreference(paramContext); Editor localEditor = localSharePreferences.edit(); localEditor.putString("Location_City", paramCity.getCityName()); localEditor.putString("Location_CityCode", paramCity.getCityCode()); localEditor.putString("Location_CityId", paramCity.getCityId()); localEditor.putString("Location_ProvinceCode", paramCity.getProvinceCode()); localEditor.putString("Location_AreaCode", paramCity.getAreaCode()); localEditor.putString("Location_SimplifyCode", paramCity.getSimplifyCode()); LogUtils.d("setCurrentCity================"); LogUtils.d("cityCode:" + paramCity.getCityCode()); LogUtils.d("cityName:" + paramCity.getCityName()); LogUtils.d("areaCode:" + paramCity.getAreaCode()); LogUtils.d("SimplifyCode:" + paramCity.getSimplifyCode()); localEditor.commit(); } public static void setLocationCity(Context paramContext, City paramCity) { try { SharedPreferences localSharePreferences = Client.getContext().getSharedPreferences("Location_City_Data", 0); Editor localEditor = localSharePreferences.edit(); localEditor.putString("Location_City", paramCity.getCityName()); localEditor.putString("Location_CityCode", paramCity.getCityCode()); localEditor.putString("Location_CityId", paramCity.getCityId()); localEditor.putString("Location_ProvinceCode", paramCity.getProvinceCode()); localEditor.putString("Location_AreaCode", paramCity.getAreaCode()); localEditor.putString("Location_SimplifyCode", paramCity.getSimplifyCode()); LogUtils.d("setCurrentCity================"); LogUtils.d("cityCode:" + paramCity.getCityCode()); LogUtils.d("cityName:" + paramCity.getCityName()); LogUtils.d("areaCode:" + paramCity.getAreaCode()); LogUtils.d("SimplifyCode:" + paramCity.getSimplifyCode()); localEditor.commit(); if(mLocationCityListener!=null) mLocationCityListener.onLocationCityChange(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static City getLastLocationCity() { City resultCity = null; try { SharedPreferences localSharePreferences = Client.getContext().getSharedPreferences("Location_City_Data", 0); // Log.d("getPreferences",localSharePreferences.getString("Location_City", null)); if (localSharePreferences.getString("Location_City", null) != null) { resultCity = new City(); resultCity.setCityName(localSharePreferences.getString("Location_City", "")); resultCity.setCityCode(localSharePreferences.getString("Location_CityCode", "")); resultCity.setCityId(localSharePreferences.getString("Location_CityId", "")); resultCity.setProvinceCode(localSharePreferences.getString("Location_ProvinceCode", "")); resultCity.setAreaCode(localSharePreferences.getString("Location_AreaCode", "")); resultCity.setSimplifyCode(localSharePreferences.getString("Location_SimplifyCode", "")); // Log.v("getLoationCity",""+resultCity.getCityName()); } else { // Log.v("getLoationCity","null"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return resultCity; } public static City selectCity() { NativeDBHelper mDB = NativeDBHelper.getInstance(Client.getContext()); String[] arrayOfString = new String[1]; arrayOfString[0] = Client.getInstance().area.trim(); Cursor localCursor = mDB.select(null, "NAME = ?", arrayOfString); // Log.d("Cityname", "" + localCursor.moveToFirst()); if (localCursor.moveToFirst()) { if (localCursor.getString(3).equalsIgnoreCase("3")) { arrayOfString = new String[2]; arrayOfString[0] = "2"; arrayOfString[1] = localCursor.getString(2); localCursor = mDB.select(null, "TYPE = ? AND REGION_CODE = ?", arrayOfString); if (!localCursor.moveToFirst()) return null; } Log.d("Cityname", "" + localCursor.getString(5)); City localCity = new City(); localCity.setAreaCode(localCursor.getString(9)); localCity.setCityCode(localCursor.getString(1)); localCity.setCityId(localCursor.getString(0)); localCity.setCityName(localCursor.getString(5)); localCity.setProvinceCode(localCursor.getString(2)); SharedUtils.selectComplete(localCity); return localCity; } return null; } public static void selectComplete(City paramCity) { String simplifyCode = ""; if (paramCity != null && paramCity.getCityCode() != null) { simplifyCode = paramCity.getCityCode(); if (simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length() - 2); } if (simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length() - 2); } } paramCity.setSimplifyCode(simplifyCode); SharedUtils.setLocationCity( Client.getContext(), paramCity); } public static void setFirstSelectedCityComplete(Context paramContext) { getPreference(paramContext).edit() .putBoolean("First_Selected_City", true).commit(); } public static void setNotificationHistory(Context paramContext, String paramString, long paramLong) { if (!TextUtils.isEmpty(paramString)) { getPreference(paramContext).edit().putLong(paramString, paramLong) .commit(); LogUtils.d("SET:" + paramString + " ," + paramLong); } } public static void setNotificationSet(Context paramContext, int paramInt) { getPreference(paramContext).edit().putInt("notification_set", paramInt) .commit(); } public static void setShortCutInstalled(Context paramContext) { getPreference(paramContext).edit() .putBoolean("short_cut_installed", true).commit(); } public static void setShowHelp(Context paramContext) { getPreference(paramContext).edit().putBoolean("SHOW_HELP", true) .commit(); } public static void setSwitchCityNotice(Context paramContext, boolean paramBoolean) { getPreference(paramContext).edit() .putBoolean("Switch_City_Notice", paramBoolean).commit(); } public static void setUseVersion(Context paramContext, String paramString) { getPreference(paramContext).edit() .putString("USE_VERSION", paramString).commit(); LogUtils.d("setUseVersion: " + paramString); } public static void setVersionChannelList(Context paramContext, String paramString1, String paramString2) { getPreference(paramContext).edit() .putString("CHANNEL_VERSION_" + paramString1, paramString2) .commit(); LogUtils.d("setCityChannelList: CHANNEL_VERSION_" + paramString1 + ", " + paramString2); } public static boolean versionListExist(Context paramContext, String paramString) { if (getPreference(paramContext).contains( "CHANNEL_VERSION_" + paramString)) LogUtils.d("Version:" + paramString + "Exist!"); return true; } public static void setCurrentPhoneInfo(Context paramContext, PhoneInfo info) { SharedPreferences.Editor localEditor = getPreference(paramContext) .edit(); localEditor.putString("Phone_DeviceId", info.getImei()); localEditor.putString("Phone_Imsi", info.getImsi()); localEditor.putString("Phone_No", info.getPhoneNo()); localEditor.putString("Phone_Provider", info.getProvider()); localEditor.commit(); } public static String getCurrentPhoneDeviceId(Context paramContext) { return getPreference(paramContext).getString("Phone_DeviceId", ""); } public static String getCurrentPhoneImsi(Context paramContext) { return getPreference(paramContext).getString("Phone_Imsi", ""); } public static String getCurrentPhoneNo(Context paramContext) { return getPreference(paramContext).getString("Phone_No", ""); } public static String getCurrentPhoneProvider(Context paramContext) { return getPreference(paramContext).getString("Phone_Provider", ""); } }
Java
package com.besttone.search.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.os.Handler; import android.os.Message; import android.telephony.CellLocation; import android.util.Log; import android.widget.Toast; import com.google.android.photostream.UserTask; public abstract class CellLocationManager { public static int CHECK_INTERVAL = 15000; public static boolean ENABLE_WIFI = true; private static boolean IS_DEBUG = true; private static final int STATE_COLLECTING = 2; private static final int STATE_IDLE = 0; private static final int STATE_READY = 1; private static final int STATE_SENDING = 3; private static final int MESSAGE_INITIALIZE = 1; private static final int MESSAGE_COLLECTING_CELL = 2; private static final int MESSAGE_COLLECTING_WIFI = 5; private static final int MESSAGE_BEFORE_FINISH = 10; private int accuracy; private int bid; private CellInfoManager cellInfoManager; private Context context; private boolean disableWifiAfterScan; private int[] aryGsmCells; private double latitude; private double longitude; private MyLooper looper; private boolean paused; private final BroadcastReceiver receiver; private long startScanTimestamp; private int state; private Task task; private long timestamp; private boolean waiting4WifiEnable; private WifiInfoManager wifiManager; public CellLocationManager(Context context, CellInfoManager cellinfomanager, WifiInfoManager wifiinfomanager) { receiver = new CellLocationManagerBroadcastReceiver(); this.context = context.getApplicationContext(); cellInfoManager = cellinfomanager; wifiManager = wifiinfomanager; } private void debug(Object paramObject) { if (IS_DEBUG) { System.out.println(paramObject); String str = String.valueOf(paramObject); Toast.makeText(this.context, str, Toast.LENGTH_SHORT).show(); } } public int accuracy() { return this.accuracy; } public double latitude() { return this.latitude; } public double longitude() { return this.longitude; } public abstract void onLocationChanged(); public void pause() { if (state > 0 && !paused) { looper.removeMessages(MESSAGE_BEFORE_FINISH); paused = true; } } public void requestUpdate() { if (state != STATE_READY) { return; } boolean bStartScanSuccessful = false; CellLocation.requestLocationUpdate(); state = STATE_COLLECTING; looper.sendEmptyMessage(MESSAGE_INITIALIZE); if (wifiManager.wifiManager().isWifiEnabled()) { bStartScanSuccessful = wifiManager.wifiManager().startScan(); waiting4WifiEnable = false; } else { startScanTimestamp = System.currentTimeMillis(); if (!ENABLE_WIFI || !wifiManager.wifiManager().setWifiEnabled(true)) { int nDelay = 0; if (!bStartScanSuccessful) nDelay = 8000; looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI, nDelay); debug("CELL UPDATE"); } else { waiting4WifiEnable = true; } } } public void resume() { if (state > 0 && paused) { paused = false; looper.removeMessages(MESSAGE_BEFORE_FINISH); looper.sendEmptyMessage(MESSAGE_BEFORE_FINISH); } } public void start() { if (state <= STATE_IDLE) { Log.i("CellLocationManager", "Starting..."); context.registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); context.registerReceiver(receiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)); looper = new MyLooper(); state = STATE_READY; paused = false; waiting4WifiEnable = false; disableWifiAfterScan = false; debug("CELL LOCATION START"); requestUpdate(); } } public void stop() { if (state > STATE_IDLE) { context.unregisterReceiver(receiver); debug("CELL LOCATION STOP"); looper = null; state = STATE_IDLE; if (disableWifiAfterScan) { disableWifiAfterScan = false; wifiManager.wifiManager().setWifiEnabled(false); } } } public long timestamp() { return this.timestamp; } protected boolean isConnectedWithInternet() { ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conManager.getActiveNetworkInfo(); if (networkInfo != null) { return networkInfo.isAvailable(); } return false; } private class MyLooper extends Handler { private float fCellScore; private JSONArray objCellTowersJson; public void handleMessage(Message paramMessage) { if(CellLocationManager.this.looper != this) return; boolean flag = true; switch (paramMessage.what) { default: break; case MESSAGE_INITIALIZE: this.objCellTowersJson = null; this.fCellScore = 1.401298E-045F; case MESSAGE_COLLECTING_CELL: if (CellLocationManager.this.state != CellLocationManager.STATE_COLLECTING) break; JSONArray objCellTowers = CellLocationManager.this.cellInfoManager.cellTowers(); float fCellScore = CellLocationManager.this.cellInfoManager.score(); if (objCellTowers != null) { float fCurrentCellScore = this.fCellScore; if (fCellScore > fCurrentCellScore) { this.objCellTowersJson = objCellTowers; this.fCellScore = fCellScore; } } this.sendEmptyMessageDelayed(MESSAGE_COLLECTING_CELL, 600L); break; case MESSAGE_COLLECTING_WIFI: if (CellLocationManager.this.state != CellLocationManager.STATE_COLLECTING) break; this.removeMessages(MESSAGE_COLLECTING_CELL); this.removeMessages(MESSAGE_BEFORE_FINISH); // if (CellLocationManager.this.disableWifiAfterScan && CellLocationManager.this.wifiManager.wifiManager().setWifiEnabled(true)) // CellLocationManager.this.disableWifiAfterScan = false; CellLocationManager.this.state = CellLocationManager.STATE_SENDING; if (CellLocationManager.this.task != null) CellLocationManager.this.task.cancel(true); int[] aryCell = null; if (CellLocationManager.this.cellInfoManager.isGsm()) aryCell = CellLocationManager.this.cellInfoManager.dumpCells(); int nBid = CellLocationManager.this.cellInfoManager.bid(); CellLocationManager.this.task = new CellLocationManager.Task(aryCell, nBid); JSONArray[] aryJsonArray = new JSONArray[2]; aryJsonArray[0] = this.objCellTowersJson; aryJsonArray[1] = CellLocationManager.this.wifiManager.wifiTowers(); if(this.objCellTowersJson != null) Log.i("CellTownerJSON", this.objCellTowersJson.toString()); if(aryJsonArray[1] != null) Log.i("WIFITownerJSON", aryJsonArray[1].toString()); CellLocationManager.this.debug("Post json"); CellLocationManager.this.task.execute(aryJsonArray); break; case MESSAGE_BEFORE_FINISH: if (CellLocationManager.this.state != CellLocationManager.STATE_READY || CellLocationManager.this.paused) break; // L7 if (CellLocationManager.this.disableWifiAfterScan && CellLocationManager.this.wifiManager.wifiManager().setWifiEnabled(false)) CellLocationManager.this.disableWifiAfterScan = false; if (!CellLocationManager.this.cellInfoManager.isGsm()) { // L9 if (CellLocationManager.this.bid == CellLocationManager.this.cellInfoManager.bid()) { flag = true; } else { flag = false; } // L14 if (flag) { requestUpdate(); } else { this.sendEmptyMessageDelayed(10, CellLocationManager.CHECK_INTERVAL); } } else { // L8 if (CellLocationManager.this.aryGsmCells == null || CellLocationManager.this.aryGsmCells.length == 0) { // L10 flag = true; } else { int[] aryCells = CellLocationManager.this.cellInfoManager.dumpCells(); if (aryCells != null && aryCells.length != 0) { // L13 int nFirstCellId = CellLocationManager.this.aryGsmCells[0]; if (nFirstCellId == aryCells[0]) { // L16 int cellLength = CellLocationManager.this.aryGsmCells.length / 2; List<Integer> arraylist = new ArrayList<Integer>(cellLength); List<Integer> arraylist1 = new ArrayList<Integer>(aryCells.length / 2); int nIndex = 0; int nGSMCellLength = CellLocationManager.this.aryGsmCells.length; while (nIndex < nGSMCellLength) { // goto L18 arraylist.add(CellLocationManager.this.aryGsmCells[nIndex]); nIndex += 2; } // goto L17 nIndex = 0; while (nIndex < aryCells.length) { // goto L20 arraylist1.add(aryCells[nIndex]); nIndex += 2; } // goto L19 int nCounter = 0; for(Iterator<Integer> iterator = arraylist.iterator(); iterator.hasNext();) { // goto L22 if (arraylist1.contains(iterator.next())) nCounter++; } // goto L21 int k4 = arraylist.size() - nCounter; int l4 = arraylist1.size() - nCounter; if (k4 + l4 > nCounter) flag = true; else flag = false; if (flag) { StringBuilder stringbuilder = new StringBuilder(k4).append(" + "); stringbuilder.append(l4).append(" > "); stringbuilder.append(nCounter); CellLocationManager.this.debug(stringbuilder.toString()); } break; } else { // L15 flag = true; CellLocationManager.this.debug("PRIMARY CELL CHANGED"); // goto L14 if (flag) { requestUpdate(); } else { this.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH, CellLocationManager.CHECK_INTERVAL); } } } else { // L12 flag = true; // goto L14 if (flag) { requestUpdate(); } else { this.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH,CellLocationManager.CHECK_INTERVAL); } } } } } } } class Task extends UserTask<JSONArray, Void, Void> { int accuracy; int bid; int[] cells; double lat; double lng; long time; public Task(int[] aryCell, int bid) { this.time = System.currentTimeMillis(); this.cells = aryCell; this.bid = bid; } public Void doInBackground(JSONArray[] paramArrayOfJSONArray) { try { JSONObject jsonObject = new JSONObject(); jsonObject.put("version", "1.1.0"); jsonObject.put("host", "maps.google.com"); jsonObject.put("address_language", "zh_CN"); jsonObject.put("request_address", true); jsonObject.put("radio_type", "gsm"); jsonObject.put("carrier", "HTC"); JSONArray cellJson = paramArrayOfJSONArray[0]; jsonObject.put("cell_towers", cellJson); JSONArray wifiJson = paramArrayOfJSONArray[1]; jsonObject.put("wifi_towers", wifiJson); DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(); HttpPost localHttpPost = new HttpPost("http://www.google.com/loc/json"); String strJson = jsonObject.toString(); StringEntity objJsonEntity = new StringEntity(strJson); localHttpPost.setEntity(objJsonEntity); HttpResponse objResponse = localDefaultHttpClient.execute(localHttpPost); int nStateCode = objResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = objResponse.getEntity(); byte[] arrayOfByte = null; if (nStateCode / 100 == 2) arrayOfByte = EntityUtils.toByteArray(httpEntity); httpEntity.consumeContent(); String strResponse = new String(arrayOfByte, "UTF-8"); jsonObject = new JSONObject(strResponse); this.lat = jsonObject.getJSONObject("location").getDouble("latitude"); this.lng = jsonObject.getJSONObject("location").getDouble("longitude"); this.accuracy = jsonObject.getJSONObject("location").getInt("accuracy");; } catch (Exception localException) { return null; } return null; } public void onPostExecute(Void paramVoid) { if (CellLocationManager.this.state != CellLocationManager.STATE_SENDING || CellLocationManager.this.task != this) return; if ((this.lat != 0.0D) && (this.lng != 0.0D)) { CellLocationManager.this.timestamp = this.time; CellLocationManager.this.latitude = this.lat; CellLocationManager.this.longitude = this.lng; CellLocationManager.this.accuracy = this.accuracy; CellLocationManager.this.aryGsmCells = this.cells; CellLocationManager.this.bid = this.bid; StringBuilder sb = new StringBuilder("CELL LOCATION DONE: ("); sb.append(this.lat).append(",").append(this.lng).append(")"); CellLocationManager.this.debug(sb.toString()); CellLocationManager.this.state = STATE_READY; CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH, CellLocationManager.CHECK_INTERVAL); CellLocationManager.this.onLocationChanged(); } else { CellLocationManager.this.task = null; CellLocationManager.this.state = CellLocationManager.STATE_READY; CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH, 5000L); } } } private class CellLocationManagerBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent intent) { // access$0 state // 1 debug // access$2 loop // 3 startScanTimestamp // 4 disableWifiAfterScan // 5 wifimanager if (CellLocationManager.this.state != CellLocationManager.STATE_COLLECTING) return; String s = intent.getAction(); if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(s)) { // goto _L4; else goto _L3 // _L3: CellLocationManager.this.debug("WIFI SCAN COMPLETE"); CellLocationManager.this.looper.removeMessages(MESSAGE_COLLECTING_WIFI); long lInterval = System.currentTimeMillis() - CellLocationManager.this.startScanTimestamp; if (lInterval > 4000L) CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI, 4000L); else CellLocationManager.this.looper.sendEmptyMessage(MESSAGE_COLLECTING_WIFI); } else { // _L4: if (!CellLocationManager.this.waiting4WifiEnable) return; String s1 = intent.getAction(); if (!WifiManager.WIFI_STATE_CHANGED_ACTION.equals(s1)) return; int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 4); // _L5: if (wifiState == WifiManager.WIFI_STATE_ENABLING) { boolean flag2 = CellLocationManager.this.wifiManager.wifiManager().startScan(); // _L8: CellLocationManager.this.disableWifiAfterScan = true; CellLocationManager.this.paused = false; // int i = flag2 ? 1 : 0; // int nDelay = i != 0 ? 8000 : 0; // CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI, nDelay); CellLocationManager.this.debug("WIFI ENABLED"); } } } } }
Java
package com.besttone.search.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.logging.Logger; public class MD5Builder { public static Logger logger = Logger.getLogger("MD5Builder"); // 用来将字节转换成 16 进制表示的字符 public static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * 对文件全文生成MD5摘要 * * @param file * 要加密的文件 * @return MD5摘要码 */ public static String getMD5(File file) { FileInputStream fis = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); logger.info("MD5摘要长度:" + md.getDigestLength()); fis = new FileInputStream(file); byte[] buffer = new byte[2048]; int length = -1; logger.info("开始生成摘要"); long s = System.currentTimeMillis(); while ((length = fis.read(buffer)) != -1) { md.update(buffer, 0, length); } logger.info("摘要生成成功,总用时: " + (System.currentTimeMillis() - s) + "ms"); byte[] b = md.digest(); return byteToHexString(b); // 16位加密 // return buf.toString().substring(8, 24); } catch (Exception ex) { ex.printStackTrace(); return null; } finally { try { fis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * 对一段String生成MD5加密信息 * * @param message * 要加密的String * @return 生成的MD5信息 */ public static String getMD5(String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); logger.info("MD5摘要长度:" + md.getDigestLength()); byte[] b = md.digest(message.getBytes()); return byteToHexString(b); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * 把byte[]数组转换成十六进制字符串表示形式 * * @param tmp * 要转换的byte[] * @return 十六进制字符串表示形式 */ private static String byteToHexString(byte[] tmp) { String s; // 用字节表示就是 16 个字节 char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符, // 所以表示成 16 进制需要 32 个字符 int k = 0; // 表示转换结果中对应的字符位置 for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节 // 转换成 16 进制字符的转换 byte byte0 = tmp[i]; // 取第 i 个字节 str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, // >>> 为逻辑右移,将符号位一起右移 str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换 } s = new String(str); // 换后的结果转换为字符串 return s; } /** * * @param message * @return */ public static String getMD5Str(String source) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); byte[] byteArray = messageDigest.digest(source.getBytes("UTF-8")); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } } return md5StrBuff.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { String tmp = "sasdfafd"; System.out.println(getMD5(tmp)); System.out.println(getMD5Str(tmp)); } }
Java
package com.besttone.search.util; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.besttone.search.model.City; import com.besttone.search.model.District; import com.besttone.search.sql.NativeDBHelper; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.util.DisplayMetrics; public class Constants { public static String appKey = "50D033D17E0140F1919EF0508FC9A41E"; public static String appSecret = "35D31BE854EC4F2BAF9F9A61821C7460"; public static String apiName = "mobile"; public static String apiMethod = "getMobileByIMSI"; // public static String serverAddress = // "http://116.228.55.196:8060/open_api/"; public static String serverAddress = "http://open.118114.cn/api"; // public static String serverAddress = "http://116.228.55.106/api"; public static String abServerAddress = "http://openapi.aibang.com/search"; // public static String abAppKey = "a312b2321506db8a3a566370fdca7e29"; public static String abAppKey = "f41c8afccc586de03a99c86097e98ccb"; public static String SPACE = ""; public static int PAGE_SIZE = 10; // 测试地址 public static final String serviceURL = "http://116.228.55.13:8085/ch_trs_ws/ch_search"; public static String chName= "jichu_client"; public static String chKey = "123456"; //public static final String serviceURL = "http://116.228.55.103:9273/ch_trs_ws/ch_search"; // public static String chName = "jichu_client"; // public static String chKey = "j0c7c2t9"; //关键词联想 public static String associate_method = "searchCHkeyNum"; public static final String NATIVE_DATABASE_NAME = "native_database.db"; public static int mDeviceHeight; public static int mDeviceWidth = 0; static { mDeviceHeight = 0; } public static void copyNativeDB(Context paramContext, InputStream paramInputStream) { try { File localFile1 = new File("/data/data/" + paramContext.getPackageName() + "/databases/"); if (!localFile1.exists()) localFile1.mkdir(); String str = "/data/data/" + paramContext.getPackageName() + "/databases/" + "native_database.db"; File localFile2 = new File(str); if (localFile2.exists()) localFile2.delete(); FileOutputStream localFileOutputStream = new FileOutputStream(str); byte[] arrayOfByte = new byte[18000]; while (true) { int i = paramInputStream.read(arrayOfByte); if (i <= 0) { localFileOutputStream.close(); paramInputStream.close(); break; } localFileOutputStream.write(arrayOfByte, 0, i); } } catch (Exception localException) { } } public static City getCity(Context paramContext, String paramString) { City localCity = null; if ((paramString != null) && (!paramString.equals(""))) { NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); String[] arrayOfString = new String[2]; arrayOfString[0] = "2"; arrayOfString[1] = paramString.trim(); Cursor localCursor = localNativeDBHelper.select(null, "TYPE=? AND REGION_CODE=?", arrayOfString); if ((localCursor != null) && (localCursor.getCount() > 0) && (localCursor.moveToFirst())) { localCity = new City(); localCity.setAreaCode(localCursor.getString(9)); localCity.setCityCode(localCursor.getString(1)); localCity.setCityId(localCursor.getString(0)); localCity.setCityName(localCursor.getString(5)); localCity.setProvinceCode(localCursor.getString(2)); } if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } return localCity; } public static String getCityCode(Context paramContext, String paramString) { String str = ""; if ((paramString != null) && (!paramString.equals(""))) { NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); if (!paramString.startsWith("0")) paramString = "0" + paramString; String[] arrayOfString1 = new String[4]; arrayOfString1[0] = "ID"; arrayOfString1[1] = "REGION_CODE"; arrayOfString1[2] = "NAME"; arrayOfString1[3] = "AREA_CODE"; String[] arrayOfString2 = new String[2]; arrayOfString2[0] = "2"; arrayOfString2[1] = paramString; Cursor localCursor = localNativeDBHelper.select(arrayOfString1, "TYPE=? AND AREA_CODE=?", arrayOfString2); if ((localCursor != null) && (localCursor.getCount() > 0) && (localCursor.moveToFirst())) str = localCursor.getString(1); if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } return str; } public static String getCodeByName(Context paramContext, String paramString) { String str = null; NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); Cursor localCursor = localNativeDBHelper.selectCodeByName(paramString); if ((localCursor != null) && (localCursor.getCount() > 0)) localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } str = localCursor.getString(1); localCursor.moveToNext(); return str; } } public static String getSimplifyCodeByName(Context paramContext, String paramString) { String cityCode = getCodeByName(paramContext, paramString); return getSimplifyCode(cityCode); } public static int getDeviceWidth(Activity paramActivity) { if (mDeviceWidth == 0) { DisplayMetrics localDisplayMetrics = new DisplayMetrics(); paramActivity.getWindowManager().getDefaultDisplay() .getMetrics(localDisplayMetrics); mDeviceWidth = localDisplayMetrics.widthPixels; } return mDeviceWidth; } public static String[] getDistrictArray(Context paramContext, String paramString) { String[] arrayOfString = null; List localList = getDistrictList(paramContext, paramString); if ((localList != null) && (localList.size() > 0)) { arrayOfString = new String[1 + localList.size()]; arrayOfString[0] = "全部区域"; } for (int i = 0; ; i++) { if (i >= localList.size()) return arrayOfString; arrayOfString[(i + 1)] = ((District)localList.get(i)).getDistrictName(); } } public static List<District> getDistrictList(Context paramContext, String paramString) { ArrayList localArrayList = null; NativeDBHelper localNativeDBHelper = NativeDBHelper.getInstance(paramContext); paramString = paramString.substring(0,2) + "%"; Cursor localCursor = localNativeDBHelper.selectDistrict(paramString); if ((localCursor != null) && (localCursor.getCount() > 0)) { localArrayList = new ArrayList(); localCursor.moveToFirst(); } while (true) { if (localCursor.isAfterLast()) { if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); return localArrayList; } District localDistrict = new District(); localDistrict.setDistrictId(localCursor.getString(0)); localDistrict.setDistrictName(localCursor.getString(4)); localDistrict.setDistrictCode(localCursor.getString(1)); localDistrict.setCityCode(localCursor.getString(2)); String simplifyCode = localCursor.getString(2); if (simplifyCode != null && simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length() - 2); } if (simplifyCode != null && simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length() - 2); } localDistrict.setSimplifyCode(simplifyCode); localArrayList.add(localDistrict); localCursor.moveToNext(); } } public static JSONObject getJSONObject(HashMap<String, String> paramHashMap) { JSONObject localJSONObject = new JSONObject(); Iterator localIterator = paramHashMap.entrySet().iterator(); while (true) { if (!localIterator.hasNext()) return localJSONObject; Map.Entry localEntry = (Map.Entry) localIterator.next(); try { localJSONObject.put((String) localEntry.getKey(), localEntry.getValue()); } catch (JSONException localJSONException) { localJSONException.printStackTrace(); } } } public static String getNameByCode(Context paramContext, String paramString) { String str = null; NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); Cursor localCursor = localNativeDBHelper.selectNameByCode(paramString); if ((localCursor != null) && (localCursor.getCount() > 0)) localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); return str; } str = localCursor.getString(4); localCursor.moveToNext(); } } public static String getProvinceId(Context paramContext, String paramString) { String str = ""; if (!StringUtils.isEmpty(paramString)) { NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); String[] arrayOfString1 = new String[1]; arrayOfString1[0] = "ID"; String[] arrayOfString2 = new String[2]; arrayOfString2[0] = "1"; arrayOfString2[1] = paramString; Cursor localCursor = localNativeDBHelper.select(arrayOfString1, "TYPE=? AND REGION_CODE=?", arrayOfString2); if ((localCursor != null) && (localCursor.getCount() > 0) && (localCursor.moveToFirst())) str = localCursor.getString(0); if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } return str; } public static boolean isBusinessOpen(Context paramContext, String paramString) { boolean flag = false; if ((paramString != null) && (!paramString.equals(""))) { NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); String[] arrayOfString1 = new String[1]; arrayOfString1[0] = "BUSINESS_FLAG"; String[] arrayOfString2 = new String[1]; arrayOfString2[0] = paramString; Cursor localCursor = localNativeDBHelper.select(arrayOfString1, "REGION_CODE=?", arrayOfString2); if ((localCursor != null) && (localCursor.getCount() > 0) && (localCursor.moveToFirst())) { String str = localCursor.getString(0); if ((str != null) && (str.equals("1"))) flag = true; } if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } return flag; } public static String getSimplifyCode(String cityCode) { if(cityCode!=null) { if(cityCode.endsWith("00")) { cityCode = cityCode.substring(0, cityCode.length()-2); } if(cityCode.endsWith("00")) { cityCode = cityCode.substring(0, cityCode.length()-2); } } return cityCode; } public static boolean isAlphabet(String s) { if(s!=null) { return s.matches("^[a-zA-Z]*$"); } return false; } public static String getCity(String s){ String city = null; if(s!=null && s.trim().length()!=0) { String[] cityArray = s.split("\\|\\|"); int index = cityArray.length - 1; city = cityArray[index]; } return city; } }
Java
package com.besttone.search.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.util.Log; public class WifiInfoManager { private WifiManager wifiManager; public WifiInfoManager(Context paramContext) { this.wifiManager = (WifiManager) paramContext.getSystemService(Context.WIFI_SERVICE); } public List<WifiInfo> dump() { if (!this.wifiManager.isWifiEnabled()) { return new ArrayList<WifiInfo>(); } android.net.wifi.WifiInfo wifiConnection = this.wifiManager.getConnectionInfo(); WifiInfo currentWIFI = null; if (wifiConnection != null) { String s = wifiConnection.getBSSID(); int i = wifiConnection.getRssi(); String s1 = wifiConnection.getSSID(); currentWIFI = new WifiInfo(s, i, s1); } ArrayList<WifiInfo> lsAllWIFI = new ArrayList<WifiInfo>(); if (currentWIFI != null) { lsAllWIFI.add(currentWIFI); } List<ScanResult> lsScanResult = this.wifiManager.getScanResults(); for (ScanResult result : lsScanResult) { WifiInfo scanWIFI = new WifiInfo(result); if (!scanWIFI.equals(currentWIFI)) lsAllWIFI.add(scanWIFI); } return lsAllWIFI; } public boolean isWifiEnabled() { return this.wifiManager.isWifiEnabled(); } public JSONArray wifiInfo() { JSONArray jsonArray = new JSONArray(); for (WifiInfo wifi : dump()) { JSONObject localJSONObject = wifi.info(); jsonArray.put(localJSONObject); } return jsonArray; } public WifiManager wifiManager() { return this.wifiManager; } public JSONArray wifiTowers() { JSONArray jsonArray = new JSONArray(); try { Iterator<WifiInfo> localObject = dump().iterator(); while (true) { if (!(localObject).hasNext()) { return jsonArray; } jsonArray.put(localObject.next().wifi_tower()); } } catch (Exception localException) { Log.e("location", localException.getMessage()); } return jsonArray; } public class WifiInfo implements Comparable<WifiInfo> { public int compareTo(WifiInfo wifiinfo) { int i = wifiinfo.dBm; int j = dBm; return i - j; } public boolean equals(Object obj) { boolean flag = false; if (obj == this) { flag = true; return flag; } else { if (obj instanceof WifiInfo) { WifiInfo wifiinfo = (WifiInfo) obj; int i = wifiinfo.dBm; int j = dBm; if (i == j) { String s = wifiinfo.bssid; String s1 = bssid; if (s.equals(s1)) { flag = true; return flag; } } flag = false; } else { flag = false; } } return flag; } public int hashCode() { int i = dBm; int j = bssid.hashCode(); return i ^ j; } public JSONObject info() { JSONObject jsonobject = new JSONObject(); try { String s = bssid; jsonobject.put("mac", s); String s1 = ssid; jsonobject.put("ssid", s1); int i = dBm; jsonobject.put("dbm", i); } catch (Exception ex) { } return jsonobject; } public JSONObject wifi_tower() { JSONObject jsonobject = new JSONObject(); try { String s = bssid; jsonobject.put("mac_address", s); int i = dBm; jsonobject.put("signal_strength", i); String s1 = ssid; jsonobject.put("ssid", s1); jsonobject.put("age", 0); } catch (Exception ex) { } return jsonobject; } public final String bssid; public final int dBm; public final String ssid; public WifiInfo(ScanResult scanresult) { String s = scanresult.BSSID; bssid = s; int i = scanresult.level; dBm = i; String s1 = scanresult.SSID; ssid = s1; } public WifiInfo(String s, int i, String s1) { bssid = s; dBm = i; ssid = s1; } } }
Java
package com.besttone.search.util; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import com.amap.mapapi.location.LocationManagerProxy; import com.amap.mapapi.location.LocationProviderProxy; public class LocationListenerProxy implements LocationListener { private final LocationManagerProxy mLocationManager; private LocationListener mListener = null; public LocationListenerProxy(final LocationManagerProxy pLocationManager) { mLocationManager = pLocationManager; } public boolean startListening(final LocationListener pListener, final long pUpdateTime, final float pUpdateDistance) { boolean result = false; mListener = pListener; //获取当前可用的Provider,其中MapABCNetwork为MapABC网络定位(基站和WiFi) for (final String provider : mLocationManager.getProviders(true)) { if (LocationManagerProxy.GPS_PROVIDER.equals(provider)||LocationProviderProxy.MapABCNetwork.equals(provider)) { result = true; mLocationManager.requestLocationUpdates(provider, pUpdateTime, pUpdateDistance, this); } } return result; } public void stopListening() { mListener = null; mLocationManager.removeUpdates(this); } @Override public void onLocationChanged(final Location location) { if (mListener != null) { mListener.onLocationChanged(location); } } @Override public void onProviderDisabled(final String arg0) { if (mListener != null) { mListener.onProviderDisabled(arg0); } } @Override public void onProviderEnabled(final String arg0) { if (mListener != null) { mListener.onProviderEnabled(arg0); } } @Override public void onStatusChanged(final String arg0, final int arg1, final Bundle arg2) { if (mListener != null) { mListener.onStatusChanged(arg0, arg1, arg2); } } }
Java
package com.besttone.search.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.util.Log; import com.besttone.search.model.PhoneInfo; public class PhoneUtil { private static final String TAG = "PhoneUtil"; public PhoneInfo getPhoneNoByIMSI(String imsi) throws Exception { PhoneInfo info; // 生成请求xml String reqXml = createParm(imsi); //返回XML String rtnXml = getRtnXml(reqXml); //DOM方式解析XML info = dealXml(rtnXml); return info; } public PhoneInfo dealXml(String rtnXml) { PhoneInfo info = new PhoneInfo(); try { // 创建解析工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 指定DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // 从文件构造一个Document,因为XML文件中已经指定了编码,所以这里不必了 ByteArrayInputStream is = new ByteArrayInputStream(rtnXml.getBytes("UTF-8")); Document document = builder.parse(is); //得到Document的根 Element root = document.getDocumentElement(); NodeList nodes = root.getElementsByTagName("data"); // 遍历根节点所有子节点 for (int i = 0; i < nodes.getLength(); i++) { // 获取data元素节点 Element phoneElement = (Element) (nodes.item(i)); // 获取data中mobile属性值 info.setPhoneNo(phoneElement.getAttribute("mobile")); } NodeList list = root.getElementsByTagName("error"); // 遍历根节点所有子节点 for (int i = 0; i < list.getLength(); i++) { info.setErrorFlag(true); Element errElement = (Element) (list.item(i)); // 获取errorCode属性 NodeList codeNode = errElement.getElementsByTagName("errorCode"); // 获取errorCode元素 Element codeElement = (Element)codeNode.item(0); //获得errorCode元素的第一个值 String errorCode = codeElement.getFirstChild().getNodeValue(); info.setErrorCode(errorCode); // 获取errorMsg属性 NodeList msgNode = errElement.getElementsByTagName("errorMessage"); // 获取errorMsg元素 Element msgElement = (Element)msgNode.item(0); //获得errorMsg元素的第一个值 String errorMsg = msgElement.getFirstChild().getNodeValue(); info.setErrorMsg(errorMsg); } } catch (Exception e) { Log.e(TAG, "XML解析出错;"+e.getMessage()); } return info; } public String getRtnXml(String reqXml) throws UnsupportedEncodingException, IOException, ClientProtocolException { //返回XML String rtnXml = ""; //http地址 StringBuilder requestUrl = new StringBuilder(Constants.serverAddress); String parm = "?reqXml=" + URLEncoder.encode(reqXml, "UTF-8") + "&sign=" + MD5Builder.getMD5Str(reqXml + Constants.appSecret); requestUrl.append(parm); String httpUrl = requestUrl.toString(); //HttpGet连接对象 HttpGet httpRequest = new HttpGet(httpUrl); //取得HttpClient对象 HttpClient httpclient = new DefaultHttpClient(); //请求HttpClient,取得HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); //请求成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //取得返回的字符串 rtnXml = EntityUtils.toString(httpResponse.getEntity()).trim(); } return rtnXml; } public String createParm(String imsi) { StringBuffer parmXml = new StringBuffer(""); parmXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); parmXml.append("<reqXML version=\"1.0\">"); String appKeyParm = "<appKey>" + Constants.appKey + "</appKey>"; String apiNameParm = "<apiName>" + Constants.apiName + "</apiName>"; String apiMethodParm = "<apiMethod>" + Constants.apiMethod + "</apiMethod>"; String timestampParm = "<timestamp>" + getTimeStamp() + "</timestamp>"; parmXml.append(appKeyParm); parmXml.append(apiNameParm); parmXml.append(apiMethodParm); parmXml.append(timestampParm); parmXml.append("<params>"); String mobileParm = "<param name=\"imsi\" value=\"" + imsi + "\"/>"; parmXml.append(mobileParm); parmXml.append("</params>"); parmXml.append("</reqXML>"); String parmXmlStr = parmXml.toString(); return parmXmlStr; } public String getTimeStamp() { String timestamp = ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); timestamp = sdf.format(new Date()); return timestamp; } }
Java
package com.besttone.search.model; public class PhoneInfo { private String model; //手机型号 private String phoneNo; //手机号码 private String imei; //IMEI private String simSN; //sim卡序列号 private String country; //国家 private String providerNo; //运营商编号 private String provider; //运营商 private String imsi; private boolean errorFlag = false;//错误标志位 private String errorCode = "";//错误代码 private String errorMsg = "";//错误信息 public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getPhoneNo() { return phoneNo; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } public String getSimSN() { return simSN; } public void setSimSN(String simSN) { this.simSN = simSN; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getProviderNo() { return providerNo; } public void setProviderNo(String providerNo) { this.providerNo = providerNo; } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public String getImsi() { return imsi; } public void setImsi(String imsi) { this.imsi = imsi; } public boolean isErrorFlag() { return errorFlag; } public void setErrorFlag(boolean errorFlag) { this.errorFlag = errorFlag; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } }
Java
package com.besttone.search.model; public class OrgInfo { private String name; private String tel; private String addr; private int chId; private String orgId; private String city; private int regionCode; private int isQymp; private int isDc; private int isDf; private long relevance; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public int getChId() { return chId; } public void setChId(int chId) { this.chId = chId; } public String getOrgId() { return orgId; } public void setOrgId(String orgId) { this.orgId = orgId; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getRegionCode() { return regionCode; } public void setRegionCode(int regionCode) { this.regionCode = regionCode; } public int getIsQymp() { return isQymp; } public void setIsQymp(int isQymp) { this.isQymp = isQymp; } public int getIsDc() { return isDc; } public void setIsDc(int isDc) { this.isDc = isDc; } public int getIsDf() { return isDf; } public void setIsDf(int isDf) { this.isDf = isDf; } public long getRelevance() { return relevance; } public void setRelevance(long relevance) { this.relevance = relevance; } }
Java
package com.besttone.search.model; import java.io.Serializable; public class City implements Serializable { private static final long serialVersionUID = 4060207134630300518L; private String areaCode; private String businessFlag; private String cityCode; private String cityId; private String cityName; private String firstLetter; private String firstPy; private String isFrequent; private String provinceCode; private String provinceId; private String simplifyCode; public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getBusinessFlag() { return businessFlag; } public void setBusinessFlag(String businessFlag) { this.businessFlag = businessFlag; } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public String getCityId() { return cityId; } public void setCityId(String cityId) { this.cityId = cityId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getFirstLetter() { return firstLetter; } public void setFirstLetter(String firstLetter) { this.firstLetter = firstLetter; } public String getFirstPy() { return firstPy; } public void setFirstPy(String firstPy) { this.firstPy = firstPy; } public String getIsFrequent() { return isFrequent; } public void setIsFrequent(String isFrequent) { this.isFrequent = isFrequent; } public String getProvinceCode() { return provinceCode; } public void setProvinceCode(String provinceCode) { this.provinceCode = provinceCode; } public String getProvinceId() { return provinceId; } public void setProvinceId(String provinceId) { this.provinceId = provinceId; } public String getSimplifyCode() { return simplifyCode; } public void setSimplifyCode(String simplifyCode) { this.simplifyCode = simplifyCode; } }
Java
package com.besttone.search.model; import java.io.Serializable; public class District implements Serializable { private static final long serialVersionUID = 1428165031459553637L; private String cityCode; private String simplifyCode; private String districtCode; private String districtId; private String districtName; public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public String getSimplifyCode() { return simplifyCode; } public void setSimplifyCode(String simplifyCode) { this.simplifyCode = simplifyCode; } public String getDistrictCode() { return districtCode; } public void setDistrictCode(String districtCode) { this.districtCode = districtCode; } public String getDistrictId() { return districtId; } public void setDistrictId(String districtId) { this.districtId = districtId; } public String getDistrictName() { return districtName; } public void setDistrictName(String districtName) { this.districtName = districtName; } }
Java
package com.besttone.search.model; import java.util.List; public class ChResultInfo { private String source; private String searchFlag; private int count; private int searchTime; private List<OrgInfo> orgList; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getSearchFlag() { return searchFlag; } public void setSearchFlag(String searchFlag) { this.searchFlag = searchFlag; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getSearchTime() { return searchTime; } public void setSearchTime(int searchTime) { this.searchTime = searchTime; } public List<OrgInfo> getOrgList() { return orgList; } public void setOrgList(List<OrgInfo> orgList) { this.orgList = orgList; } }
Java
package com.besttone.search.model; public class RequestInfo { private String region; private String deviceid; private String imsi; private String content; private String Page; private String PageSize; private String mobile; private String mobguishu; public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getDeviceid() { return deviceid; } public void setDeviceid(String deviceid) { this.deviceid = deviceid; } public String getImsi() { return imsi; } public void setImsi(String imsi) { this.imsi = imsi; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getPage() { return Page; } public void setPage(String page) { Page = page; } public String getPageSize() { return PageSize; } public void setPageSize(String pageSize) { PageSize = pageSize; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getMobguishu() { return mobguishu; } public void setMobguishu(String mobguishu) { this.mobguishu = mobguishu; } }
Java
package com.besttone.search; import com.besttone.app.SuggestionProvider; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.provider.SearchRecentSuggestions; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; public class MoreKeywordActivity extends Activity { private View view; private ImageButton btn_back; private ListView keywordListView; private String[] mKeywordArray = null; private SearchRecentSuggestions suggestions; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); view = this.getLayoutInflater().inflate(R.layout.more_keyword, null); setContentView(view); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); suggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); mKeywordArray = getResources().getStringArray(R.array.hot_search_items); keywordListView =(ListView) findViewById(R.id.keyword_list); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.more_keyword_item, mKeywordArray); keywordListView.setFastScrollEnabled(true); keywordListView.setTextFilterEnabled(true); keywordListView.setAdapter(arrayAdapter); keywordListView.setOnItemClickListener(mOnClickListener); } private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { TextView text = (TextView)v; String keyword = text.getText().toString(); Intent intent = new Intent(); intent.setClass(MoreKeywordActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("keyword", keyword); intent.putExtras(bundle); suggestions.saveRecentQuery(keyword, null); startActivity(intent); } }; }
Java
package com.besttone.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; public class MarqueeTextView extends TextView { public MarqueeTextView(Context context) { super(context); } public MarqueeTextView(Context context, AttributeSet attrs){ super(context,attrs); } public MarqueeTextView(Context context, AttributeSet attrs, int defStyle){ super(context, attrs, defStyle); } public boolean isFocused(){ return true;// 返回true,任何时候都处于focused状态,就能跑马 } }
Java
package com.besttone.widget; import com.besttone.search.R; import android.content.Context; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.InputFilter; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class EditSearchBar extends LinearLayout implements TextWatcher, View.OnClickListener, TextView.OnEditorActionListener { private static final int CMD_CHANGED = 1; private static final long DEALY = 500L; private MSCButton mBtnMsc; private ImageButton mClear; private Handler mDelayHandler = new Handler() { public void handleMessage(Message paramMessage) { if (paramMessage.what == 1) { String str = (String) paramMessage.obj; if (EditSearchBar.this.mListener != null) EditSearchBar.this.mListener.onKeywordChanged(str); } } }; private EditText mEdit; private OnKeywordChangeListner mListener; private OnStartSearchListner mStartListener; public EditSearchBar(Context paramContext) { super(paramContext); } public EditSearchBar(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); } private void publishKeywordChange(String paramString) { this.mDelayHandler.removeMessages(1); this.mDelayHandler.sendMessageDelayed( this.mDelayHandler.obtainMessage(1, paramString), 500L); } public void afterTextChanged(Editable paramEditable) { } public void beforeTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { } public String getKeyword() { String str; if (this.mEdit != null) { str = this.mEdit.getText().toString().trim(); if (TextUtils.isEmpty(str)) this.mEdit.setText(""); } while (true) { str = ""; } } public void onClick(View paramView) { if ((paramView == this.mClear) && (this.mEdit != null)) { this.mEdit.setText(""); publishKeywordChange(""); } } public boolean onEditorAction(TextView paramTextView, int paramInt, KeyEvent paramKeyEvent) { String str = getKeyword(); if ((this.mStartListener != null) && (!TextUtils.isEmpty(str))) { this.mStartListener.onStartSearch(str); return true; } return false; } protected void onFinishInflate() { super.onFinishInflate(); this.mEdit = ((EditText) findViewById(R.id.search_edit)); this.mEdit.addTextChangedListener(this); this.mEdit.setOnEditorActionListener(this); new InputFilter() { private static final String FORBID_CHARS = " ~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/"; private StringBuilder sb = new StringBuilder(); public CharSequence filter(CharSequence paramCharSequence, int paramInt1, int paramInt2, Spanned paramSpanned, int paramInt3, int paramInt4) { String str; if (paramInt1 == paramInt2) str = null; while (true) { this.sb.setLength(0); for (int i = paramInt1;; i++) { if (i >= paramInt2) { if (this.sb.length() <= 0) break; str = this.sb.toString(); break; } char c = paramCharSequence.charAt(i); if (" ~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/".indexOf(c) >= 0) continue; this.sb.append(c); } str = ""; } } }; this.mClear = ((ImageButton) findViewById(R.id.search_clear)); this.mClear.setOnClickListener(this); } public void onTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { if (TextUtils.isEmpty(paramCharSequence)) { this.mClear.setVisibility(View.GONE); publishKeywordChange(paramCharSequence.toString()); } else { while (true) { publishKeywordChange(paramCharSequence.toString()); this.mClear.setVisibility(View.VISIBLE); return; } } } public void onVoiceKeyword(String paramString) { if ((this.mStartListener != null) && (!TextUtils.isEmpty(paramString))) this.mStartListener.onStartSearch(paramString); } public void setHint(int paramInt) { if (this.mEdit != null) this.mEdit.setHint(paramInt); } public void setKeyword(String paramString) { if (paramString == null) { while (true) { if ((this.mEdit != null) && (paramString.compareTo(this.mEdit.getText() .toString()) != 0)) { this.mEdit.setText(paramString); this.mEdit.setSelection(-1 + paramString.length()); continue; } return; } } } public void setOnKeywordChangeListner( OnKeywordChangeListner paramOnKeywordChangeListner) { this.mListener = paramOnKeywordChangeListner; } public void setOnStartSearchListner( OnStartSearchListner paramOnStartSearchListner) { this.mStartListener = paramOnStartSearchListner; } public static abstract interface OnKeywordChangeListner { public abstract void onKeywordChanged(String paramString); } public static abstract interface OnStartSearchListner { public abstract void onStartSearch(String paramString); } }
Java
package com.besttone.widget.scroll; public interface OnViewChangeListener { public void OnViewChange(int view); }
Java
package com.besttone.widget.scroll; import android.R.bool; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.View.MeasureSpec; import android.widget.Scroller; public class MyScrollLayout extends ViewGroup{ private static final String TAG = "ScrollLayout"; private VelocityTracker mVelocityTracker; // 用于判断甩动手势 private static final int SNAP_VELOCITY = 600; private Scroller mScroller; // 滑动控制器 private int mCurScreen; public int getmCurScreen() { return mCurScreen; } private int mDefaultScreen = 0; private float mLastMotionX; private int mTouchSlop; private static final int TOUCH_STATE_REST = 0; private static final int TOUCH_STATE_SCROLLING = 1; private int mTouchState = TOUCH_STATE_REST; private OnViewChangeListener mOnViewChangeListener; private boolean bScroll=false; public MyScrollLayout(Context context) { super(context); // TODO Auto-generated constructor stub init(context); } public MyScrollLayout(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub init(context); } public MyScrollLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub init(context); } private void init(Context context) { mCurScreen = mDefaultScreen; // mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); mScroller = new Scroller(context); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // TODO Auto-generated method stub if (changed) { int childLeft = 0; final int childCount = getChildCount(); for (int i=0; i<childCount; i++) { final View childView = getChildAt(i); if (childView.getVisibility() != View.GONE) { final int childWidth = childView.getMeasuredWidth(); childView.layout(childLeft, 0, childLeft+childWidth, childView.getMeasuredHeight()); childLeft += childWidth; } } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int width = MeasureSpec.getSize(widthMeasureSpec); final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int count = getChildCount(); for (int i = 0; i < count; i++) { getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec); } scrollTo(mCurScreen * width, 0); } public void snapToDestination() { final int screenWidth = getWidth(); final int destScreen = (getScrollX()+ screenWidth/2)/screenWidth; snapToScreen(destScreen); } public void snapToScreen(int whichScreen) { // get the valid layout page whichScreen = Math.max(0, Math.min(whichScreen, getChildCount()-1)); if (getScrollX() != (whichScreen*getWidth())) { final int delta = whichScreen*getWidth()-getScrollX(); mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta)*2); mCurScreen = whichScreen; invalidate(); // Redraw the layout if (mOnViewChangeListener != null) { mOnViewChangeListener.OnViewChange(mCurScreen); } } } @Override public void computeScroll() { // TODO Auto-generated method stub if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); postInvalidate(); } } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub final int action = event.getAction(); final float x = event.getX(); final float y = event.getY(); switch (action) { case MotionEvent.ACTION_DOWN: Log.i("onTouchEvent", "ACTION_DOWN"); if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(event); } if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mLastMotionX = x; break; case MotionEvent.ACTION_MOVE: int deltaX = (int) (mLastMotionX - x); if (deltaX > 1) bScroll = true; if (IsCanMove(deltaX)) { if (mVelocityTracker != null) { mVelocityTracker.addMovement(event); } Log.i("onTouchEvent", "ACTION_MOVE"); mLastMotionX = x; scrollBy(deltaX, 0); } break; case MotionEvent.ACTION_UP: if (!bScroll) { boolean result = performClick(); } bScroll = false; int velocityX = 0; if (mVelocityTracker != null) { mVelocityTracker.addMovement(event); mVelocityTracker.computeCurrentVelocity(1000); velocityX = (int) mVelocityTracker.getXVelocity(); } if (velocityX > SNAP_VELOCITY && mCurScreen > 0) { // Fling enough to move left // Log.e(TAG, "snap left"); snapToScreen(mCurScreen - 1); } else if (velocityX < -SNAP_VELOCITY && mCurScreen < getChildCount() - 1) { // Fling enough to move right // Log.e(TAG, "snap right"); snapToScreen(mCurScreen + 1); } else { snapToDestination(); } if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } // mTouchState = TOUCH_STATE_REST; break; } return true; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { // TODO Auto-generated method stub final int action = ev.getAction(); final float x = ev.getX(); final float y = ev.getY(); switch (action) { case MotionEvent.ACTION_DOWN: Log.i("onInterceptTouchEvent", "ACTION_DOWN"); if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(ev); } if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mLastMotionX = x; break; case MotionEvent.ACTION_MOVE: int deltaX = (int) (mLastMotionX - x); // if (deltaX > 1) // bScroll = true; if (IsCanMove(deltaX)) { if (mVelocityTracker != null) { mVelocityTracker.addMovement(ev); } mLastMotionX = x; Log.i("onInterceptTouchEvent", "ACTION_MOVE"); // Log.i("ACTION_MOVE", " deltaX="+deltaX); scrollBy(deltaX, 0); } break; case MotionEvent.ACTION_UP: // if (!bScroll) // { // boolean result = performClick(); // } // bScroll = false; int velocityX = 0; if (mVelocityTracker != null) { mVelocityTracker.addMovement(ev); mVelocityTracker.computeCurrentVelocity(1000); velocityX = (int) mVelocityTracker.getXVelocity(); } if (velocityX > SNAP_VELOCITY && mCurScreen > 0) { // Fling enough to move left // Log.e(TAG, "snap left"); snapToScreen(mCurScreen - 1); } else if (velocityX < -SNAP_VELOCITY && mCurScreen < getChildCount() - 1) { // Fling enough to move right // Log.e(TAG, "snap right"); snapToScreen(mCurScreen + 1); } else { snapToDestination(); } if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } // mTouchState = TOUCH_STATE_REST; break; } // switch (action) // { // case MotionEvent.ACTION_MOVE: // final int xDiff = (int) Math.abs(mLastMotionX - x); // if (xDiff > mTouchSlop) // { // mTouchState = TOUCH_STATE_SCROLLING; // } // break; // // case MotionEvent.ACTION_DOWN: // mLastMotionX = x; // // mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING; // break; // // case MotionEvent.ACTION_CANCEL: // case MotionEvent.ACTION_UP: // mTouchState = TOUCH_STATE_REST; // break; // } // // if (mTouchState != TOUCH_STATE_REST) // { // Log.i("mTouchState != TOUCH_STATE_REST", " return true"); // } // // return mTouchState != TOUCH_STATE_REST; return false; } private boolean IsCanMove(int deltaX) { if (getScrollX() <= 0 && deltaX < 0 ) { return false; } if (getScrollX() >= (getChildCount() - 1) * getWidth() && deltaX > 0) { return false; } return true; } public void SetOnViewChangeListener(OnViewChangeListener listener) { mOnViewChangeListener = listener; } }
Java
package com.besttone.widget; import com.besttone.search.R; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; public class PoiListItem extends LinearLayout { TextView name; TextView tel; TextView addr; public PoiListItem(Context context) { super(context); } public PoiListItem(Context context, AttributeSet attrs) { super(context, attrs); } public void setPoiData(String name, String tel, String addr, String city) { int m = 0; if(city!=null && city.trim().length()!=0){ this.addr.setText("【" + city +"】" + addr); } else { this.addr.setText(addr); } this.tel.setText(tel); this.name.setText(name); this.name.setPadding(this.name.getPaddingLeft(), this.name.getPaddingTop(), m, this.name.getPaddingBottom()); } protected void onFinishInflate() { super.onFinishInflate(); this.name = ((TextView) findViewById(R.id.name)); this.tel = ((TextView) findViewById(R.id.tel)); this.addr = ((TextView) findViewById(R.id.addr)); } }
Java
package com.besttone.widget; public class MSCButton { }
Java
package com.besttone.widget; import com.besttone.search.R; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; public class ButtonSearchBar extends LinearLayout implements View.OnClickListener { private Button btnSearch; private ButtonSearchBarListener mListener; public ButtonSearchBar(Context paramContext) { super(paramContext); } public ButtonSearchBar(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); } public void onClick(View paramView) { // if (this.mListener != null) // this.mListener.onSearchRequested(); } protected void onFinishInflate() { super.onFinishInflate(); // this.btnSearch = ((Button) findViewById(R.id.start_search)); // this.btnSearch.setOnClickListener(this); } public void onVoiceKeyword(String paramString) { if (this.mListener != null) this.mListener.onSearchRequested(paramString); } public void setButtonSearchBarListener( ButtonSearchBarListener paramButtonSearchBarListener) { this.mListener = paramButtonSearchBarListener; } public void setGaTag(String paramString) { } public void setHint(int paramInt) { if (this.btnSearch == null); while (true) { if (paramInt > 0) { this.btnSearch.setHint(paramInt); continue; } this.btnSearch.setHint(R.string.search_hint); return; } } public void setHint(String paramString) { if (this.btnSearch != null) this.btnSearch.setHint(paramString); } public void setKeyword(String paramString) { if (this.btnSearch != null) this.btnSearch.setText(paramString); } public static abstract interface ButtonSearchBarListener { public abstract void onSearchRequested(); public abstract void onSearchRequested(String paramString); } }
Java
package com.besttone.widget; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; import android.widget.SectionIndexer; @SuppressLint("ResourceAsColor") public class AlphabetBar extends View { private String[] l; private ListView list; private int mCurIdx; private OnSelectedListener mOnSelectedListener; private int m_nItemHeight; private SectionIndexer sectionIndexter; public AlphabetBar(Context paramContext) { super(paramContext); String[] arrayOfString = new String[27]; arrayOfString[0] = "热门"; arrayOfString[1] = "A"; arrayOfString[2] = "B"; arrayOfString[3] = "C"; arrayOfString[4] = "D"; arrayOfString[5] = "E"; arrayOfString[6] = "F"; arrayOfString[7] = "G"; arrayOfString[8] = "H"; arrayOfString[9] = "I"; arrayOfString[10] = "J"; arrayOfString[11] = "K"; arrayOfString[12] = "L"; arrayOfString[13] = "M"; arrayOfString[14] = "N"; arrayOfString[15] = "O"; arrayOfString[16] = "P"; arrayOfString[17] = "Q"; arrayOfString[18] = "R"; arrayOfString[19] = "S"; arrayOfString[20] = "T"; arrayOfString[21] = "U"; arrayOfString[22] = "V"; arrayOfString[23] = "W"; arrayOfString[24] = "X"; arrayOfString[25] = "Y"; arrayOfString[26] = "Z"; this.l = arrayOfString; this.sectionIndexter = null; this.m_nItemHeight = 25; setBackgroundColor(1157627903); } public AlphabetBar(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); String[] arrayOfString = new String[27]; arrayOfString[0] = "热门"; arrayOfString[1] = "A"; arrayOfString[2] = "B"; arrayOfString[3] = "C"; arrayOfString[4] = "D"; arrayOfString[5] = "E"; arrayOfString[6] = "F"; arrayOfString[7] = "G"; arrayOfString[8] = "H"; arrayOfString[9] = "I"; arrayOfString[10] = "J"; arrayOfString[11] = "K"; arrayOfString[12] = "L"; arrayOfString[13] = "M"; arrayOfString[14] = "N"; arrayOfString[15] = "O"; arrayOfString[16] = "P"; arrayOfString[17] = "Q"; arrayOfString[18] = "R"; arrayOfString[19] = "S"; arrayOfString[20] = "T"; arrayOfString[21] = "U"; arrayOfString[22] = "V"; arrayOfString[23] = "W"; arrayOfString[24] = "X"; arrayOfString[25] = "Y"; arrayOfString[26] = "Z"; this.l = arrayOfString; this.sectionIndexter = null; this.m_nItemHeight = 25; setBackgroundColor(1157627903); } public AlphabetBar(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); String[] arrayOfString = new String[27]; arrayOfString[0] = "热门"; arrayOfString[1] = "A"; arrayOfString[2] = "B"; arrayOfString[3] = "C"; arrayOfString[4] = "D"; arrayOfString[5] = "E"; arrayOfString[6] = "F"; arrayOfString[7] = "G"; arrayOfString[8] = "H"; arrayOfString[9] = "I"; arrayOfString[10] = "J"; arrayOfString[11] = "K"; arrayOfString[12] = "L"; arrayOfString[13] = "M"; arrayOfString[14] = "N"; arrayOfString[15] = "O"; arrayOfString[16] = "P"; arrayOfString[17] = "Q"; arrayOfString[18] = "R"; arrayOfString[19] = "S"; arrayOfString[20] = "T"; arrayOfString[21] = "U"; arrayOfString[22] = "V"; arrayOfString[23] = "W"; arrayOfString[24] = "X"; arrayOfString[25] = "Y"; arrayOfString[26] = "Z"; this.l = arrayOfString; this.sectionIndexter = null; this.m_nItemHeight = 25; setBackgroundColor(1157627903); } public int getCurIndex() { return this.mCurIdx; } @SuppressLint("ResourceAsColor") protected void onDraw(Canvas paramCanvas) { Paint localPaint = new Paint(); localPaint.setColor(Color.LTGRAY); float f = 0; if (this.m_nItemHeight > 25) { localPaint.setTextSize(20.0F); localPaint.setTextAlign(Paint.Align.CENTER); f = getMeasuredWidth() / 2; } for (int i = 0;; i++) { if (i >= this.l.length) { super.onDraw(paramCanvas); if (-5 + this.m_nItemHeight < 5) { localPaint.setTextSize(5.0F); break; } localPaint.setTextSize(-5 + this.m_nItemHeight); break; } paramCanvas.drawText(String.valueOf(this.l[i]), f, this.m_nItemHeight + i * this.m_nItemHeight, localPaint); return; } } protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { super.onLayout(paramBoolean, paramInt1, paramInt2, paramInt3, paramInt4); this.m_nItemHeight = ((-10 + (paramInt4 - paramInt2)) / this.l.length); } public boolean onTouchEvent(MotionEvent paramMotionEvent) { super.onTouchEvent(paramMotionEvent); int i = (int) paramMotionEvent.getY() / this.m_nItemHeight; int j = 0; if (i >= this.l.length) { i = -1 + this.l.length; this.mCurIdx = i; if (this.sectionIndexter == null) this.sectionIndexter = ((SectionIndexer) this.list.getAdapter()); j = this.sectionIndexter.getPositionForSection(i); } while (true) { if (i >= 0) break; i = 0; this.list.setSelection(j); if (this.mOnSelectedListener != null) this.mOnSelectedListener.onSelected(j); setBackgroundColor(-3355444); return true; } return false; } public void setListView(ListView paramListView) { this.list = paramListView; } public void setOnSelectedListener(OnSelectedListener paramOnSelectedListener) { this.mOnSelectedListener = paramOnSelectedListener; } public void setSectionIndexter(SectionIndexer paramSectionIndexer) { this.sectionIndexter = paramSectionIndexer; } public static abstract interface OnSelectedListener { public abstract void onSelected(int paramInt); public abstract void onUnselected(); } }
Java
package com.besttone.adapter; import java.util.ArrayList; import com.besttone.search.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; public class CateAdapter extends BaseAdapter { private String[] data; Context mContext; private LayoutInflater mInflater; private int typeIndex = 0; public CateAdapter(Context context, String[] mChannelArray) { mContext = context; data = mChannelArray; this.mInflater = LayoutInflater.from(context); } public String getSelect() { return data[typeIndex]; } public void setTypeIndex(int index) { typeIndex = index; } public int getCount() { return data.length; } public Object getItem(int position) { return data[position]; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(R.layout.dialog_list_item, null); String area = data[position]; ((TextView) convertView.findViewById(R.id.id_area)).setText(area); View view = new View(mContext); LayoutParams param = new LayoutParams(30, 30); view.setLayoutParams(param); if (position == typeIndex) { convertView.findViewById(R.id.ic_checked).setVisibility( View.VISIBLE); } ((LinearLayout) convertView).addView(view, 0); return convertView; } private ArrayList<String> getData() { ArrayList<String> data = new ArrayList<String>(); data.add("全部频道"); data.add("美食"); data.add("休闲娱乐"); data.add("购物"); data.add("酒店"); data.add("丽人"); data.add("运动健身"); data.add("结婚"); data.add("生活服务"); return data; } }
Java
package com.besttone.adapter; import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.besttone.search.Client; import com.besttone.search.R; import com.besttone.search.model.City; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.StringUtils; import java.util.ArrayList; public class CityListAdapter extends LetterListAdapter { public TextView tvLocationCity=null; public CityListAdapter() { } public CityListAdapter(Context paramContext, ArrayList<City> paramArrayList) { super(paramContext, paramArrayList); } public View setTheView(int paramInt, View paramView, ViewGroup paramViewGroup) { City localCity = (City) this.mCitylist.get(paramInt); if ("-1".equals(localCity.getCityName())) { TextView localTextView = new TextView(this.mContext); localTextView.setTextAppearance(this.mContext, R.style.text_18_black); localTextView.setPadding(15, 0, 0, 0); localTextView.setBackgroundResource(R.color.title_grey); localTextView.setGravity(16); localTextView.setText(localCity.getFirstLetter()); return localTextView; } View localView = LayoutInflater.from(this.mContext).inflate(R.layout.select_city_list_item, null); String str1 = localCity.getCityName(); String str = localCity.getFirstLetter(); ((TextView) localView.findViewById(R.id.city_info)).setText(str1); ImageView localImageView = (ImageView) localView.findViewById(R.id.selected_item); String str2 = SharedUtils.getCurrentCityName(this.mContext); if ((!StringUtils.isEmpty(str2)) && (str2.equals(str1))) { localImageView.setVisibility(View.VISIBLE); } else { while (true) { localImageView.setVisibility(View.INVISIBLE); break; } } return localView; } }
Java
package com.besttone.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.besttone.search.model.City; import java.util.ArrayList; public abstract class LetterListAdapter extends BaseAdapter { ArrayList<City> mCitylist; Context mContext; public LetterListAdapter() { } public LetterListAdapter(Context paramContext, ArrayList<City> paramArrayList) { this.mCitylist = paramArrayList; this.mContext = paramContext; } public ArrayList<City> getmCitylist() { return mCitylist; } public void setmCitylist(ArrayList<City> mCitylist) { this.mCitylist = mCitylist; } public int getCount() { return this.mCitylist.size(); } public Object getItem(int paramInt) { return this.mCitylist.get(paramInt); } public long getItemId(int paramInt) { return paramInt; } public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) { return setTheView(paramInt, paramView, paramViewGroup); } public abstract View setTheView(int paramInt, View paramView, ViewGroup paramViewGroup); }
Java
package com.besttone.adapter; import java.util.ArrayList; import com.besttone.search.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; public class SortAdapter extends BaseAdapter { private String[] data; Context mContext; private LayoutInflater mInflater; private int disableIndex = -1; private int typeIndex = 0; public SortAdapter(Context context, String[] mSortArray) { mContext = context; data = mSortArray; this.mInflater = LayoutInflater.from(context); } public String[] getDataArray() { return data; } public String getSelect() { return data[typeIndex]; } public void setTypeIndex(int index) { typeIndex = index; } public int getCount() { return data.length; } public Object getItem(int position) { return data[position]; } public long getItemId(int position) { return position; } public boolean isEnabled(int position) { return true; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(R.layout.dialog_list_item, null); String area = data[position]; ((TextView) convertView.findViewById(R.id.id_area)).setText(area); View view = new View(mContext); LayoutParams param = new LayoutParams(30, 30); view.setLayoutParams(param); if (position == typeIndex) { convertView.findViewById(R.id.ic_checked).setVisibility( View.VISIBLE); } ((LinearLayout) convertView).addView(view, 0); return convertView; } private ArrayList<String> getData() { ArrayList<String> data = new ArrayList<String>(); data.add("按默认排序"); data.add("按距离排序"); data.add("按人气排序"); data.add("按星级排序"); data.add("按点评数排序"); data.add("优惠劵商户优先"); data.add("titlebar"); data.add("20元以下"); data.add("21-50"); data.add("51-80"); data.add("81-120"); data.add("121-200"); data.add("201以上"); return data; } }
Java
package com.besttone.adapter; import java.util.ArrayList; import java.util.Map; import com.besttone.search.R; import com.besttone.search.util.Constants; import com.besttone.search.util.SharedUtils; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; public class AreaAdapter extends BaseAdapter { private LayoutInflater mInflater; private String[] mData; private int typeIndex = 0; private Context context; public AreaAdapter(Context context, String[] mAreaArray) { this.context = context; this.mInflater = LayoutInflater.from(context); mData = mAreaArray; } public String[] getDataArray() { return mData; } public String getSelect() { return mData[typeIndex]; } public void setTypeIndex(int index) { typeIndex = index; } public int getCount() { return mData.length; } public Object getItem(int position) { return mData[position]; } public long getItemId(int arg0) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(R.layout.dialog_list_item, null); View view = new View(context); LayoutParams param = new LayoutParams(30, 30); view.setLayoutParams(param); String area = mData[position]; ((TextView)convertView.findViewById(R.id.id_area)).setText(area); if(position == typeIndex) { convertView.findViewById(R.id.ic_checked).setVisibility(View.VISIBLE); } ((LinearLayout)convertView).addView(view, 0); return convertView; } // private ArrayList<ArrayList<String>> getData() // { // ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>(); // // ArrayList<String> quanbu = new ArrayList<String>(); // quanbu.add("全部地区"); // quanbu.add("全部地区 "); // data.add(quanbu); // // ArrayList<String> hongkou = new ArrayList<String>(); // hongkou.add("全部地区"); // hongkou.add("虹口区"); // hongkou.add("海宁路/七浦路"); // hongkou.add("临平路/和平公园"); // hongkou.add("曲阳地区"); // hongkou.add("四川北路"); // hongkou.add("鲁迅公园"); // data.add(hongkou); // // ArrayList<String> zhabei = new ArrayList<String>(); // zhabei.add("全部地区"); // zhabei.add("闸北区"); // zhabei.add("大宁大区"); // zhabei.add("北区汽车站"); // zhabei.add("火车站"); // zhabei.add("闸北公园"); // data.add(zhabei); // // ArrayList<String> xuhui = new ArrayList<String>(); // xuhui.add("全部地区"); // xuhui.add("徐汇区"); // xuhui.add("衡山路"); // xuhui.add("音乐学院"); // xuhui.add("肇家浜路沿线"); // xuhui.add("漕河泾/田林"); // data.add(xuhui); // // ArrayList<String> changning = new ArrayList<String>(); // changning.add("全部地区"); // changning.add("长宁区"); // changning.add("天山"); // changning.add("上海影城/新华路"); // changning.add("中山公园"); // changning.add("古北"); // data.add(changning); // // ArrayList<String> yangpu = new ArrayList<String>(); // yangpu.add("全部地区"); // yangpu.add("杨浦区"); // yangpu.add("五角场"); // yangpu.add("控江地区"); // yangpu.add("平凉路"); // yangpu.add("黄兴公园"); // data.add(yangpu); // // ArrayList<String> qingpu = new ArrayList<String>(); // qingpu.add("全部地区"); // qingpu.add("青浦区"); // qingpu.add("朱家角"); // data.add(qingpu); // // ArrayList<String> songjiang = new ArrayList<String>(); // songjiang.add("全部地区"); // songjiang.add("松江区"); // songjiang.add("松江镇"); // songjiang.add("九亭"); // songjiang.add("佘山"); // songjiang.add("松江大学城"); // data.add(songjiang); // // ArrayList<String> baoshan = new ArrayList<String>(); // baoshan.add("全部地区"); // baoshan.add("宝山区"); // baoshan.add("大华大区"); // baoshan.add("庙行镇"); // baoshan.add("吴淞"); // baoshan.add("上海大学"); // data.add(baoshan); // // ArrayList<String> pudong = new ArrayList<String>(); // pudong.add("全部地区"); // pudong.add("康桥/周浦"); // pudong.add("陆家嘴"); // pudong.add("世纪公园"); // pudong.add("八佰伴"); // data.add(pudong); // // return data; // } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.util.Log; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.http.HttpClient; import com.ch_linghu.fanfoudroid.ui.module.MyTextView; public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //禁止横屏 if (TwitterApplication.mPref.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } // TODO: is this a hack? setResult(RESULT_OK); addPreferencesFromResource(R.xml.preferences); } @Override protected void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { return super.onPreferenceTreeClick(preferenceScreen, preference); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if ( key.equalsIgnoreCase(Preferences.NETWORK_TYPE) ) { HttpClient httpClient = TwitterApplication.mApi.getHttpClient(); String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, ""); if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) { Log.d("LDS", "Set proxy for cmwap mode."); httpClient.setProxy("10.0.0.172", 80, "http"); } else { Log.d("LDS", "No proxy."); httpClient.removeProxy(); } } else if ( key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) { MyTextView.setFontSizeChanged(true); } } }
Java
package com.ch_linghu.fanfoudroid.app; import java.util.HashMap; import android.graphics.Bitmap; public class MemoryImageCache implements ImageCache { private HashMap<String, Bitmap> mCache; public MemoryImageCache() { mCache = new HashMap<String, Bitmap>(); } @Override public Bitmap get(String url) { synchronized(this) { Bitmap bitmap = mCache.get(url); if (bitmap == null){ return mDefaultBitmap; }else{ return bitmap; } } } @Override public void put(String url, Bitmap bitmap) { synchronized(this) { mCache.put(url, bitmap); } } public void putAll(MemoryImageCache imageCache) { synchronized(this) { // TODO: is this thread safe? mCache.putAll(imageCache.mCache); } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.app; public class Preferences { public static final String USERNAME_KEY = "username"; public static final String PASSWORD_KEY = "password"; public static final String CHECK_UPDATES_KEY = "check_updates"; public static final String CHECK_UPDATE_INTERVAL_KEY = "check_update_interval"; public static final String VIBRATE_KEY = "vibrate"; public static final String TIMELINE_ONLY_KEY = "timeline_only"; public static final String REPLIES_ONLY_KEY = "replies_only"; public static final String DM_ONLY_KEY = "dm_only"; public static String RINGTONE_KEY = "ringtone"; public static final String RINGTONE_DEFAULT_KEY = "content://settings/system/notification_sound"; public static final String LAST_TWEET_REFRESH_KEY = "last_tweet_refresh"; public static final String LAST_DM_REFRESH_KEY = "last_dm_refresh"; public static final String LAST_FOLLOWERS_REFRESH_KEY = "last_followers_refresh"; public static final String TWITTER_ACTIVITY_STATE_KEY = "twitter_activity_state"; public static final String USE_PROFILE_IMAGE = "use_profile_image"; public static final String PHOTO_PREVIEW = "photo_preview"; public static final String FORCE_SHOW_ALL_IMAGE = "force_show_all_image"; public static final String RT_PREFIX_KEY = "rt_prefix"; public static final String RT_INSERT_APPEND = "rt_insert_append"; // 转发时光标放置在开始还是结尾 public static final String NETWORK_TYPE = "network_type"; // DEBUG标记 public static final String DEBUG = "debug"; // 当前用户相关信息 public static final String CURRENT_USER_ID = "current_user_id"; public static final String CURRENT_USER_SCREEN_NAME = "current_user_screenname"; public static final String UI_FONT_SIZE = "ui_font_size"; public static final String USE_ENTER_SEND = "use_enter_send"; public static final String USE_GESTRUE = "use_gestrue"; public static final String USE_SHAKE = "use_shake"; public static final String FORCE_SCREEN_ORIENTATION_PORTRAIT = "force_screen_orientation_portrait"; }
Java
package com.ch_linghu.fanfoudroid.app; import android.text.Spannable; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.view.MotionEvent; import android.widget.TextView; public class TestMovementMethod extends LinkMovementMethod { private double mY; private boolean mIsMoving = false; @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { /* int action = event.getAction(); if (action == MotionEvent.ACTION_MOVE) { double deltaY = mY - event.getY(); mY = event.getY(); Log.d("foo", deltaY + ""); if (Math.abs(deltaY) > 1) { mIsMoving = true; } } else if (action == MotionEvent.ACTION_DOWN) { mIsMoving = false; mY = event.getY(); } else if (action == MotionEvent.ACTION_UP) { boolean wasMoving = mIsMoving; mIsMoving = false; if (wasMoving) { return true; } } */ return super.onTouchEvent(widget, buffer, event); } public static MovementMethod getInstance() { if (sInstance == null) sInstance = new TestMovementMethod(); return sInstance; } private static TestMovementMethod sInstance; }
Java
package com.ch_linghu.fanfoudroid.app; import android.app.Activity; import android.content.Intent; import android.widget.Toast; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.fanfou.RefuseError; import com.ch_linghu.fanfoudroid.http.HttpAuthException; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.http.HttpServerException; public class ExceptionHandler { private Activity mActivity; public ExceptionHandler(Activity activity) { mActivity = activity; } public void handle(HttpException e) { Throwable cause = e.getCause(); if (null == cause) return; // Handle Different Exception if (cause instanceof HttpAuthException) { // 用户名/密码错误 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); Intent intent = new Intent(mActivity, LoginActivity.class); mActivity.startActivity(intent); // redirect to the login activity } else if (cause instanceof HttpServerException) { // 服务器暂时无法响应 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); } else if (cause instanceof HttpAuthException) { //FIXME: 集中处理用户名/密码验证错误,返回到登录界面 } else if (cause instanceof HttpRefusedException) { // 服务器拒绝请求,如没有权限查看某用户信息 RefuseError error = ((HttpRefusedException) cause).getError(); switch (error.getErrorCode()) { // TODO: finish it case -1: default: Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG).show(); break; } } } private void handleCause() { } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.app; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * Manages retrieval and storage of icon images. Use the put method to download * and store images. Use the get method to retrieve images from the manager. */ public class ImageManager implements ImageCache { private static final String TAG = "ImageManager"; // 饭否目前最大宽度支持596px, 超过则同比缩小 // 最大高度为1192px, 超过从中截取 public static final int DEFAULT_COMPRESS_QUALITY = 90; public static final int IMAGE_MAX_WIDTH = 596; public static final int IMAGE_MAX_HEIGHT = 1192; private Context mContext; // In memory cache. private Map<String, SoftReference<Bitmap>> mCache; // MD5 hasher. private MessageDigest mDigest; public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable .getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } public ImageManager(Context context) { mContext = context; mCache = new HashMap<String, SoftReference<Bitmap>>(); try { mDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // This shouldn't happen. throw new RuntimeException("No MD5 algorithm."); } } public void setContext(Context context) { mContext = context; } private String getHashString(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for (byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } // MD5 hases are used to generate filenames based off a URL. private String getMd5(String url) { mDigest.update(url.getBytes()); return getHashString(mDigest); } // Looks to see if an image is in the file system. private Bitmap lookupFile(String url) { String hashedUrl = getMd5(url); FileInputStream fis = null; try { fis = mContext.openFileInput(hashedUrl); return BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { // Not there. return null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // Ignore. } } } } /** * Downloads a file * @param url * @return * @throws HttpException */ public Bitmap downloadImage(String url) throws HttpException { Log.d(TAG, "Fetching image: " + url); Response res = TwitterApplication.mApi.getHttpClient().get(url); return BitmapFactory.decodeStream(new BufferedInputStream(res.asStream())); } public Bitmap downloadImage2(String url) throws HttpException { Log.d(TAG, "[NEW]Fetching image: " + url); final Response res = TwitterApplication.mApi.getHttpClient().get(url); String file = writeToFile(res.asStream(), getMd5(url)); return BitmapFactory.decodeFile(file); } /** * 下载远程图片 -> 转换为Bitmap -> 写入缓存器. * @param url * @param quality image quality 1~100 * @throws HttpException */ public void put(String url, int quality, boolean forceOverride) throws HttpException { if (!forceOverride && contains(url)) { // Image already exists. return; // TODO: write to file if not present. } Bitmap bitmap = downloadImage(url); if (bitmap != null) { put(url, bitmap, quality); // file cache } else { Log.w(TAG, "Retrieved bitmap is null."); } } /** * 重载 put(String url, int quality) * @param url * @throws HttpException */ public void put(String url) throws HttpException { put(url, DEFAULT_COMPRESS_QUALITY, false); } /** * 将本地File -> 转换为Bitmap -> 写入缓存器. * 如果图片大小超过MAX_WIDTH/MAX_HEIGHT, 则将会对图片缩放. * * @param file * @param quality 图片质量(0~100) * @param forceOverride * @throws IOException */ public void put(File file, int quality, boolean forceOverride) throws IOException { if (!file.exists()) { Log.w(TAG, file.getName() + " is not exists."); return; } if (!forceOverride && contains(file.getPath())) { // Image already exists. Log.d(TAG, file.getName() + " is exists"); return; // TODO: write to file if not present. } Bitmap bitmap = BitmapFactory.decodeFile(file.getPath()); //bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT); if (bitmap == null) { Log.w(TAG, "Retrieved bitmap is null."); } else { put(file.getPath(), bitmap, quality); } } /** * 将Bitmap写入缓存器. * @param filePath file path * @param bitmap * @param quality 1~100 */ public void put(String file, Bitmap bitmap, int quality) { synchronized (this) { mCache.put(file, new SoftReference<Bitmap>(bitmap)); } writeFile(file, bitmap, quality); } /** * 重载 put(String file, Bitmap bitmap, int quality) * @param filePath file path * @param bitmap * @param quality 1~100 */ @Override public void put(String file, Bitmap bitmap) { put(file, bitmap, DEFAULT_COMPRESS_QUALITY); } /** * 将Bitmap写入本地缓存文件. * @param file URL/PATH * @param bitmap * @param quality */ private void writeFile(String file, Bitmap bitmap, int quality) { if (bitmap == null) { Log.w(TAG, "Can't write file. Bitmap is null."); return; } BufferedOutputStream bos = null; try { String hashedUrl = getMd5(file); bos = new BufferedOutputStream( mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE)); bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos); // PNG Log.d(TAG, "Writing file: " + file); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage()); } finally { try { if (bos != null) { bitmap.recycle(); bos.flush(); bos.close(); } //bitmap.recycle(); } catch (IOException e) { Log.e(TAG, "Could not close file."); } } } private String writeToFile(InputStream is, String filename) { Log.d("LDS", "new write to file"); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(is); out = new BufferedOutputStream( mContext.openFileOutput(filename, Context.MODE_PRIVATE)); byte[] buffer = new byte[1024]; int l; while ((l = in.read(buffer)) != -1) { out.write(buffer, 0, l); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) { Log.d("LDS", "new write to file to -> " + filename); out.flush(); out.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } return mContext.getFilesDir() + "/" + filename; } public Bitmap get(File file) { return get(file.getPath()); } /** * 判断缓存着中是否存在该文件对应的bitmap */ public boolean isContains(String file) { return mCache.containsKey(file); } /** * 获得指定file/URL对应的Bitmap,首先找本地文件,如果有直接使用,否则去网上获取 * @param file file URL/file PATH * @param bitmap * @param quality * @throws HttpException */ public Bitmap safeGet(String file) throws HttpException { Bitmap bitmap = lookupFile(file); // first try file. if (bitmap != null) { synchronized (this) { // memory cache mCache.put(file, new SoftReference<Bitmap>(bitmap)); } return bitmap; } else { //get from web String url = file; bitmap = downloadImage2(url); // 注释掉以测试新的写入文件方法 //put(file, bitmap); // file Cache return bitmap; } } /** * 从缓存器中读取文件 * @param file file URL/file PATH * @param bitmap * @param quality */ public Bitmap get(String file) { SoftReference<Bitmap> ref; Bitmap bitmap; // Look in memory first. synchronized (this) { ref = mCache.get(file); } if (ref != null) { bitmap = ref.get(); if (bitmap != null) { return bitmap; } } // Now try file. bitmap = lookupFile(file); if (bitmap != null) { synchronized (this) { mCache.put(file, new SoftReference<Bitmap>(bitmap)); } return bitmap; } //TODO: why? //upload: see profileImageCacheManager line 96 Log.w(TAG, "Image is missing: " + file); // return the default photo return mDefaultBitmap; } public boolean contains(String url) { return get(url) != mDefaultBitmap; } public void clear() { String[] files = mContext.fileList(); for (String file : files) { mContext.deleteFile(file); } synchronized (this) { mCache.clear(); } } public void cleanup(HashSet<String> keepers) { String[] files = mContext.fileList(); HashSet<String> hashedUrls = new HashSet<String>(); for (String imageUrl : keepers) { hashedUrls.add(getMd5(imageUrl)); } for (String file : files) { if (!hashedUrls.contains(file)) { Log.d(TAG, "Deleting unused file: " + file); mContext.deleteFile(file); } } } /** * Compress and resize the Image * * <br /> * 因为不论图片大小和尺寸如何, 饭否都会对图片进行一次有损压缩, 所以本地压缩应该 * 考虑图片将会被二次压缩所造成的图片质量损耗 * * @param targetFile * @param quality, 0~100, recommend 100 * @return * @throws IOException */ public File compressImage(File targetFile, int quality) throws IOException { String filepath = targetFile.getAbsolutePath(); // 1. Calculate scale int scale = 1; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(filepath, o); if (o.outWidth > IMAGE_MAX_WIDTH || o.outHeight > IMAGE_MAX_HEIGHT) { scale = (int) Math.pow( 2.0, (int) Math.round(Math.log(IMAGE_MAX_WIDTH / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); //scale = 2; } Log.d(TAG, scale + " scale"); // 2. File -> Bitmap (Returning a smaller image) o.inJustDecodeBounds = false; o.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeFile(filepath, o); // 2.1. Resize Bitmap //bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT); // 3. Bitmap -> File writeFile(filepath, bitmap, quality); // 4. Get resized Image File String filePath = getMd5(targetFile.getPath()); File compressedImage = mContext.getFileStreamPath(filePath); return compressedImage; } /** * 保持长宽比缩小Bitmap * * @param bitmap * @param maxWidth * @param maxHeight * @param quality 1~100 * @return */ public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) { int originWidth = bitmap.getWidth(); int originHeight = bitmap.getHeight(); // no need to resize if (originWidth < maxWidth && originHeight < maxHeight) { return bitmap; } int newWidth = originWidth; int newHeight = originHeight; // 若图片过宽, 则保持长宽比缩放图片 if (originWidth > maxWidth) { newWidth = maxWidth; double i = originWidth * 1.0 / maxWidth; newHeight = (int) Math.floor(originHeight / i); bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); } // 若图片过长, 则从中部截取 if (newHeight > maxHeight) { newHeight = maxHeight; int half_diff = (int)((originHeight - maxHeight) / 2.0); bitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth, newHeight); } Log.d(TAG, newWidth + " width"); Log.d(TAG, newHeight + " height"); return bitmap; } }
Java
package com.ch_linghu.fanfoudroid.app; import android.graphics.Bitmap; import android.widget.ImageView; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; public class SimpleImageLoader { public static void display(final ImageView imageView, String url) { imageView.setTag(url); imageView.setImageBitmap(TwitterApplication.mImageLoader .get(url, createImageViewCallback(imageView, url))); } public static ImageLoaderCallback createImageViewCallback(final ImageView imageView, String url) { return new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { if (url.equals(imageView.getTag())) { imageView.setImageBitmap(bitmap); } } }; } }
Java
package com.ch_linghu.fanfoudroid.app; import java.lang.Thread.State; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.http.HttpException; public class LazyImageLoader { private static final String TAG = "ProfileImageCacheManager"; public static final int HANDLER_MESSAGE_ID = 1; public static final String EXTRA_BITMAP = "extra_bitmap"; public static final String EXTRA_IMAGE_URL = "extra_image_url"; private ImageManager mImageManager = new ImageManager( TwitterApplication.mContext); private BlockingQueue<String> mUrlList = new ArrayBlockingQueue<String>(50); private CallbackManager mCallbackManager = new CallbackManager(); private GetImageTask mTask = new GetImageTask(); /** * 取图片, 可能直接从cache中返回, 或下载图片后返回 * * @param url * @param callback * @return */ public Bitmap get(String url, ImageLoaderCallback callback) { Bitmap bitmap = ImageCache.mDefaultBitmap; if (mImageManager.isContains(url)) { bitmap = mImageManager.get(url); } else { // bitmap不存在,启动Task进行下载 mCallbackManager.put(url, callback); startDownloadThread(url); } return bitmap; } private void startDownloadThread(String url) { if (url != null) { addUrlToDownloadQueue(url); } // Start Thread State state = mTask.getState(); if (Thread.State.NEW == state) { mTask.start(); // first start } else if (Thread.State.TERMINATED == state) { mTask = new GetImageTask(); // restart mTask.start(); } } private void addUrlToDownloadQueue(String url) { if (!mUrlList.contains(url)) { try { mUrlList.put(url); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // Low-level interface to get ImageManager public ImageManager getImageManager() { return mImageManager; } private class GetImageTask extends Thread { private volatile boolean mTaskTerminated = false; private static final int TIMEOUT = 3 * 60; private boolean isPermanent = true; @Override public void run() { try { while (!mTaskTerminated) { String url; if (isPermanent) { url = mUrlList.take(); } else { url = mUrlList.poll(TIMEOUT, TimeUnit.SECONDS); // waiting if (null == url) { break; } // no more, shutdown } // Bitmap bitmap = ImageCache.mDefaultBitmap; final Bitmap bitmap = mImageManager.safeGet(url); // use handler to process callback final Message m = handler.obtainMessage(HANDLER_MESSAGE_ID); Bundle bundle = m.getData(); bundle.putString(EXTRA_IMAGE_URL, url); bundle.putParcelable(EXTRA_BITMAP, bitmap); handler.sendMessage(m); } } catch (HttpException ioe) { Log.e(TAG, "Get Image failed, " + ioe.getMessage()); } catch (InterruptedException e) { Log.w(TAG, e.getMessage()); } finally { Log.v(TAG, "Get image task terminated."); mTaskTerminated = true; } } @SuppressWarnings("unused") public boolean isPermanent() { return isPermanent; } @SuppressWarnings("unused") public void setPermanent(boolean isPermanent) { this.isPermanent = isPermanent; } @SuppressWarnings("unused") public void shutDown() throws InterruptedException { mTaskTerminated = true; } } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case HANDLER_MESSAGE_ID: final Bundle bundle = msg.getData(); String url = bundle.getString(EXTRA_IMAGE_URL); Bitmap bitmap = (Bitmap) (bundle.get(EXTRA_BITMAP)); // callback mCallbackManager.call(url, bitmap); break; default: // do nothing. } } }; public interface ImageLoaderCallback { void refresh(String url, Bitmap bitmap); } public static class CallbackManager { private static final String TAG = "CallbackManager"; private ConcurrentHashMap<String, List<ImageLoaderCallback>> mCallbackMap; public CallbackManager() { mCallbackMap = new ConcurrentHashMap<String, List<ImageLoaderCallback>>(); } public void put(String url, ImageLoaderCallback callback) { Log.v(TAG, "url=" + url); if (!mCallbackMap.containsKey(url)) { Log.v(TAG, "url does not exist, add list to map"); mCallbackMap.put(url, new ArrayList<ImageLoaderCallback>()); //mCallbackMap.put(url, Collections.synchronizedList(new ArrayList<ImageLoaderCallback>())); } mCallbackMap.get(url).add(callback); Log.v(TAG, "Add callback to list, count(url)=" + mCallbackMap.get(url).size()); } public void call(String url, Bitmap bitmap) { Log.v(TAG, "call url=" + url); List<ImageLoaderCallback> callbackList = mCallbackMap.get(url); if (callbackList == null) { // FIXME: 有时会到达这里,原因我还没想明白 Log.e(TAG, "callbackList=null"); return; } for (ImageLoaderCallback callback : callbackList) { if (callback != null) { callback.refresh(url, bitmap); } } callbackList.clear(); mCallbackMap.remove(url); } } }
Java
package com.ch_linghu.fanfoudroid.app; import android.graphics.Bitmap; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; public interface ImageCache { public static Bitmap mDefaultBitmap = ImageManager.drawableToBitmap(TwitterApplication.mContext.getResources().getDrawable(R.drawable.user_default_photo)); public Bitmap get(String url); public void put(String url, Bitmap bitmap); }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.data; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class Tweet extends Message implements Parcelable { private static final String TAG = "Tweet"; public com.ch_linghu.fanfoudroid.fanfou.User user; public String source; public String prevId; private int statusType = -1; // @see StatusTable#TYPE_* public void setStatusType(int type) { statusType = type; } public int getStatusType() { return statusType; } public Tweet(){} public static Tweet create(Status status){ Tweet tweet = new Tweet(); tweet.id = status.getId(); //转义符放到getSimpleTweetText里去处理,这里不做处理 tweet.text = status.getText(); tweet.createdAt = status.getCreatedAt(); tweet.favorited = status.isFavorited()?"true":"false"; tweet.truncated = status.isTruncated()?"true":"false"; tweet.inReplyToStatusId = status.getInReplyToStatusId(); tweet.inReplyToUserId = status.getInReplyToUserId(); tweet.inReplyToScreenName = status.getInReplyToScreenName(); tweet.screenName = TextHelper.getSimpleTweetText(status.getUser().getScreenName()); tweet.profileImageUrl = status.getUser().getProfileImageURL().toString(); tweet.userId = status.getUser().getId(); tweet.user = status.getUser(); tweet.thumbnail_pic = status.getThumbnail_pic(); tweet.bmiddle_pic = status.getBmiddle_pic(); tweet.original_pic = status.getOriginal_pic(); tweet.source = TextHelper.getSimpleTweetText(status.getSource()); return tweet; } public static Tweet createFromSearchApi(JSONObject jsonObject) throws JSONException { Tweet tweet = new Tweet(); tweet.id = jsonObject.getString("id") + ""; //转义符放到getSimpleTweetText里去处理,这里不做处理 tweet.text = jsonObject.getString("text"); tweet.createdAt = DateTimeHelper.parseSearchApiDateTime(jsonObject.getString("created_at")); tweet.favorited = jsonObject.getString("favorited"); tweet.truncated = jsonObject.getString("truncated"); tweet.inReplyToStatusId = jsonObject.getString("in_reply_to_status_id"); tweet.inReplyToUserId = jsonObject.getString("in_reply_to_user_id"); tweet.inReplyToScreenName = jsonObject.getString("in_reply_to_screen_name"); tweet.screenName = TextHelper.getSimpleTweetText(jsonObject.getString("from_user")); tweet.profileImageUrl = jsonObject.getString("profile_image_url"); tweet.userId = jsonObject.getString("from_user_id"); tweet.source = TextHelper.getSimpleTweetText(jsonObject.getString("source")); return tweet; } public static String buildMetaText(StringBuilder builder, Date createdAt, String source, String replyTo) { builder.setLength(0); builder.append(DateTimeHelper.getRelativeDate(createdAt)); builder.append(" "); builder.append(TwitterApplication.mContext.getString(R.string.tweet_source_prefix)); builder.append(source); if (!TextUtils.isEmpty(replyTo)) { builder.append(" " + TwitterApplication.mContext.getString(R.string.tweet_reply_to_prefix)); builder.append(replyTo); builder.append(TwitterApplication.mContext.getString(R.string.tweet_reply_to_suffix)); } return builder.toString(); } // For interface Parcelable public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeString(id); out.writeString(text); out.writeValue(createdAt); //Date out.writeString(screenName); out.writeString(favorited); out.writeString(inReplyToStatusId); out.writeString(inReplyToUserId); out.writeString(inReplyToScreenName); out.writeString(screenName); out.writeString(profileImageUrl); out.writeString(thumbnail_pic); out.writeString(bmiddle_pic); out.writeString(original_pic); out.writeString(userId); out.writeString(source); } public static final Parcelable.Creator<Tweet> CREATOR = new Parcelable.Creator<Tweet>() { public Tweet createFromParcel(Parcel in) { return new Tweet(in); } public Tweet[] newArray(int size) { // return new Tweet[size]; throw new UnsupportedOperationException(); } }; public Tweet(Parcel in) { id = in.readString(); text = in.readString(); createdAt = (Date) in.readValue(Date.class.getClassLoader()); screenName = in.readString(); favorited = in.readString(); inReplyToStatusId = in.readString(); inReplyToUserId = in.readString(); inReplyToScreenName = in.readString(); screenName = in.readString(); profileImageUrl = in.readString(); thumbnail_pic = in.readString(); bmiddle_pic = in.readString(); original_pic = in.readString(); userId = in.readString(); source = in.readString(); } @Override public String toString() { return "Tweet [source=" + source + ", id=" + id + ", screenName=" + screenName + ", text=" + text + ", profileImageUrl=" + profileImageUrl + ", createdAt=" + createdAt + ", userId=" + userId + ", favorited=" + favorited + ", inReplyToStatusId=" + inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId + ", inReplyToScreenName=" + inReplyToScreenName + "]"; } }
Java
package com.ch_linghu.fanfoudroid.data; import android.database.Cursor; public interface BaseContent { long insert(); int delete(); int update(); Cursor select(); }
Java
package com.ch_linghu.fanfoudroid.data; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.util.TextHelper; public class Dm extends Message { @SuppressWarnings("unused") private static final String TAG = "Dm"; public boolean isSent; public static Dm create(DirectMessage directMessage, boolean isSent){ Dm dm = new Dm(); dm.id = directMessage.getId(); dm.text = directMessage.getText(); dm.createdAt = directMessage.getCreatedAt(); dm.isSent = isSent; User user = dm.isSent ? directMessage.getRecipient() : directMessage.getSender(); dm.screenName = TextHelper.getSimpleTweetText(user.getScreenName()); dm.userId = user.getId(); dm.profileImageUrl = user.getProfileImageURL().toString(); return dm; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.Date; import android.os.Parcel; import android.os.Parcelable; public class User implements Parcelable { public String id; public String name; public String screenName; public String location; public String description; public String profileImageUrl; public String url; public boolean isProtected; public int followersCount; public String lastStatus; public int friendsCount; public int favoritesCount; public int statusesCount; public Date createdAt; public boolean isFollowing; // public boolean notifications; // public utc_offset public User() {} public static User create(com.ch_linghu.fanfoudroid.fanfou.User u) { User user = new User(); user.id = u.getId(); user.name = u.getName(); user.screenName = u.getScreenName(); user.location = u.getLocation(); user.description = u.getDescription(); user.profileImageUrl = u.getProfileImageURL().toString(); if (u.getURL() != null) { user.url = u.getURL().toString(); } user.isProtected = u.isProtected(); user.followersCount = u.getFollowersCount(); user.lastStatus = u.getStatusText(); user.friendsCount = u.getFriendsCount(); user.favoritesCount = u.getFavouritesCount(); user.statusesCount = u.getStatusesCount(); user.createdAt = u.getCreatedAt(); user.isFollowing = u.isFollowing(); return user; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { boolean[] boolArray = new boolean[] { isProtected, isFollowing }; out.writeString(id); out.writeString(name); out.writeString(screenName); out.writeString(location); out.writeString(description); out.writeString(profileImageUrl); out.writeString(url); out.writeBooleanArray(boolArray); out.writeInt(friendsCount); out.writeInt(followersCount); out.writeInt(statusesCount); } public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel in) { return new User(in); } public User[] newArray(int size) { // return new User[size]; throw new UnsupportedOperationException(); } }; public User(Parcel in){ boolean[] boolArray = new boolean[]{isProtected, isFollowing}; id = in.readString(); name = in.readString(); screenName = in.readString(); location = in.readString(); description = in.readString(); profileImageUrl = in.readString(); url = in.readString(); in.readBooleanArray(boolArray); friendsCount = in.readInt(); followersCount = in.readInt(); statusesCount = in.readInt(); isProtected = boolArray[0]; isFollowing = boolArray[1]; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.Date; public class Message { public String id; public String screenName; public String text; public String profileImageUrl; public Date createdAt; public String userId; public String favorited; public String truncated; public String inReplyToStatusId; public String inReplyToUserId; public String inReplyToScreenName; public String thumbnail_pic; public String bmiddle_pic; public String original_pic; }
Java
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.hardware.SensorManager; import android.util.Log; import android.widget.RemoteViews; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.service.TwitterService; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class FanfouWidget extends AppWidgetProvider { public final String TAG = "FanfouWidget"; public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.NEXT"; public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.PREV"; private static List<Tweet> tweets; private SensorManager sensorManager; private static int position = 0; class CacheCallback implements ImageLoaderCallback { private RemoteViews updateViews; CacheCallback(RemoteViews updateViews) { this.updateViews = updateViews; } @Override public void refresh(String url, Bitmap bitmap) { updateViews.setImageViewBitmap(R.id.status_image, bitmap); } } @Override public void onUpdate(Context context, AppWidgetManager appwidgetmanager, int[] appWidgetIds) { Log.d(TAG, "onUpdate"); TwitterService.setWidgetStatus(true); // if (!isRunning(context, WidgetService.class.getName())) { // Intent i = new Intent(context, WidgetService.class); // context.startService(i); // } update(context); } private void update(Context context) { fetchMessages(); position = 0; refreshView(context, NEXTACTION); } private TwitterDatabase getDb() { return TwitterApplication.mDb; } public String getUserId() { return TwitterApplication.getMyselfId(); } private void fetchMessages() { if (tweets == null) { tweets = new ArrayList<Tweet>(); } else { tweets.clear(); } Cursor cursor = getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); if (cursor != null) { if (cursor.moveToFirst()) { do { Tweet tweet = StatusTable.parseCursor(cursor); tweets.add(tweet); } while (cursor.moveToNext()); } } Log.d(TAG, "Tweets size " + tweets.size()); } private void refreshView(Context context) { ComponentName fanfouWidget = new ComponentName(context, FanfouWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(fanfouWidget, buildLogin(context)); } private RemoteViews buildLogin(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_initial_layout); updateViews.setTextViewText(R.id.status_text, TextHelper.getSimpleTweetText("请登录")); updateViews.setTextViewText(R.id.status_screen_name,""); updateViews.setTextViewText(R.id.tweet_source,""); updateViews.setTextViewText(R.id.tweet_created_at, ""); return updateViews; } private void refreshView(Context context, String action) { // 某些情况下,tweets会为null if (tweets == null) { fetchMessages(); } // 防止引发IndexOutOfBoundsException if (tweets.size() != 0) { if (action.equals(NEXTACTION)) { --position; } else if (action.equals(PREACTION)) { ++position; } // Log.d(TAG, "Tweets size =" + tweets.size()); if (position >= tweets.size() || position < 0) { position = 0; } // Log.d(TAG, "position=" + position); ComponentName fanfouWidget = new ComponentName(context, FanfouWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(fanfouWidget, buildUpdate(context)); } } public RemoteViews buildUpdate(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_initial_layout); Tweet t = tweets.get(position); Log.d(TAG, "tweet=" + t); updateViews.setTextViewText(R.id.status_screen_name, t.screenName); updateViews.setTextViewText(R.id.status_text, TextHelper.getSimpleTweetText(t.text)); updateViews.setTextViewText(R.id.tweet_source, context.getString(R.string.tweet_source_prefix) + t.source); updateViews.setTextViewText(R.id.tweet_created_at, DateTimeHelper.getRelativeDate(t.createdAt)); updateViews.setImageViewBitmap(R.id.status_image, TwitterApplication.mImageLoader.get( t.profileImageUrl, new CacheCallback(updateViews))); Intent inext = new Intent(context, FanfouWidget.class); inext.setAction(NEXTACTION); PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.btn_next, pinext); Intent ipre = new Intent(context, FanfouWidget.class); ipre.setAction(PREACTION); PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre); Intent write = WriteActivity.createNewTweetIntent(""); PendingIntent piwrite = PendingIntent.getActivity(context, 0, write, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.write_message, piwrite); Intent home = TwitterActivity.createIntent(context); PendingIntent pihome = PendingIntent.getActivity(context, 0, home, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.logo_image, pihome); Intent status = StatusActivity.createIntent(t); PendingIntent pistatus = PendingIntent.getActivity(context, 0, status, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.main_body, pistatus); return updateViews; } @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "OnReceive"); // FIXME: NullPointerException Log.i(TAG, context.getApplicationContext().toString()); if (!TwitterApplication.mApi.isLoggedIn()) { refreshView(context); } else { super.onReceive(context, intent); String action = intent.getAction(); if (NEXTACTION.equals(action) || PREACTION.equals(action)) { refreshView(context, intent.getAction()); } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { update(context); } } } /** * * @param c * @param serviceName * @return */ @Deprecated public boolean isRunning(Context c, String serviceName) { ActivityManager myAM = (ActivityManager) c .getSystemService(Context.ACTIVITY_SERVICE); ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM .getRunningServices(40); // 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办 int servicesSize = runningServices.size(); for (int i = 0; i < servicesSize; i++)// 循环枚举对比 { if (runningServices.get(i).service.getClassName().toString() .equals(serviceName)) { return true; } } return false; } @Override public void onDeleted(Context context, int[] appWidgetIds) { Log.d(TAG, "onDeleted"); } @Override public void onEnabled(Context context) { Log.d(TAG, "onEnabled"); TwitterService.setWidgetStatus(true); } @Override public void onDisabled(Context context) { Log.d(TAG, "onDisabled"); TwitterService.setWidgetStatus(false); } }
Java
package com.ch_linghu.fanfoudroid; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.db.MessageTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.base.Refreshable; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class DmActivity extends BaseActivity implements Refreshable { private static final String TAG = "DmActivity"; // Views. private ListView mTweetList; private Adapter mAdapter; private Adapter mInboxAdapter; private Adapter mSendboxAdapter; Button inbox; Button sendbox; Button newMsg; private int mDMType; private static final int DM_TYPE_ALL = 0; private static final int DM_TYPE_INBOX = 1; private static final int DM_TYPE_SENDBOX = 2; private TextView mProgressText; private NavBar mNavbar; private Feedback mFeedback; // Tasks. private GenericTask mRetrieveTask; private GenericTask mDeleteTask; private TaskListener mDeleteTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_deleting)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mAdapter.refresh(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmDeleteTask"; } }; private TaskListener mRetrieveTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_refreshing)); } @Override public void onProgressUpdate(GenericTask task, Object params) { draw(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = mPreferences.edit(); editor.putLong(Preferences.LAST_DM_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); draw(); goTop(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmRetrieve"; } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS"; public static Intent createIntent() { return createIntent(""); } public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!TextUtils.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(R.layout.dm); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mNavbar.setHeaderTitle("我的私信"); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); bindFooterButtonEvent(); mTweetList = (ListView) findViewById(R.id.tweet_list); mProgressText = (TextView) findViewById(R.id.progress_text); TwitterDatabase db = getDb(); // Mark all as read. db.markAllDmsRead(); setupAdapter(); // Make sure call bindFooterButtonEvent first boolean shouldRetrieve = false; long lastRefreshTime = mPreferences.getLong( Preferences.LAST_DM_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.d(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } // Want to be able to focus on the items with the trackball. // That way, we can navigate up and down by changing item focus. mTweetList.setItemsCanFocus(true); return true; }else{ return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } private static final String SIS_RUNNING_KEY = "running"; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } super.onDestroy(); } // UI helpers. private void bindFooterButtonEvent() { inbox = (Button) findViewById(R.id.inbox); sendbox = (Button) findViewById(R.id.sendbox); newMsg = (Button) findViewById(R.id.new_message); inbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_INBOX) { mDMType = DM_TYPE_INBOX; inbox.setEnabled(false); sendbox.setEnabled(true); mTweetList.setAdapter(mInboxAdapter); mInboxAdapter.refresh(); } } }); sendbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_SENDBOX) { mDMType = DM_TYPE_SENDBOX; inbox.setEnabled(true); sendbox.setEnabled(false); mTweetList.setAdapter(mSendboxAdapter); mSendboxAdapter.refresh(); } } }); newMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(DmActivity.this, WriteDmActivity.class); intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id startActivity(intent); } }); } private void setupAdapter() { Cursor cursor = getDb().fetchAllDms(-1); startManagingCursor(cursor); mAdapter = new Adapter(this, cursor); Cursor inboxCursor = getDb().fetchInboxDms(); startManagingCursor(inboxCursor); mInboxAdapter = new Adapter(this, inboxCursor); Cursor sendboxCursor = getDb().fetchSendboxDms(); startManagingCursor(sendboxCursor); mSendboxAdapter = new Adapter(this, sendboxCursor); mTweetList.setAdapter(mInboxAdapter); registerForContextMenu(mTweetList); inbox.setEnabled(false); } private class DmRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams...params) { List<DirectMessage> dmList; ArrayList<Dm> dms = new ArrayList<Dm>(); TwitterDatabase db = getDb(); //ImageManager imageManager = getImageManager(); String maxId = db.fetchMaxDmId(false); HashSet<String> imageUrls = new HashSet<String>(); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getDirectMessages(paging); } else { dmList = getApi().getDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList)); for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, false); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } maxId = db.fetchMaxDmId(true); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getSentDirectMessages(paging); } else { dmList = getApi().getSentDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, true); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } db.addDms(dms, false); // if (isCancelled()) { // return TaskResult.CANCELLED; // } // // publishProgress(null); // // for (String imageUrl : imageUrls) { // if (!Utils.isEmpty(imageUrl)) { // // Fetch image to cache. // try { // imageManager.put(imageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } // // if (isCancelled()) { // return TaskResult.CANCELLED; // } // } return TaskResult.OK; } } private static class Adapter extends CursorAdapter { public Adapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); // TODO: 可使用: //DM dm = MessageTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME); mTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT); mIsSentColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mIsSentColumn; private int mCreatedAtColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.direct_message, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); view.setTag(holder); return view; } class ViewHolder { public TextView userText; public TextView tweetText; public ImageView profileImage; public TextView metaText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); int isSent = cursor.getInt(mIsSentColumn); String user = cursor.getString(mUserTextColumn); if (0 == isSent) { holder.userText.setText(context .getString(R.string.direct_message_label_from_prefix) + user); } else { holder.userText.setText(context .getString(R.string.direct_message_label_to_prefix) + user); } TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage .setImageBitmap(TwitterApplication.mImageLoader .get(profileImageUrl, new ImageLoaderCallback(){ @Override public void refresh(String url, Bitmap bitmap) { Adapter.this.refresh(); } })); } try { holder.metaText.setText(DateTimeHelper .getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER .parse(cursor.getString(mCreatedAtColumn)))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } } public void refresh() { getCursor().requery(); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除 // case OPTIONS_MENU_ID_REFRESH: // doRetrieve(); // return true; case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; } return super.onOptionsItemSelected(item); } private static final int CONTEXT_REPLY_ID = 0; private static final int CONTEXT_DELETE_ID = 1; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Cursor cursor = (Cursor) mAdapter.getItem(info.position); if (cursor == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_REPLY_ID: String user_id = cursor.getString(cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_ID)); Intent intent = WriteDmActivity.createIntent(user_id); startActivity(intent); return true; case CONTEXT_DELETE_ID: int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID); String id = cursor.getString(idIndex); doDestroy(id); return true; default: return super.onContextItemSelected(item); } } private void doDestroy(String id) { Log.d(TAG, "Attempting delete."); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mDeleteTask = new DmDeleteTask(); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } private class DmDeleteTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams...params) { TaskParams param = params[0]; try { String id = param.getString("id"); DirectMessage directMessage = getApi().destroyDirectMessage(id); Dm.create(directMessage, false); getDb().deleteDm(id); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mRetrieveTask = new DmRetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); } } public void goTop() { mTweetList.setSelection(0); } public void draw() { mAdapter.refresh(); mInboxAdapter.refresh(); mSendboxAdapter.refresh(); } private void updateProgress(String msg) { mProgressText.setText(msg); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; //TODO: 数据来源换成 getFavorites() public class FavoritesActivity extends TwitterCursorBaseActivity { private static final String TAG = "FavoritesActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FAVORITES"; private static final String USER_ID = "userid"; private static final String USER_NAME = "userName"; private static final int DIALOG_WRITE_ID = 0; private String userId = null; private String userName = null; public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)){ mNavbar.setHeaderTitle(getActivityTitle()); return true; }else{ return false; } } public static Intent createNewTaskIntent(String userId, String userName) { Intent intent = createIntent(userId, userName); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override protected Cursor fetchMessages() { // TODO Auto-generated method stub return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_FAVORITE); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub String template = getString(R.string.page_title_favorites); String who; if (getUserId().equals(TwitterApplication.getMyselfId())){ who = "我"; }else{ who = getUserName(); } return MessageFormat.format(template, who); } @Override protected void markAllRead() { // TODO Auto-generated method stub getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_FAVORITE); } // hasRetrieveListTask interface @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_FAVORITE, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_FAVORITE); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { if (maxId != null){ return getApi().getFavorites(getUserId(), new Paging(maxId)); }else{ return getApi().getFavorites(getUserId()); } } @Override public String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_FAVORITE); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { Paging paging = new Paging(1, 20); paging.setMaxId(minId); return getApi().getFavorites(getUserId(), paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_FAVORITE; } @Override public String getUserId() { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null){ userId = extras.getString(USER_ID); } else { userId = TwitterApplication.getMyselfId(); } return userId; } public String getUserName(){ Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null){ userName = extras.getString(USER_NAME); } else { userName = TwitterApplication.getMyselfName(); } return userName; } }
Java
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; public class FollowingActivity extends UserArrayBaseActivity { private ListView mUserList; private UserArrayAdapter mAdapter; private String userId; private String userName; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING"; private static final String USER_ID = "userId"; private static final String USER_NAME = "userName"; private int currentPage=1; String myself=""; @Override protected boolean _onCreate(Bundle savedInstanceState) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { // 获取登录用户id userId=TwitterApplication.getMyselfId(); userName = TwitterApplication.getMyselfName(); } if(super._onCreate(savedInstanceState)){ myself = TwitterApplication.getMyselfId(); if(getUserId()==myself){ mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), "我")); } else { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), userName)); } return true; }else{ return false; } } /* * 添加取消关注按钮 * @see com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo) */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if(getUserId()==myself){ AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); menu.add(0,CONTENT_DEL_FRIEND,0,getResources().getString(R.string.cmenu_user_addfriend_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_friend_suffix)); } } public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override public Paging getNextPage() { currentPage+=1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { return new Paging(this.currentPage); } @Override protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException { return getApi().getFriendsStatuses(userId, page); } }
Java
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.db.UserInfoTable; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; /** * * @author Dino 2011-02-26 */ // public class ProfileActivity extends WithHeaderActivity { public class ProfileActivity extends BaseActivity { private static final String TAG = "ProfileActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.PROFILE"; private static final String STATUS_COUNT = "status_count"; private static final String EXTRA_USER = "user"; private static final String FANFOUROOT = "http://fanfou.com/"; private static final String USER_ID = "userid"; private static final String USER_NAME = "userName"; private GenericTask profileInfoTask;// 获取用户信息 private GenericTask setFollowingTask; private GenericTask cancelFollowingTask; private String userId; private String userName; private String myself; private User profileInfo;// 用户信息 private ImageView profileImageView;// 头像 private TextView profileName;// 名称 private TextView profileScreenName;// 昵称 private TextView userLocation;// 地址 private TextView userUrl;// url private TextView userInfo;// 自述 private TextView friendsCount;// 好友 private TextView followersCount;// 收听 private TextView statusCount;// 消息 private TextView favouritesCount;// 收藏 private TextView isFollowingText;// 是否关注 private Button followingBtn;// 收听/取消关注按钮 private Button sendMentionBtn;// 发送留言按钮 private Button sendDmBtn;// 发送私信按钮 private ProgressDialog dialog; // 请稍候 private RelativeLayout friendsLayout; private LinearLayout followersLayout; private LinearLayout statusesLayout; private LinearLayout favouritesLayout; private NavBar mNavBar; private Feedback mFeedback; private TwitterDatabase db; public static Intent createIntent(String userId) { Intent intent = new Intent(LAUNCH_ACTION); intent.putExtra(USER_ID, userId); return intent; } private ImageLoaderCallback callback = new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { profileImageView.setImageBitmap(bitmap); } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "OnCreate start"); if (super._onCreate(savedInstanceState)) { setContentView(R.layout.profile); Intent intent = getIntent(); Bundle extras = intent.getExtras(); myself = TwitterApplication.getMyselfId(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { this.userId = myself; this.userName = TwitterApplication.getMyselfName(); } Uri data = intent.getData(); if (data != null) { userId = data.getLastPathSegment(); } // 初始化控件 initControls(); Log.d(TAG, "the userid is " + userId); db = this.getDb(); draw(); return true; } else { return false; } } private void initControls() { mNavBar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mNavBar.setHeaderTitle(""); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); sendMentionBtn = (Button) findViewById(R.id.sendmetion_btn); sendDmBtn = (Button) findViewById(R.id.senddm_btn); profileImageView = (ImageView) findViewById(R.id.profileimage); profileName = (TextView) findViewById(R.id.profilename); profileScreenName = (TextView) findViewById(R.id.profilescreenname); userLocation = (TextView) findViewById(R.id.user_location); userUrl = (TextView) findViewById(R.id.user_url); userInfo = (TextView) findViewById(R.id.tweet_user_info); friendsCount = (TextView) findViewById(R.id.friends_count); followersCount = (TextView) findViewById(R.id.followers_count); TextView friendsCountTitle = (TextView) findViewById(R.id.friends_count_title); TextView followersCountTitle = (TextView) findViewById(R.id.followers_count_title); String who; if (userId.equals(myself)) { who = "我"; } else { who = "ta"; } friendsCountTitle.setText(MessageFormat.format( getString(R.string.profile_friends_count_title), who)); followersCountTitle.setText(MessageFormat.format( getString(R.string.profile_followers_count_title), who)); statusCount = (TextView) findViewById(R.id.statuses_count); favouritesCount = (TextView) findViewById(R.id.favourites_count); friendsLayout = (RelativeLayout) findViewById(R.id.friendsLayout); followersLayout = (LinearLayout) findViewById(R.id.followersLayout); statusesLayout = (LinearLayout) findViewById(R.id.statusesLayout); favouritesLayout = (LinearLayout) findViewById(R.id.favouritesLayout); isFollowingText = (TextView) findViewById(R.id.isfollowing_text); followingBtn = (Button) findViewById(R.id.following_btn); // 为按钮面板添加事件 friendsLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } String showName; if (!TextUtils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = FollowingActivity .createIntent(userId, showName); intent.setClass(ProfileActivity.this, FollowingActivity.class); startActivity(intent); } }); followersLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } String showName; if (!TextUtils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = FollowersActivity .createIntent(userId, showName); intent.setClass(ProfileActivity.this, FollowersActivity.class); startActivity(intent); } }); statusesLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } String showName; if (!TextUtils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = UserTimelineActivity.createIntent( profileInfo.getId(), showName); launchActivity(intent); } }); favouritesLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } Intent intent = FavoritesActivity.createIntent(userId, profileInfo.getName()); intent.setClass(ProfileActivity.this, FavoritesActivity.class); startActivity(intent); } }); // 刷新 View.OnClickListener refreshListener = new View.OnClickListener() { @Override public void onClick(View v) { doGetProfileInfo(); } }; mNavBar.getRefreshButton().setOnClickListener(refreshListener); } private void draw() { Log.d(TAG, "draw"); bindProfileInfo(); // doGetProfileInfo(); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop."); } /** * 从数据库获取,如果数据库不存在则创建 */ private void bindProfileInfo() { dialog = ProgressDialog.show(ProfileActivity.this, "请稍候", "正在加载信息..."); if (null != db && db.existsUser(userId)) { Cursor cursor = db.getUserInfoById(userId); profileInfo = User.parseUser(cursor); cursor.close(); if (profileInfo == null) { Log.w(TAG, "cannot get userinfo from userinfotable the id is" + userId); } bindControl(); if (dialog != null) { dialog.dismiss(); } } else { doGetProfileInfo(); } } private void doGetProfileInfo() { mFeedback.start(""); if (profileInfoTask != null && profileInfoTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { profileInfoTask = new GetProfileTask(); profileInfoTask.setListener(profileInfoTaskListener); TaskParams params = new TaskParams(); profileInfoTask.execute(params); } } private void bindControl() { if (profileInfo.getId().equals(myself)) { sendMentionBtn.setVisibility(View.GONE); sendDmBtn.setVisibility(View.GONE); } else { // 发送留言 sendMentionBtn.setVisibility(View.VISIBLE); sendMentionBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewTweetIntent(String .format("@%s ", profileInfo.getScreenName())); startActivity(intent); } }); // 发送私信 sendDmBtn.setVisibility(View.VISIBLE); sendDmBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteDmActivity.createIntent(profileInfo .getId()); startActivity(intent); } }); } if (userId.equals(myself)) { mNavBar.setHeaderTitle("我" + getString(R.string.cmenu_user_profile_prefix)); } else { mNavBar.setHeaderTitle(profileInfo.getScreenName() + getString(R.string.cmenu_user_profile_prefix)); } profileImageView .setImageBitmap(TwitterApplication.mImageLoader .get(profileInfo.getProfileImageURL().toString(), callback)); profileName.setText(profileInfo.getId()); profileScreenName.setText(profileInfo.getScreenName()); if (profileInfo.getId().equals(myself)) { isFollowingText.setText(R.string.profile_isyou); followingBtn.setVisibility(View.GONE); } else if (profileInfo.isFollowing()) { isFollowingText.setText(R.string.profile_isfollowing); followingBtn.setVisibility(View.VISIBLE); followingBtn.setText(R.string.user_label_unfollow); followingBtn.setOnClickListener(cancelFollowingListener); followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources() .getDrawable(R.drawable.ic_unfollow), null, null, null); } else { isFollowingText.setText(R.string.profile_notfollowing); followingBtn.setVisibility(View.VISIBLE); followingBtn.setText(R.string.user_label_follow); followingBtn.setOnClickListener(setfollowingListener); followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources() .getDrawable(R.drawable.ic_follow), null, null, null); } String location = profileInfo.getLocation(); if (location == null || location.length() == 0) { location = getResources().getString(R.string.profile_location_null); } userLocation.setText(location); if (profileInfo.getURL() != null) { userUrl.setText(profileInfo.getURL().toString()); } else { userUrl.setText(FANFOUROOT + profileInfo.getId()); } String description = profileInfo.getDescription(); if (description == null || description.length() == 0) { description = getResources().getString( R.string.profile_description_null); } userInfo.setText(description); friendsCount.setText(String.valueOf(profileInfo.getFriendsCount())); followersCount.setText(String.valueOf(profileInfo.getFollowersCount())); statusCount.setText(String.valueOf(profileInfo.getStatusesCount())); favouritesCount .setText(String.valueOf(profileInfo.getFavouritesCount())); } private TaskListener profileInfoTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { // 加载成功 if (result == TaskResult.OK) { mFeedback.success(""); // 绑定控件 bindControl(); if (dialog != null) { dialog.dismiss(); } } } @Override public String getName() { return "GetProfileInfo"; } }; /** * 更新数据库中的用户 * * @return */ private boolean updateUser() { ContentValues v = new ContentValues(); v.put(BaseColumns._ID, profileInfo.getName()); v.put(UserInfoTable.FIELD_USER_NAME, profileInfo.getName()); v.put(UserInfoTable.FIELD_USER_SCREEN_NAME, profileInfo.getScreenName()); v.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, profileInfo .getProfileImageURL().toString()); v.put(UserInfoTable.FIELD_LOCALTION, profileInfo.getLocation()); v.put(UserInfoTable.FIELD_DESCRIPTION, profileInfo.getDescription()); v.put(UserInfoTable.FIELD_PROTECTED, profileInfo.isProtected()); v.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, profileInfo.getFollowersCount()); v.put(UserInfoTable.FIELD_LAST_STATUS, profileInfo.getStatusSource()); v.put(UserInfoTable.FIELD_FRIENDS_COUNT, profileInfo.getFriendsCount()); v.put(UserInfoTable.FIELD_FAVORITES_COUNT, profileInfo.getFavouritesCount()); v.put(UserInfoTable.FIELD_STATUSES_COUNT, profileInfo.getStatusesCount()); v.put(UserInfoTable.FIELD_FOLLOWING, profileInfo.isFollowing()); if (profileInfo.getURL() != null) { v.put(UserInfoTable.FIELD_URL, profileInfo.getURL().toString()); } return db.updateUser(profileInfo.getId(), v); } /** * 获取用户信息task * * @author Dino * */ private class GetProfileTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.v(TAG, "get profile task"); try { profileInfo = getApi().showUser(userId); mFeedback.update(80); if (profileInfo != null) { if (null != db && !db.existsUser(userId)) { com.ch_linghu.fanfoudroid.data.User userinfodb = profileInfo .parseUser(); db.createUserInfo(userinfodb); } else { // 更新用户 updateUser(); } } } catch (HttpException e) { Log.e(TAG, e.getMessage()); return TaskResult.FAILED; } mFeedback.update(99); return TaskResult.OK; } } /** * 设置关注监听 */ private OnClickListener setfollowingListener = new OnClickListener() { @Override public void onClick(View v) { Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this) .setTitle("关注提示").setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(setFollowingTaskLinstener); TaskParams params = new TaskParams(); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } }; /* * 取消关注监听 */ private OnClickListener cancelFollowingListener = new OnClickListener() { @Override public void onClick(View v) { Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this) .setTitle("关注提示").setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask .setListener(cancelFollowingTaskLinstener); TaskParams params = new TaskParams(); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } }; /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener setFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { followingBtn.setText("取消关注"); isFollowingText.setText(getResources().getString( R.string.profile_isfollowing)); followingBtn.setOnClickListener(cancelFollowingListener); Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { followingBtn.setText("添加关注"); isFollowingText.setText(getResources().getString( R.string.profile_notfollowing)); followingBtn.setOnClickListener(setfollowingListener); Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; }
Java
package com.ch_linghu.fanfoudroid.dao; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Log; import com.ch_linghu.fanfoudroid.dao.SQLiteTemplate.RowMapper; import com.ch_linghu.fanfoudroid.data2.Photo; import com.ch_linghu.fanfoudroid.data2.Status; import com.ch_linghu.fanfoudroid.data2.User; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.db2.FanContent; import com.ch_linghu.fanfoudroid.db2.FanContent.StatusesPropertyTable; import com.ch_linghu.fanfoudroid.db2.FanDatabase; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.db2.FanContent.*; public class StatusDAO { private static final String TAG = "StatusDAO"; private SQLiteTemplate mSqlTemplate; public StatusDAO(Context context) { mSqlTemplate = new SQLiteTemplate(FanDatabase.getInstance(context) .getSQLiteOpenHelper()); } /** * Insert a Status * * 若报 SQLiteconstraintexception 异常, 检查是否某not null字段为空 * * @param status * @param isUnread * @return */ public long insertStatus(Status status) { if (!isExists(status)) { return mSqlTemplate.getDb(true).insert(StatusesTable.TABLE_NAME, null, statusToContentValues(status)); } else { Log.e(TAG, status.getId() + " is exists."); return -1; } } // TODO: public int insertStatuses(List<Status> statuses) { int result = 0; SQLiteDatabase db = mSqlTemplate.getDb(true); try { db.beginTransaction(); for (int i = statuses.size() - 1; i >= 0; i--) { Status status = statuses.get(i); long id = db.insertWithOnConflict(StatusesTable.TABLE_NAME, null, statusToContentValues(status), SQLiteDatabase.CONFLICT_IGNORE); if (-1 == id) { Log.e(TAG, "cann't insert the tweet : " + status.toString()); } else { ++result; Log.v(TAG, String.format( "Insert a status into database : %s", status.toString())); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } return result; } /** * Delete a status * * @param statusId * @param owner_id * owner id * @param type * status type * @return * @see StatusDAO#deleteStatus(Status) */ public int deleteStatus(String statusId, String owner_id, int type) { //FIXME: 数据模型改变后这里的逻辑需要完全重写,目前仅保证编译可通过 String where = StatusesTable.Columns.ID + " =? "; String[] binds; if (!TextUtils.isEmpty(owner_id)) { where += " AND " + StatusesPropertyTable.Columns.OWNER_ID + " = ? "; binds = new String[] { statusId, owner_id }; } else { binds = new String[] { statusId }; } if (-1 != type) { where += " AND " + StatusesPropertyTable.Columns.TYPE + " = " + type; } return mSqlTemplate.getDb(true).delete(StatusesTable.TABLE_NAME, where.toString(), binds); } /** * Delete a Status * * @param status * @return * @see StatusDAO#deleteStatus(String, String, int) */ public int deleteStatus(Status status) { return deleteStatus(status.getId(), status.getOwnerId(), status.getType()); } /** * Find a status by status ID * * @param statusId * @return */ public Status fetchStatus(String statusId) { return mSqlTemplate.queryForObject(mRowMapper, StatusesTable.TABLE_NAME, null, StatusesTable.Columns.ID + " = ?", new String[] { statusId }, null, null, "created_at DESC", "1"); } /** * Find user's statuses * * @param userId * user id * @param statusType * status type, see {@link StatusTable#TYPE_USER}... * @return list of statuses */ public List<Status> fetchStatuses(String userId, int statusType) { return mSqlTemplate.queryForList(mRowMapper, FanContent.StatusesTable.TABLE_NAME, null, StatusesPropertyTable.Columns.OWNER_ID + " = ? AND " + StatusesPropertyTable.Columns.TYPE + " = " + statusType, new String[] { userId }, null, null, "created_at DESC", null); } /** * @see StatusDAO#fetchStatuses(String, int) */ public List<Status> fetchStatuses(String userId, String statusType) { return fetchStatuses(userId, Integer.parseInt(statusType)); } /** * Update by using {@link ContentValues} * * @param statusId * @param newValues * @return */ public int updateStatus(String statusId, ContentValues values) { return mSqlTemplate.updateById(FanContent.StatusesTable.TABLE_NAME, statusId, values); } /** * Update by using {@link Status} * * @param status * @return */ public int updateStatus(Status status) { return updateStatus(status.getId(), statusToContentValues(status)); } /** * Check if status exists * * FIXME: 取消使用Query * * @param status * @return */ public boolean isExists(Status status) { StringBuilder sql = new StringBuilder(); sql.append("SELECT COUNT(*) FROM ").append(FanContent.StatusesTable.TABLE_NAME) .append(" WHERE ").append(StatusesTable.Columns.ID).append(" =? AND ") .append(StatusesPropertyTable.Columns.OWNER_ID).append(" =? AND ") .append(StatusesPropertyTable.Columns.TYPE).append(" = ") .append(status.getType()); return mSqlTemplate.isExistsBySQL(sql.toString(), new String[] { status.getId(), status.getUser().getId() }); } /** * Status -> ContentValues * * @param status * @param isUnread * @return */ private ContentValues statusToContentValues(Status status) { final ContentValues v = new ContentValues(); v.put(StatusesTable.Columns.ID, status.getId()); v.put(StatusesPropertyTable.Columns.TYPE, status.getType()); v.put(StatusesTable.Columns.TEXT, status.getText()); v.put(StatusesPropertyTable.Columns.OWNER_ID, status.getOwnerId()); v.put(StatusesTable.Columns.FAVORITED, status.isFavorited() + ""); v.put(StatusesTable.Columns.TRUNCATED, status.isTruncated()); // TODO: v.put(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId()); v.put(StatusesTable.Columns.IN_REPLY_TO_USER_ID, status.getInReplyToUserId()); // v.put(StatusTable.Columns.IN_REPLY_TO_SCREEN_NAME, // status.getInReplyToScreenName()); // v.put(IS_REPLY, status.isReply()); v.put(StatusesTable.Columns.CREATED_AT, TwitterDatabase.DB_DATE_FORMATTER.format(status.getCreatedAt())); v.put(StatusesTable.Columns.SOURCE, status.getSource()); // v.put(StatusTable.Columns.IS_UNREAD, status.isUnRead()); final User user = status.getUser(); if (user != null) { v.put(UserTable.Columns.USER_ID, user.getId()); v.put(UserTable.Columns.SCREEN_NAME, user.getScreenName()); v.put(UserTable.Columns.PROFILE_IMAGE_URL, user.getProfileImageUrl()); } final Photo photo = status.getPhotoUrl(); /*if (photo != null) { v.put(StatusTable.Columns.PIC_THUMB, photo.getThumburl()); v.put(StatusTable.Columns.PIC_MID, photo.getImageurl()); v.put(StatusTable.Columns.PIC_ORIG, photo.getLargeurl()); }*/ return v; } private static final RowMapper<Status> mRowMapper = new RowMapper<Status>() { @Override public Status mapRow(Cursor cursor, int rowNum) { Photo photo = new Photo(); /*photo.setImageurl(cursor.getString(cursor .getColumnIndex(StatusTable.Columns.PIC_MID))); photo.setLargeurl(cursor.getString(cursor .getColumnIndex(StatusTable.Columns.PIC_ORIG))); photo.setThumburl(cursor.getString(cursor .getColumnIndex(StatusTable.Columns.PIC_THUMB))); */ User user = new User(); user.setScreenName(cursor.getString(cursor .getColumnIndex(UserTable.Columns.SCREEN_NAME))); user.setId(cursor.getString(cursor .getColumnIndex(UserTable.Columns.USER_ID))); user.setProfileImageUrl(cursor.getString(cursor .getColumnIndex(UserTable.Columns.PROFILE_IMAGE_URL))); Status status = new Status(); status.setPhotoUrl(photo); status.setUser(user); status.setOwnerId(cursor.getString(cursor .getColumnIndex(StatusesPropertyTable.Columns.OWNER_ID))); // TODO: 将数据库中的statusType改成Int类型 status.setType(cursor.getInt(cursor .getColumnIndex(StatusesPropertyTable.Columns.TYPE))); status.setId(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.ID))); status.setCreatedAt(DateTimeHelper.parseDateTimeFromSqlite(cursor .getString(cursor.getColumnIndex(StatusesTable.Columns.CREATED_AT)))); // TODO: 更改favorite 在数据库类型为boolean后改为 " != 0 " status.setFavorited(cursor.getString( cursor.getColumnIndex(StatusesTable.Columns.FAVORITED)) .equals("true")); status.setText(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.TEXT))); status.setSource(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.SOURCE))); // status.setInReplyToScreenName(cursor.getString(cursor // .getColumnIndex(StatusTable.IN_REPLY_TO_SCREEN_NAME))); status.setInReplyToStatusId(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID))); status.setInReplyToUserId(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_USER_ID))); status.setTruncated(cursor.getInt(cursor .getColumnIndex(StatusesTable.Columns.TRUNCATED)) != 0); // status.setUnRead(cursor.getInt(cursor // .getColumnIndex(StatusTable.Columns.IS_UNREAD)) != 0); return status; } }; }
Java
package com.ch_linghu.fanfoudroid.dao; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Database Helper * * @see SQLiteDatabase */ public class SQLiteTemplate { /** * Default Primary key */ protected String mPrimaryKey = "_id"; /** * SQLiteDatabase Open Helper */ protected SQLiteOpenHelper mDatabaseOpenHelper; /** * Construct * * @param databaseOpenHelper */ public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper) { mDatabaseOpenHelper = databaseOpenHelper; } /** * Construct * * @param databaseOpenHelper * @param primaryKey */ public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper, String primaryKey) { this(databaseOpenHelper); setPrimaryKey(primaryKey); } /** * 根据某一个字段和值删除一行数据, 如 name="jack" * * @param table * @param field * @param value * @return */ public int deleteByField(String table, String field, String value) { return getDb(true).delete(table, field + "=?", new String[] { value }); } /** * 根据主键删除一行数据 * * @param table * @param id * @return */ public int deleteById(String table, String id) { return deleteByField(table, mPrimaryKey, id); } /** * 根据主键更新一行数据 * * @param table * @param id * @param values * @return */ public int updateById(String table, String id, ContentValues values) { return getDb(true).update(table, values, mPrimaryKey + "=?", new String[] { id }); } /** * 根据主键查看某条数据是否存在 * * @param table * @param id * @return */ public boolean isExistsById(String table, String id) { return isExistsByField(table, mPrimaryKey, id); } /** * 根据某字段/值查看某条数据是否存在 * * @param status * @return */ public boolean isExistsByField(String table, String field, String value) { StringBuilder sql = new StringBuilder(); sql.append("SELECT COUNT(*) FROM ").append(table).append(" WHERE ") .append(field).append(" =?"); return isExistsBySQL(sql.toString(), new String[] { value }); } /** * 使用SQL语句查看某条数据是否存在 * * @param sql * @param selectionArgs * @return */ public boolean isExistsBySQL(String sql, String[] selectionArgs) { boolean result = false; final Cursor c = getDb(false).rawQuery(sql, selectionArgs); try { if (c.moveToFirst()) { result = (c.getInt(0) > 0); } } finally { c.close(); } return result; } /** * Query for cursor * * @param <T> * @param rowMapper * @return a cursor * * @see SQLiteDatabase#query(String, String[], String, String[], String, * String, String, String) */ public <T> T queryForObject(RowMapper<T> rowMapper, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { T object = null; final Cursor c = getDb(false).query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); try { if (c.moveToFirst()) { object = rowMapper.mapRow(c, c.getCount()); } } finally { c.close(); } return object; } /** * Query for list * * @param <T> * @param rowMapper * @return list of object * * @see SQLiteDatabase#query(String, String[], String, String[], String, * String, String, String) */ public <T> List<T> queryForList(RowMapper<T> rowMapper, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { List<T> list = new ArrayList<T>(); final Cursor c = getDb(false).query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); try { while (c.moveToNext()) { list.add(rowMapper.mapRow(c, 1)); } } finally { c.close(); } return list; } /** * Get Primary Key * * @return */ public String getPrimaryKey() { return mPrimaryKey; } /** * Set Primary Key * * @param primaryKey */ public void setPrimaryKey(String primaryKey) { this.mPrimaryKey = primaryKey; } /** * Get Database Connection * * @param writeable * @return * @see SQLiteOpenHelper#getWritableDatabase(); * @see SQLiteOpenHelper#getReadableDatabase(); */ public SQLiteDatabase getDb(boolean writeable) { if (writeable) { return mDatabaseOpenHelper.getWritableDatabase(); } else { return mDatabaseOpenHelper.getReadableDatabase(); } } /** * Some as Spring JDBC RowMapper * * @see org.springframework.jdbc.core.RowMapper * @see com.ch_linghu.fanfoudroid.db.dao.SqliteTemplate * @param <T> */ public interface RowMapper<T> { public T mapRow(Cursor cursor, int rowNum); } }
Java
package com.ch_linghu.fanfoudroid.db2; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.ch_linghu.fanfoudroid.db2.FanContent.*; public class FanDatabase { private static final String TAG = FanDatabase.class.getSimpleName(); /** * SQLite Database file name */ private static final String DATABASE_NAME = "fanfoudroid.db"; /** * Database Version */ public static final int DATABASE_VERSION = 2; /** * self instance */ private static FanDatabase sInstance = null; /** * SQLiteDatabase Open Helper */ private DatabaseHelper mOpenHelper = null; /** * SQLiteOpenHelper */ private static class DatabaseHelper extends SQLiteOpenHelper { // Construct public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "Create Database."); // TODO: create tables createAllTables(db); createAllIndexes(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "Upgrade Database."); // TODO: DROP TABLE onCreate(db); } } /** * Construct * * @param context */ private FanDatabase(Context context) { mOpenHelper = new DatabaseHelper(context); } /** * Get Database * * @param context * @return */ public static synchronized FanDatabase getInstance(Context context) { if (null == sInstance) { sInstance = new FanDatabase(context); } return sInstance; } /** * Get SQLiteDatabase Open Helper * * @return */ public SQLiteOpenHelper getSQLiteOpenHelper() { return mOpenHelper; } /** * Get Database Connection * * @param writeable * @return */ public SQLiteDatabase getDb(boolean writeable) { if (writeable) { return mOpenHelper.getWritableDatabase(); } else { return mOpenHelper.getReadableDatabase(); } } /** * Close Database */ public void close() { if (null != sInstance) { mOpenHelper.close(); sInstance = null; } } // Create All tables private static void createAllTables(SQLiteDatabase db) { db.execSQL(StatusesTable.getCreateSQL()); db.execSQL(StatusesPropertyTable.getCreateSQL()); db.execSQL(UserTable.getCreateSQL()); db.execSQL(DirectMessageTable.getCreateSQL()); db.execSQL(FollowRelationshipTable.getCreateSQL()); db.execSQL(TrendTable.getCreateSQL()); db.execSQL(SavedSearchTable.getCreateSQL()); } private static void dropAllTables(SQLiteDatabase db) { db.execSQL(StatusesTable.getDropSQL()); db.execSQL(StatusesPropertyTable.getDropSQL()); db.execSQL(UserTable.getDropSQL()); db.execSQL(DirectMessageTable.getDropSQL()); db.execSQL(FollowRelationshipTable.getDropSQL()); db.execSQL(TrendTable.getDropSQL()); db.execSQL(SavedSearchTable.getDropSQL()); } private static void resetAllTables(SQLiteDatabase db, int oldVersion, int newVersion) { try { dropAllTables(db); } catch (SQLException e) { Log.e(TAG, "resetAllTables ERROR!"); } createAllTables(db); } //indexes private static void createAllIndexes(SQLiteDatabase db) { db.execSQL(StatusesTable.getCreateIndexSQL()); } }
Java
package com.ch_linghu.fanfoudroid.db2; import java.util.zip.CheckedOutputStream; import android.R.color; public abstract class FanContent { /** * 消息表 消息表存放消息本身 * * @author phoenix * */ public static class StatusesTable { public static final String TABLE_NAME = "t_statuses"; public static class Columns { public static final String ID = "_id"; public static final String STATUS_ID = "status_id"; public static final String AUTHOR_ID = "author_id"; public static final String TEXT = "text"; public static final String SOURCE = "source"; public static final String CREATED_AT = "created_at"; public static final String TRUNCATED = "truncated"; public static final String FAVORITED = "favorited"; public static final String PHOTO_URL = "photo_url"; public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id"; public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id"; public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.ID + " INTEGER PRIMARY KEY, " + Columns.STATUS_ID + " TEXT UNIQUE NOT NULL, " + Columns.AUTHOR_ID + " TEXT, " + Columns.TEXT + " TEXT, " + Columns.SOURCE + " TEXT, " + Columns.CREATED_AT + " INT, " + Columns.TRUNCATED + " INT DEFAULT 0, " + Columns.FAVORITED + " INT DEFAULT 0, " + Columns.PHOTO_URL + " TEXT, " + Columns.IN_REPLY_TO_STATUS_ID + " TEXT, " + Columns.IN_REPLY_TO_USER_ID + " TEXT, " + Columns.IN_REPLY_TO_SCREEN_NAME + " TEXT " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.ID, Columns.STATUS_ID, Columns.AUTHOR_ID, Columns.TEXT, Columns.SOURCE, Columns.CREATED_AT, Columns.TRUNCATED, Columns.FAVORITED, Columns.PHOTO_URL, Columns.IN_REPLY_TO_STATUS_ID, Columns.IN_REPLY_TO_USER_ID, Columns.IN_REPLY_TO_SCREEN_NAME }; } public static String getCreateIndexSQL() { String createIndexSQL = "CREATE INDEX " + TABLE_NAME + "_idx ON " + TABLE_NAME + " ( " + getIndexColumns()[1] + " );"; return createIndexSQL; } } /** * 消息属性表 每一条消息所属类别、所有者等信息 消息ID(外键) 所有者(随便看看的所有者为空) * 消息类别(随便看看/首页(自己及自己好友)/个人(仅自己)/收藏/照片) * * @author phoenix * */ public static class StatusesPropertyTable { public static final String TABLE_NAME = "t_statuses_property"; public static class Columns { public static final String ID = "_id"; public static final String STATUS_ID = "status_id"; public static final String OWNER_ID = "owner_id"; public static final String TYPE = "type"; public static final String SEQUENCE_FLAG = "sequence_flag"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.ID + " INTEGER PRIMARY KEY, " + Columns.STATUS_ID + " TEXT NOT NULL, " + Columns.OWNER_ID + " TEXT, " + Columns.TYPE + " INT, " + Columns.SEQUENCE_FLAG + " INT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.ID, Columns.STATUS_ID, Columns.OWNER_ID, Columns.TYPE, Columns.SEQUENCE_FLAG, Columns.LOAD_TIME }; } } /** * User表 包括User的基本信息和扩展信息(每次获得最新User信息都update进User表) * 每次更新User表时希望能更新LOAD_TIME,记录最后更新时间 * * @author phoenix * */ public static class UserTable { public static final String TABLE_NAME = "t_user"; public static class Columns { public static final String ID = "_id"; public static final String USER_ID = "user_id"; public static final String USER_NAME = "user_name"; public static final String SCREEN_NAME = "screen_name"; public static final String LOCATION = "location"; public static final String DESCRIPTION = "description"; public static final String URL = "url"; public static final String PROTECTED = "protected"; public static final String PROFILE_IMAGE_URL = "profile_image_url"; public static final String FOLLOWERS_COUNT = "followers_count"; public static final String FRIENDS_COUNT = "friends_count"; public static final String FAVOURITES_COUNT = "favourites_count"; public static final String STATUSES_COUNT = "statuses_count"; public static final String CREATED_AT = "created_at"; public static final String FOLLOWING = "following"; public static final String NOTIFICATIONS = "notifications"; public static final String UTC_OFFSET = "utc_offset"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.ID + " INTEGER PRIMARY KEY, " + Columns.USER_ID + " TEXT UNIQUE NOT NULL, " + Columns.USER_NAME + " TEXT UNIQUE NOT NULL, " + Columns.SCREEN_NAME + " TEXT, " + Columns.LOCATION + " TEXT, " + Columns.DESCRIPTION + " TEXT, " + Columns.URL + " TEXT, " + Columns.PROTECTED + " INT DEFAULT 0, " + Columns.PROFILE_IMAGE_URL + " TEXT " + Columns.FOLLOWERS_COUNT + " INT, " + Columns.FRIENDS_COUNT + " INT, " + Columns.FAVOURITES_COUNT + " INT, " + Columns.STATUSES_COUNT + " INT, " + Columns.CREATED_AT + " INT, " + Columns.FOLLOWING + " INT DEFAULT 0, " + Columns.NOTIFICATIONS + " INT DEFAULT 0, " + Columns.UTC_OFFSET + " TEXT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.ID, Columns.USER_ID, Columns.USER_NAME, Columns.SCREEN_NAME, Columns.LOCATION, Columns.DESCRIPTION, Columns.URL, Columns.PROTECTED, Columns.PROFILE_IMAGE_URL, Columns.FOLLOWERS_COUNT, Columns.FRIENDS_COUNT, Columns.FAVOURITES_COUNT, Columns.STATUSES_COUNT, Columns.CREATED_AT, Columns.FOLLOWING, Columns.NOTIFICATIONS, Columns.UTC_OFFSET, Columns.LOAD_TIME }; } } /** * 私信表 私信的基本信息 * * @author phoenix * */ public static class DirectMessageTable { public static final String TABLE_NAME = "t_direct_message"; public static class Columns { public static final String ID = "_id"; public static final String MSG_ID = "msg_id"; public static final String TEXT = "text"; public static final String SENDER_ID = "sender_id"; public static final String RECIPINET_ID = "recipinet_id"; public static final String CREATED_AT = "created_at"; public static final String LOAD_TIME = "load_time"; public static final String SEQUENCE_FLAG = "sequence_flag"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.ID + " INTEGER PRIMARY KEY, " + Columns.MSG_ID + " TEXT UNIQUE NOT NULL, " + Columns.TEXT + " TEXT, " + Columns.SENDER_ID + " TEXT, " + Columns.RECIPINET_ID + " TEXT, " + Columns.CREATED_AT + " INT, " + Columns.SEQUENCE_FLAG + " INT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.ID, Columns.MSG_ID, Columns.TEXT, Columns.SENDER_ID, Columns.RECIPINET_ID, Columns.CREATED_AT, Columns.SEQUENCE_FLAG, Columns.LOAD_TIME }; } } /** * Follow关系表 某个特定用户的Follow关系(User1 following User2, * 查找关联某人好友只需限定User1或者User2) * * @author phoenix * */ public static class FollowRelationshipTable { public static final String TABLE_NAME = "t_follow_relationship"; public static class Columns { public static final String USER1_ID = "user1_id"; public static final String USER2_ID = "user2_id"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.USER1_ID + " TEXT, " + Columns.USER2_ID + " TEXT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.USER1_ID, Columns.USER2_ID, Columns.LOAD_TIME }; } } /** * 热门话题表 记录每次查询得到的热词 * * @author phoenix * */ public static class TrendTable { public static final String TABLE_NAME = "t_trend"; public static class Columns { public static final String NAME = "name"; public static final String QUERY = "query"; public static final String URL = "url"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.NAME + " TEXT, " + Columns.QUERY + " TEXT, " + Columns.URL + " TEXT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.NAME, Columns.QUERY, Columns.URL, Columns.LOAD_TIME }; } } /** * 保存搜索表 QUERY_ID(这个ID在API删除保存搜索词时使用) * * @author phoenix * */ public static class SavedSearchTable { public static final String TABLE_NAME = "t_saved_search"; public static class Columns { public static final String QUERY_ID = "query_id"; public static final String QUERY = "query"; public static final String NAME = "name"; public static final String CREATED_AT = "created_at"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.QUERY_ID + " INT, " + Columns.QUERY + " TEXT, " + Columns.NAME + " TEXT, " + Columns.CREATED_AT + " INT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.QUERY_ID, Columns.QUERY, Columns.NAME, Columns.CREATED_AT, Columns.LOAD_TIME }; } } }
Java
package com.ch_linghu.fanfoudroid.db2; import java.util.ArrayList; import java.util.Arrays; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; /** * Wrapper of SQliteDatabse#query, OOP style. * * Usage: * ------------------------------------------------ * Query select = new Query(SQLiteDatabase); * * // SELECT * query.from("tableName", new String[] { "colName" }) * .where("id = ?", 123456) * .where("name = ?", "jack") * .orderBy("created_at DESC") * .limit(1); * Cursor cursor = query.select(); * * // DELETE * query.from("tableName") * .where("id = ?", 123455); * .delete(); * * // UPDATE * query.setTable("tableName") * .values(contentValues) * .update(); * * // INSERT * query.into("tableName") * .values(contentValues) * .insert(); * ------------------------------------------------ * * @see SQLiteDatabase#query(String, String[], String, String[], String, String, String, String) */ public class Query { private static final String TAG = "Query-Builder"; /** TEMP list for selctionArgs */ private ArrayList<String> binds = new ArrayList<String>(); private SQLiteDatabase mDb = null; private String mTable; private String[] mColumns; private String mSelection = null; private String[] mSelectionArgs = null; private String mGroupBy = null; private String mHaving = null; private String mOrderBy = null; private String mLimit = null; private ContentValues mValues = null; private String mNullColumnHack = null; public Query() { } /** * Construct * * @param db */ public Query(SQLiteDatabase db) { this.setDb(db); } /** * Query the given table, returning a Cursor over the result set. * * @param db SQLitedatabase * @return A Cursor object, which is positioned before the first entry, or NULL */ public Cursor select() { if ( preCheck() ) { buildQuery(); return mDb.query(mTable, mColumns, mSelection, mSelectionArgs, mGroupBy, mHaving, mOrderBy, mLimit); } else { //throw new SelectException("Cann't build the query . " + toString()); Log.e(TAG, "Cann't build the query " + toString()); return null; } } /** * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */ public int delete() { if ( preCheck() ) { buildQuery(); return mDb.delete(mTable, mSelection, mSelectionArgs); } else { Log.e(TAG, "Cann't build the query " + toString()); return -1; } } /** * Set FROM * * @param table * The table name to compile the query against. * @param columns * A list of which columns to return. Passing null will return * all columns, which is discouraged to prevent reading data from * storage that isn't going to be used. * @return self * */ public Query from(String table, String[] columns) { mTable = table; mColumns = columns; return this; } /** * @see Query#from(String table, String[] columns) * @param table * @return self */ public Query from(String table) { return from(table, null); // all columns } /** * Add WHERE * * @param selection * A filter declaring which rows to return, formatted as an SQL * WHERE clause (excluding the WHERE itself). Passing null will * return all rows for the given table. * @param selectionArgs * You may include ?s in selection, which will be replaced by the * values from selectionArgs, in order that they appear in the * selection. The values will be bound as Strings. * @return self */ public Query where(String selection, String[] selectionArgs) { addSelection(selection); binds.addAll(Arrays.asList(selectionArgs)); return this; } /** * @see Query#where(String selection, String[] selectionArgs) */ public Query where(String selection, String selectionArg) { addSelection(selection); binds.add(selectionArg); return this; } /** * @see Query#where(String selection, String[] selectionArgs) */ public Query where(String selection) { addSelection(selection); return this; } /** * add selection part * * @param selection */ private void addSelection(String selection) { if (null == mSelection) { mSelection = selection; } else { mSelection += " AND " + selection; } } /** * set HAVING * * @param having * A filter declare which row groups to include in the cursor, if * row grouping is being used, formatted as an SQL HAVING clause * (excluding the HAVING itself). Passing null will cause all row * groups to be included, and is required when row grouping is * not being used. * @return self */ public Query having(String having) { this.mHaving = having; return this; } /** * Set GROUP BY * * @param groupBy * A filter declaring how to group rows, formatted as an SQL * GROUP BY clause (excluding the GROUP BY itself). Passing null * will cause the rows to not be grouped. * @return self */ public Query groupBy(String groupBy) { this.mGroupBy = groupBy; return this; } /** * Set ORDER BY * * @param orderBy * How to order the rows, formatted as an SQL ORDER BY clause * (excluding the ORDER BY itself). Passing null will use the * default sort order, which may be unordered. * @return self */ public Query orderBy(String orderBy) { this.mOrderBy = orderBy; return this; } /** * @param limit * Limits the number of rows returned by the query, formatted as * LIMIT clause. Passing null denotes no LIMIT clause. * @return self */ public Query limit(String limit) { this.mLimit = limit; return this; } /** * @see Query#limit(String limit) */ public Query limit(int limit) { return limit(limit + ""); } /** * Merge selectionArgs */ private void buildQuery() { mSelectionArgs = new String[binds.size()]; binds.toArray(mSelectionArgs); Log.v(TAG, toString()); } private boolean preCheck() { return (mTable != null && mDb != null); } // For Insert /** * set insert table * * @param table table name * @return self */ public Query into(String table) { return setTable(table); } /** * Set new values * * @param values new values * @return self */ public Query values(ContentValues values) { mValues = values; return this; } /** * Insert a row * * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long insert() { return mDb.insert(mTable, mNullColumnHack, mValues); } // For update /** * Set target table * * @param table table name * @return self */ public Query setTable(String table) { mTable = table; return this; } /** * Update a row * * @return the number of rows affected, or -1 if an error occurred */ public int update() { if ( preCheck() ) { buildQuery(); return mDb.update(mTable, mValues, mSelection, mSelectionArgs); } else { Log.e(TAG, "Cann't build the query " + toString()); return -1; } } /** * Set back-end database * @param db */ public void setDb(SQLiteDatabase db) { if (null == this.mDb) { this.mDb = db; } } @Override public String toString() { return "Query [table=" + mTable + ", columns=" + Arrays.toString(mColumns) + ", selection=" + mSelection + ", selectionArgs=" + Arrays.toString(mSelectionArgs) + ", groupBy=" + mGroupBy + ", having=" + mHaving + ", orderBy=" + mOrderBy + "]"; } /** for debug */ public ContentValues getContentValues() { return mValues; } }
Java
package com.ch_linghu.fanfoudroid.http; import java.util.HashMap; import java.util.Map; public class HTMLEntity { public static String escape(String original) { StringBuffer buf = new StringBuffer(original); escape(buf); return buf.toString(); } public static void escape(StringBuffer original) { int index = 0; String escaped; while (index < original.length()) { escaped = entityEscapeMap.get(original.substring(index, index + 1)); if (null != escaped) { original.replace(index, index + 1, escaped); index += escaped.length(); } else { index++; } } } public static String unescape(String original) { StringBuffer buf = new StringBuffer(original); unescape(buf); return buf.toString(); } public static void unescape(StringBuffer original) { int index = 0; int semicolonIndex = 0; String escaped; String entity; while (index < original.length()) { index = original.indexOf("&", index); if (-1 == index) { break; } semicolonIndex = original.indexOf(";", index); if (-1 != semicolonIndex && 10 > (semicolonIndex - index)) { escaped = original.substring(index, semicolonIndex + 1); entity = escapeEntityMap.get(escaped); if (null != entity) { original.replace(index, semicolonIndex + 1, entity); } index++; } else { break; } } } private static Map<String, String> entityEscapeMap = new HashMap<String, String>(); private static Map<String, String> escapeEntityMap = new HashMap<String, String>(); static { String[][] entities = {{"&nbsp;", "&#160;"/* no-break space = non-breaking space */, "\u00A0"} , {"&iexcl;", "&#161;"/* inverted exclamation mark */, "\u00A1"} , {"&cent;", "&#162;"/* cent sign */, "\u00A2"} , {"&pound;", "&#163;"/* pound sign */, "\u00A3"} , {"&curren;", "&#164;"/* currency sign */, "\u00A4"} , {"&yen;", "&#165;"/* yen sign = yuan sign */, "\u00A5"} , {"&brvbar;", "&#166;"/* broken bar = broken vertical bar */, "\u00A6"} , {"&sect;", "&#167;"/* section sign */, "\u00A7"} , {"&uml;", "&#168;"/* diaeresis = spacing diaeresis */, "\u00A8"} , {"&copy;", "&#169;"/* copyright sign */, "\u00A9"} , {"&ordf;", "&#170;"/* feminine ordinal indicator */, "\u00AA"} , {"&laquo;", "&#171;"/* left-pointing double angle quotation mark = left pointing guillemet */, "\u00AB"} , {"&not;", "&#172;"/* not sign = discretionary hyphen */, "\u00AC"} , {"&shy;", "&#173;"/* soft hyphen = discretionary hyphen */, "\u00AD"} , {"&reg;", "&#174;"/* registered sign = registered trade mark sign */, "\u00AE"} , {"&macr;", "&#175;"/* macron = spacing macron = overline = APL overbar */, "\u00AF"} , {"&deg;", "&#176;"/* degree sign */, "\u00B0"} , {"&plusmn;", "&#177;"/* plus-minus sign = plus-or-minus sign */, "\u00B1"} , {"&sup2;", "&#178;"/* superscript two = superscript digit two = squared */, "\u00B2"} , {"&sup3;", "&#179;"/* superscript three = superscript digit three = cubed */, "\u00B3"} , {"&acute;", "&#180;"/* acute accent = spacing acute */, "\u00B4"} , {"&micro;", "&#181;"/* micro sign */, "\u00B5"} , {"&para;", "&#182;"/* pilcrow sign = paragraph sign */, "\u00B6"} , {"&middot;", "&#183;"/* middle dot = Georgian comma = Greek middle dot */, "\u00B7"} , {"&cedil;", "&#184;"/* cedilla = spacing cedilla */, "\u00B8"} , {"&sup1;", "&#185;"/* superscript one = superscript digit one */, "\u00B9"} , {"&ordm;", "&#186;"/* masculine ordinal indicator */, "\u00BA"} , {"&raquo;", "&#187;"/* right-pointing double angle quotation mark = right pointing guillemet */, "\u00BB"} , {"&frac14;", "&#188;"/* vulgar fraction one quarter = fraction one quarter */, "\u00BC"} , {"&frac12;", "&#189;"/* vulgar fraction one half = fraction one half */, "\u00BD"} , {"&frac34;", "&#190;"/* vulgar fraction three quarters = fraction three quarters */, "\u00BE"} , {"&iquest;", "&#191;"/* inverted question mark = turned question mark */, "\u00BF"} , {"&Agrave;", "&#192;"/* latin capital letter A with grave = latin capital letter A grave */, "\u00C0"} , {"&Aacute;", "&#193;"/* latin capital letter A with acute */, "\u00C1"} , {"&Acirc;", "&#194;"/* latin capital letter A with circumflex */, "\u00C2"} , {"&Atilde;", "&#195;"/* latin capital letter A with tilde */, "\u00C3"} , {"&Auml;", "&#196;"/* latin capital letter A with diaeresis */, "\u00C4"} , {"&Aring;", "&#197;"/* latin capital letter A with ring above = latin capital letter A ring */, "\u00C5"} , {"&AElig;", "&#198;"/* latin capital letter AE = latin capital ligature AE */, "\u00C6"} , {"&Ccedil;", "&#199;"/* latin capital letter C with cedilla */, "\u00C7"} , {"&Egrave;", "&#200;"/* latin capital letter E with grave */, "\u00C8"} , {"&Eacute;", "&#201;"/* latin capital letter E with acute */, "\u00C9"} , {"&Ecirc;", "&#202;"/* latin capital letter E with circumflex */, "\u00CA"} , {"&Euml;", "&#203;"/* latin capital letter E with diaeresis */, "\u00CB"} , {"&Igrave;", "&#204;"/* latin capital letter I with grave */, "\u00CC"} , {"&Iacute;", "&#205;"/* latin capital letter I with acute */, "\u00CD"} , {"&Icirc;", "&#206;"/* latin capital letter I with circumflex */, "\u00CE"} , {"&Iuml;", "&#207;"/* latin capital letter I with diaeresis */, "\u00CF"} , {"&ETH;", "&#208;"/* latin capital letter ETH */, "\u00D0"} , {"&Ntilde;", "&#209;"/* latin capital letter N with tilde */, "\u00D1"} , {"&Ograve;", "&#210;"/* latin capital letter O with grave */, "\u00D2"} , {"&Oacute;", "&#211;"/* latin capital letter O with acute */, "\u00D3"} , {"&Ocirc;", "&#212;"/* latin capital letter O with circumflex */, "\u00D4"} , {"&Otilde;", "&#213;"/* latin capital letter O with tilde */, "\u00D5"} , {"&Ouml;", "&#214;"/* latin capital letter O with diaeresis */, "\u00D6"} , {"&times;", "&#215;"/* multiplication sign */, "\u00D7"} , {"&Oslash;", "&#216;"/* latin capital letter O with stroke = latin capital letter O slash */, "\u00D8"} , {"&Ugrave;", "&#217;"/* latin capital letter U with grave */, "\u00D9"} , {"&Uacute;", "&#218;"/* latin capital letter U with acute */, "\u00DA"} , {"&Ucirc;", "&#219;"/* latin capital letter U with circumflex */, "\u00DB"} , {"&Uuml;", "&#220;"/* latin capital letter U with diaeresis */, "\u00DC"} , {"&Yacute;", "&#221;"/* latin capital letter Y with acute */, "\u00DD"} , {"&THORN;", "&#222;"/* latin capital letter THORN */, "\u00DE"} , {"&szlig;", "&#223;"/* latin small letter sharp s = ess-zed */, "\u00DF"} , {"&agrave;", "&#224;"/* latin small letter a with grave = latin small letter a grave */, "\u00E0"} , {"&aacute;", "&#225;"/* latin small letter a with acute */, "\u00E1"} , {"&acirc;", "&#226;"/* latin small letter a with circumflex */, "\u00E2"} , {"&atilde;", "&#227;"/* latin small letter a with tilde */, "\u00E3"} , {"&auml;", "&#228;"/* latin small letter a with diaeresis */, "\u00E4"} , {"&aring;", "&#229;"/* latin small letter a with ring above = latin small letter a ring */, "\u00E5"} , {"&aelig;", "&#230;"/* latin small letter ae = latin small ligature ae */, "\u00E6"} , {"&ccedil;", "&#231;"/* latin small letter c with cedilla */, "\u00E7"} , {"&egrave;", "&#232;"/* latin small letter e with grave */, "\u00E8"} , {"&eacute;", "&#233;"/* latin small letter e with acute */, "\u00E9"} , {"&ecirc;", "&#234;"/* latin small letter e with circumflex */, "\u00EA"} , {"&euml;", "&#235;"/* latin small letter e with diaeresis */, "\u00EB"} , {"&igrave;", "&#236;"/* latin small letter i with grave */, "\u00EC"} , {"&iacute;", "&#237;"/* latin small letter i with acute */, "\u00ED"} , {"&icirc;", "&#238;"/* latin small letter i with circumflex */, "\u00EE"} , {"&iuml;", "&#239;"/* latin small letter i with diaeresis */, "\u00EF"} , {"&eth;", "&#240;"/* latin small letter eth */, "\u00F0"} , {"&ntilde;", "&#241;"/* latin small letter n with tilde */, "\u00F1"} , {"&ograve;", "&#242;"/* latin small letter o with grave */, "\u00F2"} , {"&oacute;", "&#243;"/* latin small letter o with acute */, "\u00F3"} , {"&ocirc;", "&#244;"/* latin small letter o with circumflex */, "\u00F4"} , {"&otilde;", "&#245;"/* latin small letter o with tilde */, "\u00F5"} , {"&ouml;", "&#246;"/* latin small letter o with diaeresis */, "\u00F6"} , {"&divide;", "&#247;"/* division sign */, "\u00F7"} , {"&oslash;", "&#248;"/* latin small letter o with stroke = latin small letter o slash */, "\u00F8"} , {"&ugrave;", "&#249;"/* latin small letter u with grave */, "\u00F9"} , {"&uacute;", "&#250;"/* latin small letter u with acute */, "\u00FA"} , {"&ucirc;", "&#251;"/* latin small letter u with circumflex */, "\u00FB"} , {"&uuml;", "&#252;"/* latin small letter u with diaeresis */, "\u00FC"} , {"&yacute;", "&#253;"/* latin small letter y with acute */, "\u00FD"} , {"&thorn;", "&#254;"/* latin small letter thorn with */, "\u00FE"} , {"&yuml;", "&#255;"/* latin small letter y with diaeresis */, "\u00FF"} , {"&fnof;", "&#402;"/* latin small f with hook = function = florin */, "\u0192"} /* Greek */ , {"&Alpha;", "&#913;"/* greek capital letter alpha */, "\u0391"} , {"&Beta;", "&#914;"/* greek capital letter beta */, "\u0392"} , {"&Gamma;", "&#915;"/* greek capital letter gamma */, "\u0393"} , {"&Delta;", "&#916;"/* greek capital letter delta */, "\u0394"} , {"&Epsilon;", "&#917;"/* greek capital letter epsilon */, "\u0395"} , {"&Zeta;", "&#918;"/* greek capital letter zeta */, "\u0396"} , {"&Eta;", "&#919;"/* greek capital letter eta */, "\u0397"} , {"&Theta;", "&#920;"/* greek capital letter theta */, "\u0398"} , {"&Iota;", "&#921;"/* greek capital letter iota */, "\u0399"} , {"&Kappa;", "&#922;"/* greek capital letter kappa */, "\u039A"} , {"&Lambda;", "&#923;"/* greek capital letter lambda */, "\u039B"} , {"&Mu;", "&#924;"/* greek capital letter mu */, "\u039C"} , {"&Nu;", "&#925;"/* greek capital letter nu */, "\u039D"} , {"&Xi;", "&#926;"/* greek capital letter xi */, "\u039E"} , {"&Omicron;", "&#927;"/* greek capital letter omicron */, "\u039F"} , {"&Pi;", "&#928;"/* greek capital letter pi */, "\u03A0"} , {"&Rho;", "&#929;"/* greek capital letter rho */, "\u03A1"} /* there is no Sigmaf and no \u03A2 */ , {"&Sigma;", "&#931;"/* greek capital letter sigma */, "\u03A3"} , {"&Tau;", "&#932;"/* greek capital letter tau */, "\u03A4"} , {"&Upsilon;", "&#933;"/* greek capital letter upsilon */, "\u03A5"} , {"&Phi;", "&#934;"/* greek capital letter phi */, "\u03A6"} , {"&Chi;", "&#935;"/* greek capital letter chi */, "\u03A7"} , {"&Psi;", "&#936;"/* greek capital letter psi */, "\u03A8"} , {"&Omega;", "&#937;"/* greek capital letter omega */, "\u03A9"} , {"&alpha;", "&#945;"/* greek small letter alpha */, "\u03B1"} , {"&beta;", "&#946;"/* greek small letter beta */, "\u03B2"} , {"&gamma;", "&#947;"/* greek small letter gamma */, "\u03B3"} , {"&delta;", "&#948;"/* greek small letter delta */, "\u03B4"} , {"&epsilon;", "&#949;"/* greek small letter epsilon */, "\u03B5"} , {"&zeta;", "&#950;"/* greek small letter zeta */, "\u03B6"} , {"&eta;", "&#951;"/* greek small letter eta */, "\u03B7"} , {"&theta;", "&#952;"/* greek small letter theta */, "\u03B8"} , {"&iota;", "&#953;"/* greek small letter iota */, "\u03B9"} , {"&kappa;", "&#954;"/* greek small letter kappa */, "\u03BA"} , {"&lambda;", "&#955;"/* greek small letter lambda */, "\u03BB"} , {"&mu;", "&#956;"/* greek small letter mu */, "\u03BC"} , {"&nu;", "&#957;"/* greek small letter nu */, "\u03BD"} , {"&xi;", "&#958;"/* greek small letter xi */, "\u03BE"} , {"&omicron;", "&#959;"/* greek small letter omicron */, "\u03BF"} , {"&pi;", "&#960;"/* greek small letter pi */, "\u03C0"} , {"&rho;", "&#961;"/* greek small letter rho */, "\u03C1"} , {"&sigmaf;", "&#962;"/* greek small letter final sigma */, "\u03C2"} , {"&sigma;", "&#963;"/* greek small letter sigma */, "\u03C3"} , {"&tau;", "&#964;"/* greek small letter tau */, "\u03C4"} , {"&upsilon;", "&#965;"/* greek small letter upsilon */, "\u03C5"} , {"&phi;", "&#966;"/* greek small letter phi */, "\u03C6"} , {"&chi;", "&#967;"/* greek small letter chi */, "\u03C7"} , {"&psi;", "&#968;"/* greek small letter psi */, "\u03C8"} , {"&omega;", "&#969;"/* greek small letter omega */, "\u03C9"} , {"&thetasym;", "&#977;"/* greek small letter theta symbol */, "\u03D1"} , {"&upsih;", "&#978;"/* greek upsilon with hook symbol */, "\u03D2"} , {"&piv;", "&#982;"/* greek pi symbol */, "\u03D6"} /* General Punctuation */ , {"&bull;", "&#8226;"/* bullet = black small circle */, "\u2022"} /* bullet is NOT the same as bullet operator ,"\u2219*/ , {"&hellip;", "&#8230;"/* horizontal ellipsis = three dot leader */, "\u2026"} , {"&prime;", "&#8242;"/* prime = minutes = feet */, "\u2032"} , {"&Prime;", "&#8243;"/* double prime = seconds = inches */, "\u2033"} , {"&oline;", "&#8254;"/* overline = spacing overscore */, "\u203E"} , {"&frasl;", "&#8260;"/* fraction slash */, "\u2044"} /* Letterlike Symbols */ , {"&weierp;", "&#8472;"/* script capital P = power set = Weierstrass p */, "\u2118"} , {"&image;", "&#8465;"/* blackletter capital I = imaginary part */, "\u2111"} , {"&real;", "&#8476;"/* blackletter capital R = real part symbol */, "\u211C"} , {"&trade;", "&#8482;"/* trade mark sign */, "\u2122"} , {"&alefsym;", "&#8501;"/* alef symbol = first transfinite cardinal */, "\u2135"} /* alef symbol is NOT the same as hebrew letter alef ,"\u05D0"}*/ /* Arrows */ , {"&larr;", "&#8592;"/* leftwards arrow */, "\u2190"} , {"&uarr;", "&#8593;"/* upwards arrow */, "\u2191"} , {"&rarr;", "&#8594;"/* rightwards arrow */, "\u2192"} , {"&darr;", "&#8595;"/* downwards arrow */, "\u2193"} , {"&harr;", "&#8596;"/* left right arrow */, "\u2194"} , {"&crarr;", "&#8629;"/* downwards arrow with corner leftwards = carriage return */, "\u21B5"} , {"&lArr;", "&#8656;"/* leftwards double arrow */, "\u21D0"} /* Unicode does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */ , {"&uArr;", "&#8657;"/* upwards double arrow */, "\u21D1"} , {"&rArr;", "&#8658;"/* rightwards double arrow */, "\u21D2"} /* Unicode does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */ , {"&dArr;", "&#8659;"/* downwards double arrow */, "\u21D3"} , {"&hArr;", "&#8660;"/* left right double arrow */, "\u21D4"} /* Mathematical Operators */ , {"&forall;", "&#8704;"/* for all */, "\u2200"} , {"&part;", "&#8706;"/* partial differential */, "\u2202"} , {"&exist;", "&#8707;"/* there exists */, "\u2203"} , {"&empty;", "&#8709;"/* empty set = null set = diameter */, "\u2205"} , {"&nabla;", "&#8711;"/* nabla = backward difference */, "\u2207"} , {"&isin;", "&#8712;"/* element of */, "\u2208"} , {"&notin;", "&#8713;"/* not an element of */, "\u2209"} , {"&ni;", "&#8715;"/* contains as member */, "\u220B"} /* should there be a more memorable name than 'ni'? */ , {"&prod;", "&#8719;"/* n-ary product = product sign */, "\u220F"} /* prod is NOT the same character as ,"\u03A0"}*/ , {"&sum;", "&#8721;"/* n-ary sumation */, "\u2211"} /* sum is NOT the same character as ,"\u03A3"}*/ , {"&minus;", "&#8722;"/* minus sign */, "\u2212"} , {"&lowast;", "&#8727;"/* asterisk operator */, "\u2217"} , {"&radic;", "&#8730;"/* square root = radical sign */, "\u221A"} , {"&prop;", "&#8733;"/* proportional to */, "\u221D"} , {"&infin;", "&#8734;"/* infinity */, "\u221E"} , {"&ang;", "&#8736;"/* angle */, "\u2220"} , {"&and;", "&#8743;"/* logical and = wedge */, "\u2227"} , {"&or;", "&#8744;"/* logical or = vee */, "\u2228"} , {"&cap;", "&#8745;"/* intersection = cap */, "\u2229"} , {"&cup;", "&#8746;"/* union = cup */, "\u222A"} , {"&int;", "&#8747;"/* integral */, "\u222B"} , {"&there4;", "&#8756;"/* therefore */, "\u2234"} , {"&sim;", "&#8764;"/* tilde operator = varies with = similar to */, "\u223C"} /* tilde operator is NOT the same character as the tilde ,"\u007E"}*/ , {"&cong;", "&#8773;"/* approximately equal to */, "\u2245"} , {"&asymp;", "&#8776;"/* almost equal to = asymptotic to */, "\u2248"} , {"&ne;", "&#8800;"/* not equal to */, "\u2260"} , {"&equiv;", "&#8801;"/* identical to */, "\u2261"} , {"&le;", "&#8804;"/* less-than or equal to */, "\u2264"} , {"&ge;", "&#8805;"/* greater-than or equal to */, "\u2265"} , {"&sub;", "&#8834;"/* subset of */, "\u2282"} , {"&sup;", "&#8835;"/* superset of */, "\u2283"} /* note that nsup 'not a superset of ,"\u2283"}*/ , {"&sube;", "&#8838;"/* subset of or equal to */, "\u2286"} , {"&supe;", "&#8839;"/* superset of or equal to */, "\u2287"} , {"&oplus;", "&#8853;"/* circled plus = direct sum */, "\u2295"} , {"&otimes;", "&#8855;"/* circled times = vector product */, "\u2297"} , {"&perp;", "&#8869;"/* up tack = orthogonal to = perpendicular */, "\u22A5"} , {"&sdot;", "&#8901;"/* dot operator */, "\u22C5"} /* dot operator is NOT the same character as ,"\u00B7"} /* Miscellaneous Technical */ , {"&lceil;", "&#8968;"/* left ceiling = apl upstile */, "\u2308"} , {"&rceil;", "&#8969;"/* right ceiling */, "\u2309"} , {"&lfloor;", "&#8970;"/* left floor = apl downstile */, "\u230A"} , {"&rfloor;", "&#8971;"/* right floor */, "\u230B"} , {"&lang;", "&#9001;"/* left-pointing angle bracket = bra */, "\u2329"} /* lang is NOT the same character as ,"\u003C"}*/ , {"&rang;", "&#9002;"/* right-pointing angle bracket = ket */, "\u232A"} /* rang is NOT the same character as ,"\u003E"}*/ /* Geometric Shapes */ , {"&loz;", "&#9674;"/* lozenge */, "\u25CA"} /* Miscellaneous Symbols */ , {"&spades;", "&#9824;"/* black spade suit */, "\u2660"} /* black here seems to mean filled as opposed to hollow */ , {"&clubs;", "&#9827;"/* black club suit = shamrock */, "\u2663"} , {"&hearts;", "&#9829;"/* black heart suit = valentine */, "\u2665"} , {"&diams;", "&#9830;"/* black diamond suit */, "\u2666"} , {"&quot;", "&#34;" /* quotation mark = APL quote */, "\""} , {"&amp;", "&#38;" /* ampersand */, "\u0026"} , {"&lt;", "&#60;" /* less-than sign */, "\u003C"} , {"&gt;", "&#62;" /* greater-than sign */, "\u003E"} /* Latin Extended-A */ , {"&OElig;", "&#338;" /* latin capital ligature OE */, "\u0152"} , {"&oelig;", "&#339;" /* latin small ligature oe */, "\u0153"} /* ligature is a misnomer this is a separate character in some languages */ , {"&Scaron;", "&#352;" /* latin capital letter S with caron */, "\u0160"} , {"&scaron;", "&#353;" /* latin small letter s with caron */, "\u0161"} , {"&Yuml;", "&#376;" /* latin capital letter Y with diaeresis */, "\u0178"} /* Spacing Modifier Letters */ , {"&circ;", "&#710;" /* modifier letter circumflex accent */, "\u02C6"} , {"&tilde;", "&#732;" /* small tilde */, "\u02DC"} /* General Punctuation */ , {"&ensp;", "&#8194;"/* en space */, "\u2002"} , {"&emsp;", "&#8195;"/* em space */, "\u2003"} , {"&thinsp;", "&#8201;"/* thin space */, "\u2009"} , {"&zwnj;", "&#8204;"/* zero width non-joiner */, "\u200C"} , {"&zwj;", "&#8205;"/* zero width joiner */, "\u200D"} , {"&lrm;", "&#8206;"/* left-to-right mark */, "\u200E"} , {"&rlm;", "&#8207;"/* right-to-left mark */, "\u200F"} , {"&ndash;", "&#8211;"/* en dash */, "\u2013"} , {"&mdash;", "&#8212;"/* em dash */, "\u2014"} , {"&lsquo;", "&#8216;"/* left single quotation mark */, "\u2018"} , {"&rsquo;", "&#8217;"/* right single quotation mark */, "\u2019"} , {"&sbquo;", "&#8218;"/* single low-9 quotation mark */, "\u201A"} , {"&ldquo;", "&#8220;"/* left double quotation mark */, "\u201C"} , {"&rdquo;", "&#8221;"/* right double quotation mark */, "\u201D"} , {"&bdquo;", "&#8222;"/* double low-9 quotation mark */, "\u201E"} , {"&dagger;", "&#8224;"/* dagger */, "\u2020"} , {"&Dagger;", "&#8225;"/* double dagger */, "\u2021"} , {"&permil;", "&#8240;"/* per mille sign */, "\u2030"} , {"&lsaquo;", "&#8249;"/* single left-pointing angle quotation mark */, "\u2039"} /* lsaquo is proposed but not yet ISO standardized */ , {"&rsaquo;", "&#8250;"/* single right-pointing angle quotation mark */, "\u203A"} /* rsaquo is proposed but not yet ISO standardized */ , {"&euro;", "&#8364;" /* euro sign */, "\u20AC"}}; for (String[] entity : entities) { entityEscapeMap.put(entity[2], entity[0]); escapeEntityMap.put(entity[0], entity[2]); escapeEntityMap.put(entity[1], entity[2]); } } }
Java
package com.ch_linghu.fanfoudroid.http; /** * HTTP StatusCode is not 200 */ public class HttpException extends Exception { private int statusCode = -1; public HttpException(String msg) { super(msg); } public HttpException(Exception cause) { super(cause); } public HttpException(String msg, int statusCode) { super(msg); this.statusCode = statusCode; } public HttpException(String msg, Exception cause) { super(msg, cause); } public HttpException(String msg, Exception cause, int statusCode) { super(msg, cause); this.statusCode = statusCode; } public int getStatusCode() { return this.statusCode; } }
Java
package com.ch_linghu.fanfoudroid.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.util.CharArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import android.util.Log; import com.ch_linghu.fanfoudroid.util.DebugTimer; public class Response { private final HttpResponse mResponse; private boolean mStreamConsumed = false; public Response(HttpResponse res) { mResponse = res; } /** * Convert Response to inputStream * * @return InputStream or null * @throws ResponseException */ public InputStream asStream() throws ResponseException { try { final HttpEntity entity = mResponse.getEntity(); if (entity != null) { return entity.getContent(); } } catch (IllegalStateException e) { throw new ResponseException(e.getMessage(), e); } catch (IOException e) { throw new ResponseException(e.getMessage(), e); } return null; } /** * @deprecated use entity.getContent(); * @param entity * @return * @throws ResponseException */ private InputStream asStream(HttpEntity entity) throws ResponseException { if (null == entity) { return null; } InputStream is = null; try { is = entity.getContent(); } catch (IllegalStateException e) { throw new ResponseException(e.getMessage(), e); } catch (IOException e) { throw new ResponseException(e.getMessage(), e); } //mResponse = null; return is; } /** * Convert Response to Context String * * @return response context string or null * @throws ResponseException */ public String asString() throws ResponseException { try { return entityToString(mResponse.getEntity()); } catch (IOException e) { throw new ResponseException(e.getMessage(), e); } } /** * EntityUtils.toString(entity, "UTF-8"); * * @param entity * @return * @throws IOException * @throws ResponseException */ private String entityToString(final HttpEntity entity) throws IOException, ResponseException { DebugTimer.betweenStart("AS STRING"); if (null == entity) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); //InputStream instream = asStream(entity); if (instream == null) { return ""; } if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } Log.i("LDS", i + " content length"); Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8")); CharArrayBuffer buffer = new CharArrayBuffer(i); try { char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } } finally { reader.close(); } DebugTimer.betweenEnd("AS STRING"); return buffer.toString(); } /** * @deprecated use entityToString() * @param in * @return * @throws ResponseException */ private String inputStreamToString(final InputStream in) throws IOException { if (null == in) { return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuffer buf = new StringBuffer(); try { char[] buffer = new char[1024]; while ((reader.read(buffer)) != -1) { buf.append(buffer); } return buf.toString(); } finally { if (reader != null) { reader.close(); setStreamConsumed(true); } } } public JSONObject asJSONObject() throws ResponseException { try { return new JSONObject(asString()); } catch (JSONException jsone) { throw new ResponseException(jsone.getMessage() + ":" + asString(), jsone); } } public JSONArray asJSONArray() throws ResponseException { try { return new JSONArray(asString()); } catch (Exception jsone) { throw new ResponseException(jsone.getMessage(), jsone); } } private void setStreamConsumed(boolean mStreamConsumed) { this.mStreamConsumed = mStreamConsumed; } public boolean isStreamConsumed() { return mStreamConsumed; } /** * @deprecated * @return */ public Document asDocument() { // TODO Auto-generated method stub return null; } private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});"); /** * Unescape UTF-8 escaped characters to string. * @author pengjianq...@gmail.com * * @param original The string to be unescaped. * @return The unescaped string */ public static String unescape(String original) { Matcher mm = escaped.matcher(original); StringBuffer unescaped = new StringBuffer(); while (mm.find()) { mm.appendReplacement(unescaped, Character.toString( (char) Integer.parseInt(mm.group(1), 10))); } mm.appendTail(unescaped); return unescaped.toString(); } }
Java
package com.ch_linghu.fanfoudroid.http; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import javax.net.ssl.SSLHandshakeException; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpVersion; import org.apache.http.NoHttpResponseException; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.fanfou.Configuration; import com.ch_linghu.fanfoudroid.fanfou.RefuseError; import com.ch_linghu.fanfoudroid.util.DebugTimer; /** * Wrap of org.apache.http.impl.client.DefaultHttpClient * * @author lds * */ public class HttpClient { private static final String TAG = "HttpClient"; private final static boolean DEBUG = Configuration.getDebug(); /** OK: Success! */ public static final int OK = 200; /** Not Modified: There was no new data to return. */ public static final int NOT_MODIFIED = 304; /** Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. */ public static final int BAD_REQUEST = 400; /** Not Authorized: Authentication credentials were missing or incorrect. */ public static final int NOT_AUTHORIZED = 401; /** Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. */ public static final int FORBIDDEN = 403; /** Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists. */ public static final int NOT_FOUND = 404; /** Not Acceptable: Returned by the Search API when an invalid format is specified in the request. */ public static final int NOT_ACCEPTABLE = 406; /** Internal Server Error: Something is broken. Please post to the group so the Weibo team can investigate. */ public static final int INTERNAL_SERVER_ERROR = 500; /** Bad Gateway: Weibo is down or being upgraded. */ public static final int BAD_GATEWAY = 502; /** Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited. */ public static final int SERVICE_UNAVAILABLE = 503; private static final int CONNECTION_TIMEOUT_MS = 30 * 1000; private static final int SOCKET_TIMEOUT_MS = 30 * 1000; public static final int RETRIEVE_LIMIT = 20; public static final int RETRIED_TIME = 3; private static final String SERVER_HOST = "api.fanfou.com"; private DefaultHttpClient mClient; private AuthScope mAuthScope; private BasicHttpContext localcontext; private String mUserId; private String mPassword; private static boolean isAuthenticationEnabled = false; public HttpClient() { prepareHttpClient(); } /** * @param user_id auth user * @param password auth password */ public HttpClient(String user_id, String password) { prepareHttpClient(); setCredentials(user_id, password); } /** * Empty the credentials */ public void reset() { setCredentials("", ""); } /** * @return authed user id */ public String getUserId() { return mUserId; } /** * @return authed user password */ public String getPassword() { return mPassword; } /** * @param hostname the hostname (IP or DNS name) * @param port the port number. -1 indicates the scheme default port. * @param scheme the name of the scheme. null indicates the default scheme */ public void setProxy(String host, int port, String scheme) { HttpHost proxy = new HttpHost(host, port, scheme); mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } public void removeProxy() { mClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); } private void enableDebug() { Log.d(TAG, "enable apache.http debug"); java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.FINEST); java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINER); java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF); /* System.setProperty("log.tag.org.apache.http", "VERBOSE"); System.setProperty("log.tag.org.apache.http.wire", "VERBOSE"); System.setProperty("log.tag.org.apache.http.headers", "VERBOSE"); 在这里使用System.setProperty设置不会生效, 原因不明, 必须在终端上输入以下命令方能开启http调试信息: > adb shell setprop log.tag.org.apache.http VERBOSE > adb shell setprop log.tag.org.apache.http.wire VERBOSE > adb shell setprop log.tag.org.apache.http.headers VERBOSE */ } /** * Setup DefaultHttpClient * * Use ThreadSafeClientConnManager. * */ private void prepareHttpClient() { if (DEBUG) { enableDebug(); } // Create and initialize HTTP parameters HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 10); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory .getSocketFactory(), 443)); // Create an HttpClient with the ThreadSafeClientConnManager. ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); mClient = new DefaultHttpClient(cm, params); // Setup BasicAuth BasicScheme basicScheme = new BasicScheme(); mAuthScope = new AuthScope(SERVER_HOST, AuthScope.ANY_PORT); // mClient.setAuthSchemes(authRegistry); mClient.setCredentialsProvider(new BasicCredentialsProvider()); // Generate BASIC scheme object and stick it to the local // execution context localcontext = new BasicHttpContext(); localcontext.setAttribute("preemptive-auth", basicScheme); // first request interceptor mClient.addRequestInterceptor(preemptiveAuth, 0); // Support GZIP mClient.addResponseInterceptor(gzipResponseIntercepter); // TODO: need to release this connection in httpRequest() // cm.releaseConnection(conn, validDuration, timeUnit); //httpclient.getConnectionManager().shutdown(); } /** * HttpRequestInterceptor for DefaultHttpClient */ private static HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) { AuthState authState = (AuthState) context .getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context .getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; private static HttpResponseInterceptor gzipResponseIntercepter = new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws org.apache.http.HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity( new GzipDecompressingEntity(response.getEntity())); return; } } } } }; static class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content is not known return -1; } } /** * Setup Credentials for HTTP Basic Auth * * @param username * @param password */ public void setCredentials(String username, String password) { mUserId = username; mPassword = password; mClient.getCredentialsProvider().setCredentials(mAuthScope, new UsernamePasswordCredentials(username, password)); isAuthenticationEnabled = true; } public Response post(String url, ArrayList<BasicNameValuePair> postParams, boolean authenticated) throws HttpException { if (null == postParams) { postParams = new ArrayList<BasicNameValuePair>(); } return httpRequest(url, postParams, authenticated, HttpPost.METHOD_NAME); } public Response post(String url, ArrayList<BasicNameValuePair> params) throws HttpException { return httpRequest(url, params, false, HttpPost.METHOD_NAME); } public Response post(String url, boolean authenticated) throws HttpException { return httpRequest(url, null, authenticated, HttpPost.METHOD_NAME); } public Response post(String url) throws HttpException { return httpRequest(url, null, false, HttpPost.METHOD_NAME); } public Response post(String url, File file) throws HttpException { return httpRequest(url, null, file, false, HttpPost.METHOD_NAME); } /** * POST一个文件 * * @param url * @param file * @param authenticate * @return * @throws HttpException */ public Response post(String url, File file, boolean authenticate) throws HttpException { return httpRequest(url, null, file, authenticate, HttpPost.METHOD_NAME); } public Response get(String url, ArrayList<BasicNameValuePair> params, boolean authenticated) throws HttpException { return httpRequest(url, params, authenticated, HttpGet.METHOD_NAME); } public Response get(String url, ArrayList<BasicNameValuePair> params) throws HttpException { return httpRequest(url, params, false, HttpGet.METHOD_NAME); } public Response get(String url) throws HttpException { return httpRequest(url, null, false, HttpGet.METHOD_NAME); } public Response get(String url, boolean authenticated) throws HttpException { return httpRequest(url, null, authenticated, HttpGet.METHOD_NAME); } public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams, boolean authenticated, String httpMethod) throws HttpException { return httpRequest(url, postParams, null, authenticated, httpMethod); } /** * Execute the DefaultHttpClient * * @param url * target * @param postParams * @param file * can be NULL * @param authenticated * need or not * @param httpMethod * HttpPost.METHOD_NAME * HttpGet.METHOD_NAME * HttpDelete.METHOD_NAME * @return Response from server * @throws HttpException 此异常包装了一系列底层异常 <br /><br /> * 1. 底层异常, 可使用getCause()查看: <br /> * <li>URISyntaxException, 由`new URI` 引发的.</li> * <li>IOException, 由`createMultipartEntity` 或 `UrlEncodedFormEntity` 引发的.</li> * <li>IOException和ClientProtocolException, 由`HttpClient.execute` 引发的.</li><br /> * * 2. 当响应码不为200时报出的各种子类异常: * <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常, * 首先检查request log, 确认不是人为错误导致请求失败</li> * <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li> * <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因 * 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li> * <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li> * <li>HttpException, 其他未知错误.</li> */ public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams, File file, boolean authenticated, String httpMethod) throws HttpException { Log.d(TAG, "Sending " + httpMethod + " request to " + url); if (TwitterApplication.DEBUG){ DebugTimer.betweenStart("HTTP"); } URI uri = createURI(url); HttpResponse response = null; Response res = null; HttpUriRequest method = null; // Create POST, GET or DELETE METHOD method = createMethod(httpMethod, uri, file, postParams); // Setup ConnectionParams, Request Headers SetupHTTPConnectionParams(method); // Execute Request try { response = mClient.execute(method, localcontext); res = new Response(response); } catch (ClientProtocolException e) { Log.e(TAG, e.getMessage(), e); throw new HttpException(e.getMessage(), e); } catch (IOException ioe) { throw new HttpException(ioe.getMessage(), ioe); } if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); // It will throw a weiboException while status code is not 200 HandleResponseStatusCode(statusCode, res); } else { Log.e(TAG, "response is null"); } if (TwitterApplication.DEBUG){ DebugTimer.betweenEnd("HTTP"); } return res; } /** * CreateURI from URL string * * @param url * @return request URI * @throws HttpException * Cause by URISyntaxException */ private URI createURI(String url) throws HttpException { URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { Log.e(TAG, e.getMessage(), e); throw new HttpException("Invalid URL."); } return uri; } /** * 创建可带一个File的MultipartEntity * * @param filename * 文件名 * @param file * 文件 * @param postParams * 其他POST参数 * @return 带文件和其他参数的Entity * @throws UnsupportedEncodingException */ private MultipartEntity createMultipartEntity(String filename, File file, ArrayList<BasicNameValuePair> postParams) throws UnsupportedEncodingException { MultipartEntity entity = new MultipartEntity(); // Don't try this. Server does not appear to support chunking. // entity.addPart("media", new InputStreamBody(imageStream, "media")); entity.addPart(filename, new FileBody(file)); for (BasicNameValuePair param : postParams) { entity.addPart(param.getName(), new StringBody(param.getValue())); } return entity; } /** * Setup HTTPConncetionParams * * @param method */ private void SetupHTTPConnectionParams(HttpUriRequest method) { HttpConnectionParams.setConnectionTimeout(method.getParams(), CONNECTION_TIMEOUT_MS); HttpConnectionParams .setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS); mClient.setHttpRequestRetryHandler(requestRetryHandler); method.addHeader("Accept-Encoding", "gzip, deflate"); method.addHeader("Accept-Charset", "UTF-8,*;q=0.5"); } /** * Create request method, such as POST, GET, DELETE * * @param httpMethod * "GET","POST","DELETE" * @param uri * 请求的URI * @param file * 可为null * @param postParams * POST参数 * @return httpMethod Request implementations for the various HTTP methods * like GET and POST. * @throws HttpException * createMultipartEntity 或 UrlEncodedFormEntity引发的IOException */ private HttpUriRequest createMethod(String httpMethod, URI uri, File file, ArrayList<BasicNameValuePair> postParams) throws HttpException { HttpUriRequest method; if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) { // POST METHOD HttpPost post = new HttpPost(uri); // See this: http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e178b1d3d63d8e3b post.getParams().setBooleanParameter("http.protocol.expect-continue", false); try { HttpEntity entity = null; if (null != file) { entity = createMultipartEntity("photo", file, postParams); post.setEntity(entity); } else if (null != postParams) { entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8); } post.setEntity(entity); } catch (IOException ioe) { throw new HttpException(ioe.getMessage(), ioe); } method = post; } else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) { method = new HttpDelete(uri); } else { method = new HttpGet(uri); } return method; } /** * 解析HTTP错误码 * * @param statusCode * @return */ private static String getCause(int statusCode) { String cause = null; switch (statusCode) { case NOT_MODIFIED: break; case BAD_REQUEST: cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting."; break; case NOT_AUTHORIZED: cause = "Authentication credentials were missing or incorrect."; break; case FORBIDDEN: cause = "The request is understood, but it has been refused. An accompanying error message will explain why."; break; case NOT_FOUND: cause = "The URI requested is invalid or the resource requested, such as a user, does not exists."; break; case NOT_ACCEPTABLE: cause = "Returned by the Search API when an invalid format is specified in the request."; break; case INTERNAL_SERVER_ERROR: cause = "Something is broken. Please post to the group so the Weibo team can investigate."; break; case BAD_GATEWAY: cause = "Weibo is down or being upgraded."; break; case SERVICE_UNAVAILABLE: cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited."; break; default: cause = ""; } return statusCode + ":" + cause; } public boolean isAuthenticationEnabled() { return isAuthenticationEnabled; } public static void log(String msg) { if (DEBUG) { Log.d(TAG, msg); } } /** * Handle Status code * * @param statusCode * 响应的状态码 * @param res * 服务器响应 * @throws HttpException * 当响应码不为200时都会报出此异常:<br /> * <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常, * 首先检查request log, 确认不是人为错误导致请求失败</li> * <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li> * <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因 * 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li> * <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li> * <li>HttpException, 其他未知错误.</li> */ private void HandleResponseStatusCode(int statusCode, Response res) throws HttpException { String msg = getCause(statusCode) + "\n"; RefuseError error = null; switch (statusCode) { // It's OK, do nothing case OK: break; // Mine mistake, Check the Log case NOT_MODIFIED: case BAD_REQUEST: case NOT_FOUND: case NOT_ACCEPTABLE: throw new HttpException(msg + res.asString(), statusCode); // UserName/Password incorrect case NOT_AUTHORIZED: throw new HttpAuthException(msg + res.asString(), statusCode); // Server will return a error message, use // HttpRefusedException#getError() to see. case FORBIDDEN: throw new HttpRefusedException(msg, statusCode); // Something wrong with server case INTERNAL_SERVER_ERROR: case BAD_GATEWAY: case SERVICE_UNAVAILABLE: throw new HttpServerException(msg, statusCode); // Others default: throw new HttpException(msg + res.asString(), statusCode); } } public static String encode(String value) throws HttpException { try { return URLEncoder.encode(value, HTTP.UTF_8); } catch (UnsupportedEncodingException e_e) { throw new HttpException(e_e.getMessage(), e_e); } } public static String encodeParameters(ArrayList<BasicNameValuePair> params) throws HttpException { StringBuffer buf = new StringBuffer(); for (int j = 0; j < params.size(); j++) { if (j != 0) { buf.append("&"); } try { buf.append(URLEncoder.encode(params.get(j).getName(), "UTF-8")) .append("=") .append(URLEncoder.encode(params.get(j).getValue(), "UTF-8")); } catch (java.io.UnsupportedEncodingException neverHappen) { throw new HttpException(neverHappen.getMessage(), neverHappen); } } return buf.toString(); } /** * 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复 */ private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() { // 自定义的恢复策略 public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // 设置恢复策略,在发生异常时候将自动重试N次 if (executionCount >= RETRIED_TIME) { // Do not retry if over max retry count return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest) context .getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (!idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.IDs; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener; import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter; import com.ch_linghu.fanfoudroid.ui.module.Widget; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.DebugTimer; import com.hlidskialf.android.hardware.ShakeListener; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity { static final String TAG = "TwitterCursorBaseActivity"; // Views. protected ListView mTweetList; protected TweetCursorAdapter mTweetAdapter; protected View mListHeader; protected View mListFooter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; protected ShakeListener mShaker = null; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask; private int mRetrieveCount = 0; private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { mFeedback.failed("登录信息出错"); logout(); } else if (result == TaskResult.OK) { // TODO: XML处理, GC压力 SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); // TODO: 1. StatusType(DONE) ; if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) { // 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性 getDb().gc(getUserId(), getDatabaseType()); // GC } draw(); if (task == mRetrieveTask) { goTop(); } } else if (result == TaskResult.IO_ERROR) { // FIXME: bad smell if (task == mRetrieveTask) { mFeedback.failed(((RetrieveTask) task).getErrorMsg()); } else if (task == mGetMoreTask) { mFeedback.failed(((GetMoreTask) task).getErrorMsg()); } } else { // do nothing } // 刷新按钮停止旋转 loadMoreGIFTop.setVisibility(View.GONE); loadMoreGIF.setVisibility(View.GONE); // DEBUG if (TwitterApplication.DEBUG) { DebugTimer.stop(); Log.v("DEBUG", DebugTimer.getProfileAsString()); } } @Override public void onPreExecute(GenericTask task) { mRetrieveCount = 0; if (TwitterApplication.DEBUG) { DebugTimer.start(); } } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected void markAllRead(); abstract protected Cursor fetchMessages(); public abstract int getDatabaseType(); public abstract String getUserId(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread); public abstract List<Status> getMessageSinceId(String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchMessages(); // getDb().fetchMentions(); setTitle(getActivityTitle()); startManagingCursor(cursor); mTweetList = (ListView) findViewById(R.id.tweet_list); // TODO: 需处理没有数据时的情况 Log.d("LDS", cursor.getCount() + " cursor count"); setupListHeader(true); mTweetAdapter = new TweetCursorAdapter(this, cursor); mTweetList.setAdapter(mTweetAdapter); // ? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add Header to ListView mListHeader = View.inflate(this, R.layout.listview_header, null); mTweetList.addHeaderView(mListHeader, null, true); // Add Footer to ListView mListFooter = View.inflate(this, R.layout.listview_footer, null); mTweetList.addFooterView(mListFooter, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header); loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header); } @Override protected void specialItemClicked(int position) { // 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别 // 前者仅包含数据的数量(不包括foot和head),后者包含foot和head // 因此在同时存在foot和head的情况下,list.count = adapter.count + 2 if (position == 0) { // 第一个Item(header) loadMoreGIFTop.setVisibility(View.VISIBLE); doRetrieve(); } else if (position == mTweetList.getCount() - 1) { // 最后一个Item(footer) loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } @Override protected int getLayoutId() { return R.layout.main; } @Override protected ListView getTweetList() { return mTweetList; } @Override protected TweetAdapter getTweetAdapter() { return mTweetAdapter; } @Override protected boolean useBasicMenu() { return true; } @Override protected Tweet getContextItemTweet(int position) { position = position - 1; // 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个 if (position >= 0 && position < mTweetAdapter.getCount()) { Cursor cursor = (Cursor) mTweetAdapter.getItem(position); if (cursor == null) { return null; } else { return StatusTable.parseCursor(cursor); } } else { return null; } } @Override protected void updateTweet(Tweet tweet) { // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 // 对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { goTop(); // skip the header // Mark all as read. // getDb().markAllMentionsRead(); markAllRead(); boolean shouldRetrieve = false; // FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want // dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.d(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.d(TAG, "Last followers refresh was " + diff + " ms ago."); // FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。 // 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring // 现在频繁会出现主键冲突的问题。 // // Should Refresh Followers // if (diff > FOLLOWERS_REFRESH_THRESHOLD // && (mRetrieveTask == null || mRetrieveTask.getStatus() != // GenericTask.Status.RUNNING)) { // Log.d(TAG, "Refresh followers."); // doRetrieveFollowers(); // } // 手势识别 registerGestureListener(); //晃动刷新 registerShakeListener(); return true; } else { return false; } } @Override protected void onResume() { Log.d(TAG, "onResume."); if (lastPosition != 0) { mTweetList.setSelection(lastPosition); } if (mShaker != null){ mShaker.resume(); } super.onResume(); checkIsLogedIn(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.d(TAG, "onPause."); if (mShaker != null){ mShaker.pause(); } super.onPause(); lastPosition = mTweetList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.d(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { return null; } @Override protected void adapterRefresh() { mTweetAdapter.notifyDataSetChanged(); mTweetAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mTweetAdapter.refresh(); } public void goTop() { Log.d(TAG, "goTop."); mTweetList.setSelection(1); } private void doRetrieveFollowers() { Log.d(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private class RetrieveTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; try { String maxId = fetchMaxId(); // getDb().fetchMaxMentionId(); statusList = getMessageSinceId(maxId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); mRetrieveCount = addMessages(tweets, false); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { // TODO: 目前仅做新API兼容性改动,待完善Follower处理 IDs followers = getApi().getFollowersIDs(); List<String> followerIds = Arrays.asList(followers.getIDs()); getDb().syncFollowers(followerIds); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } // GET MORE TASK private class GetMoreTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; String minId = fetchMinId(); // getDb().fetchMaxMentionId(); if (minId == null) { return TaskResult.FAILED; } try { statusList = getMoreMessageFromId(minId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } if (statusList == null) { return TaskResult.FAILED; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } addMessages(tweets, false); // getDb().addMentions(tweets, false); return TaskResult.OK; } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setFeedback(mFeedback); mGetMoreTask.setListener(mRetrieveTaskListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } //////////////////// Gesture test ///////////////////////////////////// private static boolean useGestrue; { useGestrue = TwitterApplication.mPref.getBoolean( Preferences.USE_GESTRUE, false); if (useGestrue) { Log.v(TAG, "Using Gestrue!"); } else { Log.v(TAG, "Not Using Gestrue!"); } } //////////////////// Gesture test ///////////////////////////////////// private static boolean useShake; { useShake = TwitterApplication.mPref.getBoolean( Preferences.USE_SHAKE, false); if (useShake) { Log.v(TAG, "Using Shake to refresh!"); } else { Log.v(TAG, "Not Using Shake!"); } } protected FlingGestureListener myGestureListener = null; @Override public boolean onTouchEvent(MotionEvent event) { if (useGestrue && myGestureListener != null) { return myGestureListener.getDetector().onTouchEvent(event); } return super.onTouchEvent(event); } // use it in _onCreate private void registerGestureListener() { if (useGestrue) { myGestureListener = new FlingGestureListener(this, MyActivityFlipper.create(this)); getTweetList().setOnTouchListener(myGestureListener); } } // use it in _onCreate private void registerShakeListener() { if (useShake){ mShaker = new ShakeListener(this); mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() { @Override public void onShake() { doRetrieve(); } }); } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.List; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.db.UserInfoTable; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class UserCursorBaseActivity extends UserListBaseActivity { /** * 第一种方案:(采取第一种) 暂不放在数据库中,直接从Api读取。 * * 第二种方案: 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 按照饭否api每次分页100人 * 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。 * 当收听数>100时采取分页加载,先按照id * 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载 * 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 单击刷新按钮则从api加载并同步到数据库中 * */ static final String TAG = "UserCursorBaseActivity"; // Views. protected ListView mUserList; protected UserCursorAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次十个用户 protected abstract String getUserId();// 获得用户id private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); // TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC, // 因为小于时可以保证数据的连续性 // FIXME: gc需要带owner // getDb().gc(getDatabaseType()); // GC draw(); goTop(); } else { // Do nothing. } // loadMoreGIFTop.setVisibility(View.GONE); updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected Cursor fetchUsers(); public abstract int getDatabaseType(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers() throws HttpException; public abstract void addUsers( ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers); // public abstract List<Status> getMessageSinceId(String maxId) // throws WeiboException; public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUserSinceId( String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public abstract Paging getNextPage();// 下一页数 public abstract Paging getCurrentPage();// 当前页数 protected abstract String[] getIds(); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchUsers(); // setTitle(getActivityTitle()); startManagingCursor(cursor); mUserList = (ListView) findViewById(R.id.follower_list); // TODO: 需处理没有数据时的情况 Log.d("LDS", cursor.getCount() + " cursor count"); setupListHeader(true); mUserListAdapter = new UserCursorAdapter(this, cursor); mUserList.setAdapter(mUserListAdapter); // ? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add footer to Listview View footer = View.inflate(this, R.layout.listview_footer, null); mUserList.addFooterView(footer, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); // loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header); // loadMoreGIFTop = // (ProgressBar)findViewById(R.id.rectangleProgressBar_header); // loadMoreAnimation = (AnimationDrawable) // loadMoreGIF.getIndeterminateDrawable(); } @Override protected void specialItemClicked(int position) { if (position == mUserList.getCount() - 1) { // footer loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } @Override protected boolean useBasicMenu() { return true; } protected User getContextItemUser(int position) { // position = position - 1; // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { Cursor cursor = (Cursor) mUserListAdapter.getItem(position); if (cursor == null) { return null; } else { return UserInfoTable.parseCursor(cursor); } } else { return null; } } @Override protected void updateTweet(Tweet tweet) { // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 // 对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { goTop(); // skip the header boolean shouldRetrieve = false; // FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); /* * if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if * (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to * see if it was running a send or retrieve task. // It makes no * sense to resend the send request (don't want dupes) // so we * instead retrieve (refresh) to see if the message has // posted. * Log.d(TAG, * "Was last running a retrieve or send task. Let's refresh."); * shouldRetrieve = true; } */ shouldRetrieve = true; if (shouldRetrieve) { doRetrieve(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.d(TAG, "Last followers refresh was " + diff + " ms ago."); /* * if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null * || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) { * Log.d(TAG, "Refresh followers."); doRetrieveFollowers(); } */ return true; } else { return false; } } @Override protected void onResume() { Log.d(TAG, "onResume."); if (lastPosition != 0) { mUserList.setSelection(lastPosition); } super.onResume(); checkIsLogedIn(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.d(TAG, "onPause."); super.onPause(); lastPosition = mUserList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.d(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected void adapterRefresh() { mUserListAdapter.notifyDataSetChanged(); mUserListAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mUserListAdapter.refresh(); } public void goTop() { Log.d(TAG, "goTop."); mUserList.setSelection(1); } private void doRetrieveFollowers() { Log.d(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } /** * TODO:从API获取当前Followers,并同步到数据库 * * @author Dino * */ private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getApi().getFollowersList(getUserId(), getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); ArrayList<User> users = new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { Log.d(TAG, "load FollowersErtrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> t_users = getUsers(); getDb().syncWeiboUsers(t_users); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getApi().getFollowersList(getUserId(), getNextPage()); } catch (HttpException e) { e.printStackTrace(); } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); ArrayList<User> users = new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); loadMoreGIF.setVisibility(View.GONE); } }; public void doGetMore() { Log.d(TAG, "Attempting getMore."); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setFeedback(mFeedback); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * AbstractTwitterListBaseLine用于抽象tweets List的展现 * UI基本元素要求:一个ListView用于tweet列表 * 一个ProgressText用于提示信息 */ package com.ch_linghu.fanfoudroid.ui.base; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.StatusActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; public abstract class TwitterListBaseActivity extends BaseActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected Feedback mFeedback; protected NavBar mNavbar; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; // Tasks. protected GenericTask mFavTask; private TaskListener mFavTaskListener = new TaskAdapter(){ @Override public String getName() { return "FavoriteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onFavSuccess(); } else if (result == TaskResult.IO_ERROR) { onFavFailure(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getTweetList(); abstract protected TweetAdapter getTweetAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected Tweet getContextItemTweet(int position); abstract protected void updateTweet(Tweet tweet); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, * 以保证其他人使用常量时不产生重复 * @return 最大的Context Menu常量 */ protected int getLastContextMenuId(){ return CONTEXT_DEL_FAV_ID; } @Override protected boolean _onCreate(Bundle savedInstanceState){ if (super._onCreate(savedInstanceState)){ setContentView(getLayoutId()); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); // 提示栏 mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getTweetList()); registerOnClickListener(getTweetList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { Log.d("FLING", "onContextItemSelected"); super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()){ AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return; } menu.add(0, CONTEXT_MORE_ID, 0, tweet.screenName + getResources().getString(R.string.cmenu_user_profile_prefix)); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet); menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message); if (tweet.favorited.equals("true")) { menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav); } else { menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_MORE_ID: launchActivity(ProfileActivity.createIntent(tweet.userId)); return true; case CONTEXT_REPLY_ID: { // TODO: this isn't quite perfect. It leaves extra empty spaces if // you perform the reply action again. Intent intent = WriteActivity.createNewReplyIntent(tweet.text, tweet.screenName, tweet.id); startActivity(intent); return true; } case CONTEXT_RETWEET_ID: Intent intent = WriteActivity.createNewRepostIntent(this, tweet.text, tweet.screenName, tweet.id); startActivity(intent); return true; case CONTEXT_DM_ID: launchActivity(WriteDmActivity.createIntent(tweet.userId)); return true; case CONTEXT_ADD_FAV_ID: doFavorite("add", tweet.id); return true; case CONTEXT_DEL_FAV_ID: doFavorite("del", tweet.id); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } protected void draw() { getTweetAdapter().refresh(); } protected void goTop() { getTweetList().setSelection(1); } protected void adapterRefresh(){ getTweetAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!TextUtils.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } protected void specialItemClicked(int position){ } protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Tweet tweet = getContextItemTweet(position); if (tweet == null) { Log.w(TAG, "Selected item not available."); specialItemClicked(position); }else{ launchActivity(StatusActivity.createIntent(tweet)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.ListActivity; /** * TODO: 准备重构现有的几个ListActivity * * 目前几个ListActivity存在的问题是 : * 1. 因为要实现[刷新]这些功能, 父类设定了子类继承时必须要实现的方法, * 而刷新/获取其实更多的时候可以理解成是ListView的层面, 这在于讨论到底是一个"可刷新的Activity" * 还是一个拥有"可刷新的ListView"的Activity, 如果改成后者, 则只要在父类拥有一个实现了可刷新接口的ListView即可, * 而无需强制要求子类去直接实现某些方法. * 2. 父类过于专制, 比如getLayoutId()等抽象方法的存在只是为了在父类进行setContentView, 而此类方法可以下放到子类去自行实现, * 诸如此类的, 应该下放给子类更自由的空间. 理想状态为不使用抽象类. * 3. 随着功能扩展, 需要将几个不同的ListActivity子类重复的部分重新抽象到父类来, 已减少代码重复. * 4. TwitterList和UserList代码存在重复现象, 可抽象. * 5. TwitterList目前过于依赖Cursor类型的List, 而没有Array类型的抽象类. * */ public class BaseListActivity extends ListActivity { }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.ch_linghu.fanfoudroid.AboutActivity; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.PreferencesActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.Weibo; import com.ch_linghu.fanfoudroid.service.TwitterService; /** * A BaseActivity has common routines and variables for an Activity that * contains a list of tweets and a text input field. * * Not the cleanest design, but works okay for several Activities in this app. */ public class BaseActivity extends Activity { private static final String TAG = "BaseActivity"; protected SharedPreferences mPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); _onCreate(savedInstanceState); } // 因为onCreate方法无法返回状态,因此无法进行状态判断, // 为了能对上层返回的信息进行判断处理,我们使用_onCreate代替真正的 // onCreate进行工作。onCreate仅在顶层调用_onCreate。 protected boolean _onCreate(Bundle savedInstanceState) { if (TwitterApplication.mPref.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } if (!checkIsLogedIn()) { return false; } else { PreferenceManager.setDefaultValues(this, R.xml.preferences, false); mPreferences = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(this); return true; } } protected void handleLoggedOut() { if (isTaskRoot()) { showLogin(); } else { setResult(RESULT_LOGOUT); } finish(); } public TwitterDatabase getDb() { return TwitterApplication.mDb; } public Weibo getApi() { return TwitterApplication.mApi; } public SharedPreferences getPreferences() { return mPreferences; } @Override protected void onDestroy() { super.onDestroy(); } protected boolean isLoggedIn() { return getApi().isLoggedIn(); } private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1; // Retrieve interface // public ImageManager getImageManager() { // return TwitterApplication.mImageManager; // } private void _logout() { TwitterService.unschedule(BaseActivity.this); getDb().clearData(); getApi().reset(); // Clear SharedPreferences SharedPreferences.Editor editor = mPreferences.edit(); editor.clear(); editor.commit(); // TODO: 提供用户手动情况所有缓存选项 TwitterApplication.mImageLoader.getImageManager().clear(); // TODO: cancel notifications. TwitterService.unschedule(BaseActivity.this); handleLoggedOut(); } public void logout() { Dialog dialog = new AlertDialog.Builder(BaseActivity.this) .setTitle("提示").setMessage("确实要注销吗?") .setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { _logout(); } }).setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); dialog.show(); } protected void showLogin() { Intent intent = new Intent(this, LoginActivity.class); // TODO: might be a hack? intent.putExtra(Intent.EXTRA_INTENT, getIntent()); startActivity(intent); } protected void manageUpdateChecks() { //检查后台更新状态设置 boolean isUpdateEnabled = mPreferences.getBoolean( Preferences.CHECK_UPDATES_KEY, false); if (isUpdateEnabled) { TwitterService.schedule(this); } else if (!TwitterService.isWidgetEnabled()) { TwitterService.unschedule(this); } //检查强制竖屏设置 boolean isOrientationPortrait = mPreferences.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false); if (isOrientationPortrait) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } } // Menus. protected static final int OPTIONS_MENU_ID_LOGOUT = 1; protected static final int OPTIONS_MENU_ID_PREFERENCES = 2; protected static final int OPTIONS_MENU_ID_ABOUT = 3; protected static final int OPTIONS_MENU_ID_SEARCH = 4; protected static final int OPTIONS_MENU_ID_REPLIES = 5; protected static final int OPTIONS_MENU_ID_DM = 6; protected static final int OPTIONS_MENU_ID_TWEETS = 7; protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8; protected static final int OPTIONS_MENU_ID_FOLLOW = 9; protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10; protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11; protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12; protected static final int OPTIONS_MENU_ID_EXIT = 13; /** * 如果增加了Option Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复 * * @return 最大的Option Menu常量 */ protected int getLastOptionMenuId() { return OPTIONS_MENU_ID_EXIT; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // SubMenu submenu = // menu.addSubMenu(R.string.write_label_insert_picture); // submenu.setIcon(android.R.drawable.ic_menu_gallery); // // submenu.add(0, OPTIONS_MENU_ID_IMAGE_CAPTURE, 0, // R.string.write_label_take_a_picture); // submenu.add(0, OPTIONS_MENU_ID_PHOTO_LIBRARY, 0, // R.string.write_label_choose_a_picture); // // MenuItem item = menu.add(0, OPTIONS_MENU_ID_SEARCH, 0, // R.string.omenu_search); // item.setIcon(android.R.drawable.ic_search_category_default); // item.setAlphabeticShortcut(SearchManager.MENU_KEY); MenuItem item; item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0, R.string.omenu_settings); item.setIcon(android.R.drawable.ic_menu_preferences); item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout); item.setIcon(android.R.drawable.ic_menu_revert); item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about); item.setIcon(android.R.drawable.ic_menu_info_details); item = menu.add(0, OPTIONS_MENU_ID_EXIT, 0, R.string.omenu_exit); item.setIcon(android.R.drawable.ic_menu_rotate); return true; } protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0; protected static final int REQUEST_CODE_PREFERENCES = 1; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_LOGOUT: logout(); return true; case OPTIONS_MENU_ID_SEARCH: onSearchRequested(); return true; case OPTIONS_MENU_ID_PREFERENCES: Intent launchPreferencesIntent = new Intent().setClass(this, PreferencesActivity.class); startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES); return true; case OPTIONS_MENU_ID_ABOUT: //AboutDialog.show(this); Intent intent = new Intent().setClass(this, AboutActivity.class); startActivity(intent); return true; case OPTIONS_MENU_ID_EXIT: exit(); return true; } return super.onOptionsItemSelected(item); } protected void exit() { TwitterService.unschedule(this); Intent i = new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); startActivity(i); } protected void launchActivity(Intent intent) { // TODO: probably don't need this result chaining to finish upon logout. // since the subclasses have to check in onResume. startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY); } protected void launchDefaultActivity() { Intent intent = new Intent(); intent.setClass(this, TwitterActivity.class); startActivity(intent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) { manageUpdateChecks(); } else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY && resultCode == RESULT_LOGOUT) { Log.d(TAG, "Result logout."); handleLoggedOut(); } } protected boolean checkIsLogedIn() { if (!getApi().isLoggedIn()) { Log.d(TAG, "Not logged in."); handleLoggedOut(); return false; } return true; } public static boolean isTrue(Bundle bundle, String key) { return bundle != null && bundle.containsKey(key) && bundle.getBoolean(key); } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.text.TextPaint; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.SearchActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.MenuDialog; import com.ch_linghu.fanfoudroid.ui.module.NavBar; /** * @deprecated 使用 {@link NavBar} 代替 */ public class WithHeaderActivity extends BaseActivity { private static final String TAG = "WithHeaderActivity"; public static final int HEADER_STYLE_HOME = 1; public static final int HEADER_STYLE_WRITE = 2; public static final int HEADER_STYLE_BACK = 3; public static final int HEADER_STYLE_SEARCH = 4; protected ImageView refreshButton; protected ImageButton searchButton; protected ImageButton writeButton; protected TextView titleButton; protected Button backButton; protected ImageButton homeButton; protected MenuDialog dialog; protected EditText searchEdit; protected Feedback mFeedback; // FIXME: 刷新动画二选一, DELETE ME protected AnimationDrawable mRefreshAnimation; protected ProgressBar mProgress = null; protected ProgressBar mLoadingProgress = null; //搜索硬按键行为 @Override public boolean onSearchRequested() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } // LOGO按钮 protected void addTitleButton() { titleButton = (TextView) findViewById(R.id.title); titleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int top = titleButton.getTop(); int height = titleButton.getHeight(); int x = top + height; if (null == dialog) { Log.d(TAG, "Create menu dialog."); dialog = new MenuDialog(WithHeaderActivity.this); dialog.bindEvent(WithHeaderActivity.this); dialog.setPosition(-1, x); } // toggle dialog if (dialog.isShowing()) { dialog.dismiss(); //没机会触发 } else { dialog.show(); } } }); } protected void setHeaderTitle(String title) { titleButton.setBackgroundDrawable( new BitmapDrawable()); titleButton.setText(title); LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT); lp.setMargins(3, 12, 0, 0); titleButton.setLayoutParams(lp); // 中文粗体 TextPaint tp = titleButton.getPaint(); tp.setFakeBoldText(true); } protected void setHeaderTitle(int resource) { titleButton.setBackgroundResource(resource); } // 刷新 protected void addRefreshButton() { final Activity that = this; refreshButton = (ImageView) findViewById(R.id.top_refresh); // FIXME: 暂时取消旋转效果, 测试ProgressBar //refreshButton.setBackgroundResource(R.drawable.top_refresh); //mRefreshAnimation = (AnimationDrawable) refreshButton.getBackground(); // FIXME: DELETE ME mProgress = (ProgressBar) findViewById(R.id.progress_bar); mLoadingProgress = (ProgressBar) findViewById(R.id.top_refresh_progressBar); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); refreshButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (that instanceof Refreshable) { ((Refreshable) that).doRetrieve(); } else { Log.e(TAG, "The current view " + that.getClass().getName() + " cann't be retrieved"); } } }); } /** * @param v * @deprecated use {@link WithHeaderActivity#setRefreshAnimation(boolean)} */ protected void animRotate(View v) { setRefreshAnimation(true); } /** * @param progress 0~100 * @deprecated use feedback */ public void setGlobalProgress(int progress) { if ( null != mProgress) { mProgress.setProgress(progress); } } /** * Start/Stop Top Refresh Button's Animation * * @param animate start or stop * @deprecated use feedback */ public void setRefreshAnimation(boolean animate) { if (mRefreshAnimation != null) { if (animate) { mRefreshAnimation.start(); } else { mRefreshAnimation.setVisible(true, true); // restart mRefreshAnimation.start(); // goTo frame 0 mRefreshAnimation.stop(); } } else { Log.w(TAG, "mRefreshAnimation is null"); } } // 搜索 protected void addSearchButton() { searchButton = (ImageButton) findViewById(R.id.search); searchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // // 旋转动画 // Animation anim = AnimationUtils.loadAnimation(v.getContext(), // R.anim.scale_lite); // v.startAnimation(anim); //go to SearchActivity startSearch(); } }); } // 这个方法会在SearchActivity里重写 protected boolean startSearch() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } //搜索框 protected void addSearchBox() { searchEdit = (EditText) findViewById(R.id.search_edit); } // 撰写 protected void addWriteButton() { writeButton = (ImageButton) findViewById(R.id.writeMessage); writeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to write activity Intent intent = new Intent(); intent.setClass(v.getContext(), WriteActivity.class); v.getContext().startActivity(intent); } }); } // 回首页 protected void addHomeButton() { homeButton = (ImageButton) findViewById(R.id.home); homeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to TwitterActivity Intent intent = new Intent(); intent.setClass(v.getContext(), TwitterActivity.class); v.getContext().startActivity(intent); } }); } // 返回 protected void addBackButton() { backButton = (Button) findViewById(R.id.top_back); // 中文粗体 // TextPaint tp = backButton.getPaint(); // tp.setFakeBoldText(true); backButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Go back to previous activity finish(); } }); } protected void initHeader(int style) { //FIXME: android 1.6似乎不支持addHeaderView中使用的方法 // 来增加header,造成header无法显示和使用。 // 改用在layout xml里include的方法来确保显示 switch (style) { case HEADER_STYLE_HOME: //addHeaderView(R.layout.header); addTitleButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_BACK: //addHeaderView(R.layout.header_back); addBackButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_WRITE: //addHeaderView(R.layout.header_write); addBackButton(); //addHomeButton(); break; case HEADER_STYLE_SEARCH: //addHeaderView(R.layout.header_search); addBackButton(); addSearchBox(); addSearchButton(); break; } } private void addHeaderView(int resource) { // find content root view ViewGroup root = (ViewGroup) getWindow().getDecorView(); ViewGroup content = (ViewGroup) root.getChildAt(0); View header = View.inflate(WithHeaderActivity.this, resource, null); // LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); content.addView(header, 0); } @Override protected void onDestroy() { // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception if (dialog != null){ dialog.dismiss(); } super.onDestroy(); } }
Java
package com.ch_linghu.fanfoudroid.ui.base; public interface Refreshable { void doRetrieve(); }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.UserTimelineActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; public abstract class UserListBaseActivity extends BaseActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected NavBar mNavbar; protected Feedback mFeedback; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; private static final String USER_ID = "userId"; // Tasks. protected GenericTask mFavTask; private TaskListener mFavTaskListener = new TaskAdapter() { @Override public String getName() { return "FavoriteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onFavSuccess(); } else if (result == TaskResult.IO_ERROR) { onFavFailure(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getUserList(); abstract protected TweetAdapter getUserAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected User getContextItemUser(int position); abstract protected void updateTweet(Tweet tweet); protected abstract String getUserId();// 获得用户id public static final int CONTENT_PROFILE_ID = Menu.FIRST + 1; public static final int CONTENT_STATUS_ID = Menu.FIRST + 2; public static final int CONTENT_DEL_FRIEND = Menu.FIRST + 3; public static final int CONTENT_ADD_FRIEND = Menu.FIRST + 4; public static final int CONTENT_SEND_DM = Menu.FIRST + 5; public static final int CONTENT_SEND_MENTION = Menu.FIRST + 6; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复 * * @return 最大的Context Menu常量 */ // protected int getLastContextMenuId(){ // return CONTEXT_DEL_FAV_ID; // } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(getLayoutId()); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getUserList()); registerOnClickListener(getUserList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()) { AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return; } menu.add(0, CONTENT_PROFILE_ID, 0, user.screenName + getResources().getString( R.string.cmenu_user_profile_prefix)); menu.add(0, CONTENT_STATUS_ID, 0, user.screenName + getResources().getString(R.string.cmenu_user_status)); menu.add(0, CONTENT_SEND_MENTION, 0, getResources().getString(R.string.cmenu_user_send_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_sendmention_suffix)); menu.add(0, CONTENT_SEND_DM, 0, getResources().getString(R.string.cmenu_user_send_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_senddm_suffix)); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTENT_PROFILE_ID: launchActivity(ProfileActivity.createIntent(user.id)); return true; case CONTENT_STATUS_ID: launchActivity(UserTimelineActivity .createIntent(user.id, user.name)); return true; case CONTENT_DEL_FRIEND: delFriend(user.id); return true; case CONTENT_ADD_FRIEND: addFriend(user.id); return true; case CONTENT_SEND_MENTION: launchActivity(WriteActivity.createNewTweetIntent(String.format( "@%s ", user.screenName))); return true; case CONTENT_SEND_DM: launchActivity(WriteDmActivity.createIntent(user.id)); return true; default: return super.onContextItemSelected(item); } } /** * 取消关注 * * @param id */ private void delFriend(final String id) { Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this) .setTitle("关注提示").setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask .setListener(cancelFollowingTaskLinstener); TaskParams params = new TaskParams(); params.put(USER_ID, id); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } private GenericTask cancelFollowingTask; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { // TODO:userid String userId = params[0].getString(USER_ID); getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("添加关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_notfollowing)); // followingBtn.setOnClickListener(setfollowingListener); Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; private GenericTask setFollowingTask; /** * 设置关注 * * @param id */ private void addFriend(String id) { Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this) .setTitle("关注提示").setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(setFollowingTaskLinstener); TaskParams params = new TaskParams(); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String userId = params[0].getString(USER_ID); getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener setFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("取消关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_isfollowing)); // followingBtn.setOnClickListener(cancelFollowingListener); Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } private void draw() { getUserAdapter().refresh(); } private void goTop() { getUserList().setSelection(0); } protected void adapterRefresh() { getUserAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!TextUtils.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setFeedback(mFeedback); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } protected void specialItemClicked(int position) { } /* * TODO:单击列表项 */ protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(getBaseContext(), "选择第"+position+"个列表",Toast.LENGTH_SHORT).show(); User user = getContextItemUser(position); if (user == null) { Log.w(TAG, "selected item not available"); specialItemClicked(position); } else { launchActivity(ProfileActivity.createIntent(user.id)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; public abstract class UserArrayBaseActivity extends UserListBaseActivity { static final String TAG = "UserArrayBaseActivity"; // Views. protected ListView mUserList; protected UserArrayAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次100用户 public abstract Paging getCurrentPage();// 加载 public abstract Paging getNextPage();// 加载 // protected abstract String[] getIds(); protected abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException; private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { doRetrieve();// 加载第一页 return true; } else { return false; } } @Override public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { draw(); } updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; public void updateProgress(String progress) { mProgressText.setText(progress); } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } /** * TODO:从API获取当前Followers * * @author Dino * */ private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } return TaskResult.OK; } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected void setupState() { setTitle(getActivityTitle()); mUserList = (ListView) findViewById(R.id.follower_list); setupListHeader(true); mUserListAdapter = new UserArrayAdapter(this); mUserList.setAdapter(mUserListAdapter); allUserList = new ArrayList<com.ch_linghu.fanfoudroid.data.User>(); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected boolean useBasicMenu() { return true; } @Override protected User getContextItemUser(int position) { // position = position - 1; // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { User item = (User) mUserListAdapter.getItem(position); if (item == null) { return null; } else { return item; } } else { return null; } } /** * TODO:不知道啥用 */ @Override protected void updateTweet(Tweet tweet) { // TODO Auto-generated method stub } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add footer to Listview View footer = View.inflate(this, R.layout.listview_footer, null); mUserList.addFooterView(footer, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); } @Override protected void specialItemClicked(int position) { if (position == mUserList.getCount() - 1) { // footer loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); mFeedback.start(""); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); mFeedback.success(""); loadMoreGIF.setVisibility(View.GONE); } }; /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getNextPage()); mFeedback.update(60); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } // 将获取到的数据(保存/更新)到数据库 getDb().syncWeiboUsers(usersList); mFeedback.update(100 - (int) Math.floor(usersList.size() * 2)); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } mFeedback.update(99); return TaskResult.OK; } } public void draw() { mUserListAdapter.refresh(allUserList); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.util.TextHelper; public class TweetArrayAdapter extends BaseAdapter implements TweetAdapter { private static final String TAG = "TweetArrayAdapter"; protected ArrayList<Tweet> mTweets; private Context mContext; protected LayoutInflater mInflater; protected StringBuilder mMetaBuilder; private ImageLoaderCallback callback = new ImageLoaderCallback(){ @Override public void refresh(String url, Bitmap bitmap) { TweetArrayAdapter.this.refresh(); } }; public TweetArrayAdapter(Context context) { mTweets = new ArrayList<Tweet>(); mContext = context; mInflater = LayoutInflater.from(mContext); mMetaBuilder = new StringBuilder(); } @Override public int getCount() { return mTweets.size(); } @Override public Object getItem(int position) { return mTweets.get(position); } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public TextView tweetUserText; public TextView tweetText; public ImageView profileImage; public TextView metaText; public ImageView fav; public ImageView has_image; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext); boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); if (convertView == null) { view = mInflater.inflate(R.layout.tweet, parent, false); ViewHolder holder = new ViewHolder(); holder.tweetUserText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); holder.fav = (ImageView) view.findViewById(R.id.tweet_fav); holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image); view.setTag(holder); } else { view = convertView; } ViewHolder holder = (ViewHolder) view.getTag(); Tweet tweet = mTweets.get(position); holder.tweetUserText.setText(tweet.screenName); TextHelper.setSimpleTweetText(holder.tweetText, tweet.text); // holder.tweetText.setText(tweet.text, BufferType.SPANNABLE); String profileImageUrl = tweet.profileImageUrl; if (useProfileImage){ if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder, tweet.createdAt, tweet.source, tweet.inReplyToScreenName)); if (tweet.favorited.equals("true")) { holder.fav.setVisibility(View.VISIBLE); } else { holder.fav.setVisibility(View.GONE); } if (!TextUtils.isEmpty(tweet.thumbnail_pic)) { holder.has_image.setVisibility(View.VISIBLE); } else { holder.has_image.setVisibility(View.GONE); } return view; } public void refresh(ArrayList<Tweet> tweets) { mTweets = tweets; notifyDataSetChanged(); } @Override public void refresh() { notifyDataSetChanged(); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.widget.ListAdapter; public interface TweetAdapter extends ListAdapter{ void refresh(); }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.app.Activity; import android.view.MotionEvent; import com.ch_linghu.fanfoudroid.BrowseActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; /** * MyActivityFlipper 利用左右滑动手势切换Activity * * 1. 切换Activity, 继承与 {@link ActivityFlipper} 2. 手势识别, 实现接口 * {@link Widget.OnGestureListener} * */ public class MyActivityFlipper extends ActivityFlipper implements Widget.OnGestureListener { public MyActivityFlipper() { super(); } public MyActivityFlipper(Activity activity) { super(activity); // TODO Auto-generated constructor stub } // factory public static MyActivityFlipper create(Activity activity) { MyActivityFlipper flipper = new MyActivityFlipper(activity); flipper.addActivity(BrowseActivity.class); flipper.addActivity(TwitterActivity.class); flipper.addActivity(MentionActivity.class); flipper.setToastResource(new int[] { R.drawable.point_left, R.drawable.point_center, R.drawable.point_right }); flipper.setInAnimation(R.anim.push_left_in); flipper.setOutAnimation(R.anim.push_left_out); flipper.setPreviousInAnimation(R.anim.push_right_in); flipper.setPreviousOutAnimation(R.anim.push_right_out); return flipper; } @Override public boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; // do nothing } @Override public boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; // do nothing } @Override public boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { autoShowNext(); return true; } @Override public boolean onFlingRight(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { autoShowPrevious(); return true; } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.AbsListView; import android.widget.ListView; public class MyListView extends ListView implements ListView.OnScrollListener { private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE; public MyListView(Context context, AttributeSet attrs) { super(context, attrs); setOnScrollListener(this); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { boolean result = super.onInterceptTouchEvent(event); if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) { return true; } return result; } private OnNeedMoreListener mOnNeedMoreListener; public static interface OnNeedMoreListener { public void needMore(); } public void setOnNeedMoreListener(OnNeedMoreListener onNeedMoreListener) { mOnNeedMoreListener = onNeedMoreListener; } private int mFirstVisibleItem; @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mOnNeedMoreListener == null) { return; } if (firstVisibleItem != mFirstVisibleItem) { if (firstVisibleItem + visibleItemCount >= totalItemCount) { mOnNeedMoreListener.needMore(); } } else { mFirstVisibleItem = firstVisibleItem; } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mScrollState = scrollState; } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Color; import android.text.Layout; import android.text.Spannable; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.text.style.URLSpan; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; public class MyTextView extends TextView { private static float mFontSize = 15; private static boolean mFontSizeChanged = true; public MyTextView(Context context) { super(context, null); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); setLinksClickable(false); Resources res = getResources(); int color = res.getColor(R.color.link_color); setLinkTextColor(color); initFontSize(); } public void initFontSize() { if ( mFontSizeChanged ) { mFontSize = getFontSizeFromPreferences(mFontSize); setFontSizeChanged(false); // reset } setTextSize(mFontSize); } private float getFontSizeFromPreferences(float defaultValue) { SharedPreferences preferences = TwitterApplication.mPref; if (preferences.contains(Preferences.UI_FONT_SIZE)) { Log.v("DEBUG", preferences.getString(Preferences.UI_FONT_SIZE, "null") + " CHANGE FONT SIZE"); return Float.parseFloat(preferences.getString( Preferences.UI_FONT_SIZE, "14")); } return defaultValue; } private URLSpan mCurrentLink; private ForegroundColorSpan mLinkFocusStyle = new ForegroundColorSpan( Color.RED); @Override public boolean onTouchEvent(MotionEvent event) { CharSequence text = getText(); int action = event.getAction(); if (!(text instanceof Spannable)) { return super.onTouchEvent(event); } Spannable buffer = (Spannable) text; if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) { TextView widget = this; int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); URLSpan[] link = buffer.getSpans(off, off, URLSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { if (mCurrentLink == link[0]) { link[0].onClick(widget); } mCurrentLink = null; buffer.removeSpan(mLinkFocusStyle); } else if (action == MotionEvent.ACTION_DOWN) { mCurrentLink = link[0]; buffer.setSpan(mLinkFocusStyle, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return true; } } mCurrentLink = null; buffer.removeSpan(mLinkFocusStyle); return super.onTouchEvent(event); } public static void setFontSizeChanged(boolean isChanged) { mFontSizeChanged = isChanged; } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.util.Log; public class FeedbackFactory { private static final String TAG = "FeedbackFactory"; public static enum FeedbackType { DIALOG, PROGRESS, REFRESH }; public static Feedback create(Context context, FeedbackType type) { Feedback feedback = null; switch (type) { case PROGRESS: feedback = new SimpleFeedback(context); break; } if (null == feedback || !feedback.isAvailable()) { feedback = new FeedbackAdapter(context); Log.e(TAG, type + " feedback is not available."); } return feedback; } public static class FeedbackAdapter implements Feedback { public FeedbackAdapter(Context context) {} @Override public void start(CharSequence text) {} @Override public void cancel(CharSequence text) {} @Override public void success(CharSequence text) {} @Override public void failed(CharSequence text) {} @Override public void update(Object arg0) {} @Override public boolean isAvailable() { return true; } @Override public void setIndeterminate(boolean indeterminate) {} } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import java.util.List; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.ch_linghu.fanfoudroid.R; public class SimpleFeedback implements Feedback, Widget { private static final String TAG = "SimpleFeedback"; public static final int MAX = 100; private ProgressBar mProgress = null; private ProgressBar mLoadingProgress = null; public SimpleFeedback(Context context) { mProgress = (ProgressBar) ((Activity) context) .findViewById(R.id.progress_bar); mLoadingProgress = (ProgressBar) ((Activity) context) .findViewById(R.id.top_refresh_progressBar); } @Override public void start(CharSequence text) { mProgress.setProgress(20); mLoadingProgress.setVisibility(View.VISIBLE); } @Override public void success(CharSequence text) { mProgress.setProgress(100); mLoadingProgress.setVisibility(View.GONE); resetProgressBar(); } @Override public void failed(CharSequence text) { resetProgressBar(); showMessage(text); } @Override public void cancel(CharSequence text) { } @Override public void update(Object arg0) { if (arg0 instanceof Integer) { mProgress.setProgress((Integer) arg0); } else if (arg0 instanceof CharSequence) { showMessage((String) arg0); } } @Override public void setIndeterminate(boolean indeterminate) { mProgress.setIndeterminate(indeterminate); } @Override public Context getContext() { if (mProgress != null) { return mProgress.getContext(); } if (mLoadingProgress != null) { return mLoadingProgress.getContext(); } return null; } @Override public boolean isAvailable() { if (null == mProgress) { Log.e(TAG, "R.id.progress_bar is missing"); return false; } if (null == mLoadingProgress) { Log.e(TAG, "R.id.top_refresh_progressBar is missing"); return false; } return true; } /** * @param total 0~100 * @param maxSize max size of list * @param list * @return */ public static int calProgressBySize(int total, int maxSize, List<?> list) { if (null != list) { return (MAX - (int)Math.floor(list.size() * (total/maxSize))); } return MAX; } private void resetProgressBar() { if (mProgress.isIndeterminate()) { //TODO: 第二次不会出现 mProgress.setIndeterminate(false); } mProgress.setProgress(0); } private void showMessage(CharSequence text) { Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show(); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Weibo; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; //TODO: /* * 用于用户的Adapter */ public class UserArrayAdapter extends BaseAdapter implements TweetAdapter{ private static final String TAG = "UserArrayAdapter"; private static final String USER_ID="userId"; protected ArrayList<User> mUsers; private Context mContext; protected LayoutInflater mInflater; public UserArrayAdapter(Context context) { mUsers = new ArrayList<User>(); mContext = context; mInflater = LayoutInflater.from(mContext); } @Override public int getCount() { return mUsers.size(); } @Override public Object getItem(int position) { return mUsers.get(position); } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public ImageView profileImage; public TextView screenName; public TextView userId; public TextView lastStatus; public TextView followBtn; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext); boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); if (convertView == null) { view = mInflater.inflate(R.layout.follower_item, parent, false); ViewHolder holder = new ViewHolder(); holder.profileImage = (ImageView) view.findViewById(R.id.profile_image); holder.screenName = (TextView) view.findViewById(R.id.screen_name); holder.userId = (TextView) view.findViewById(R.id.user_id); //holder.lastStatus = (TextView) view.findViewById(R.id.last_status); holder.followBtn = (TextView) view.findViewById(R.id.follow_btn); view.setTag(holder); } else { view = convertView; } ViewHolder holder = (ViewHolder) view.getTag(); final User user = mUsers.get(position); String profileImageUrl = user.profileImageUrl; if (useProfileImage){ if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } //holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap); holder.screenName.setText(user.screenName); holder.userId.setText(user.id); //holder.lastStatus.setText(user.lastStatus); holder.followBtn.setText(user.isFollowing ? mContext .getString(R.string.general_del_friend) : mContext .getString(R.string.general_add_friend)); holder.followBtn.setOnClickListener(user.isFollowing?new OnClickListener(){ @Override public void onClick(View v) { //Toast.makeText(mContext, user.name+"following", Toast.LENGTH_SHORT).show(); delFriend(user.id); }}:new OnClickListener(){ @Override public void onClick(View v) { //Toast.makeText(mContext, user.name+"not following", Toast.LENGTH_SHORT).show(); addFriend(user.id); }}); return view; } public void refresh(ArrayList<User> users) { mUsers = users; notifyDataSetChanged(); } @Override public void refresh() { notifyDataSetChanged(); } private ImageLoaderCallback callback = new ImageLoaderCallback(){ @Override public void refresh(String url, Bitmap bitmap) { UserArrayAdapter.this.refresh(); } }; /** * 取消关注 * @param id */ private void delFriend(final String id) { Builder diaBuilder = new AlertDialog.Builder(mContext) .setTitle("关注提示").setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask .setListener(cancelFollowingTaskLinstener); TaskParams params = new TaskParams(); params.put(USER_ID, id); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } private GenericTask cancelFollowingTask; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { //TODO:userid String userId=params[0].getString(USER_ID); getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("添加关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_notfollowing)); // followingBtn.setOnClickListener(setfollowingListener); Toast.makeText(mContext, "取消关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(mContext, "取消关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; private GenericTask setFollowingTask; /** * 设置关注 * @param id */ private void addFriend(String id){ Builder diaBuilder = new AlertDialog.Builder(mContext) .setTitle("关注提示").setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(setFollowingTaskLinstener); TaskParams params = new TaskParams(); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String userId=params[0].getString(USER_ID); getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener setFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("取消关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_isfollowing)); // followingBtn.setOnClickListener(cancelFollowingListener); Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; public Weibo getApi() { return TwitterApplication.mApi; } }
Java
package com.ch_linghu.fanfoudroid.ui.module; public interface IFlipper { void showNext(); void showPrevious(); }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; public interface Widget { Context getContext(); // TEMP public static interface OnGestureListener { /** * @param e1 * The first down motion event that started the fling. * @param e2 * The move motion event that triggered the current onFling. * @param velocityX * The velocity of this fling measured in pixels per second * along the x axis. * @param velocityY * The velocity of this fling measured in pixels per second * along the y axis. * @return true if the event is consumed, else false * * @see SimpleOnGestureListener#onFling */ boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); boolean onFlingRight(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); } public static interface OnRefreshListener { void onRefresh(); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.text.TextPaint; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.SearchActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.ui.base.Refreshable; public class NavBar implements Widget { private static final String TAG = "NavBar"; public static final int HEADER_STYLE_HOME = 1; public static final int HEADER_STYLE_WRITE = 2; public static final int HEADER_STYLE_BACK = 3; public static final int HEADER_STYLE_SEARCH = 4; private ImageView mRefreshButton; private ImageButton mSearchButton; private ImageButton mWriteButton; private TextView mTitleButton; private Button mBackButton; private ImageButton mHomeButton; private MenuDialog mDialog; private EditText mSearchEdit; /** @deprecated 已废弃 */ protected AnimationDrawable mRefreshAnimation; private ProgressBar mProgressBar = null; // 进度条(横) private ProgressBar mLoadingProgress = null; // 旋转图标 public NavBar(int style, Context context) { initHeader(style, (Activity) context); } private void initHeader(int style, final Activity activity) { switch (style) { case HEADER_STYLE_HOME: addTitleButtonTo(activity); addWriteButtonTo(activity); addSearchButtonTo(activity); addRefreshButtonTo(activity); break; case HEADER_STYLE_BACK: addBackButtonTo(activity); addWriteButtonTo(activity); addSearchButtonTo(activity); addRefreshButtonTo(activity); break; case HEADER_STYLE_WRITE: addBackButtonTo(activity); break; case HEADER_STYLE_SEARCH: addBackButtonTo(activity); addSearchBoxTo(activity); addSearchButtonTo(activity); break; } } /** * 搜索硬按键行为 * @deprecated 这个不晓得还有没有用, 已经是已经被新的搜索替代的吧 ? */ public boolean onSearchRequested() { /* Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); */ return true; } /** * 添加[LOGO/标题]按钮 * @param acticity */ private void addTitleButtonTo(final Activity acticity) { mTitleButton = (TextView) acticity.findViewById(R.id.title); mTitleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int top = mTitleButton.getTop(); int height = mTitleButton.getHeight(); int x = top + height; if (null == mDialog) { Log.d(TAG, "Create menu dialog."); mDialog = new MenuDialog(acticity); mDialog.bindEvent(acticity); mDialog.setPosition(-1, x); } // toggle dialog if (mDialog.isShowing()) { mDialog.dismiss(); // 没机会触发 } else { mDialog.show(); } } }); } /** * 设置标题 * @param title */ public void setHeaderTitle(String title) { if (null != mTitleButton) { mTitleButton.setText(title); TextPaint tp = mTitleButton.getPaint(); tp.setFakeBoldText(true); // 中文粗体 } } /** * 设置标题 * @param resource R.string.xxx */ public void setHeaderTitle(int resource) { if (null != mTitleButton) { mTitleButton.setBackgroundResource(resource); } } /** * 添加[刷新]按钮 * @param activity */ private void addRefreshButtonTo(final Activity activity) { mRefreshButton = (ImageView) activity.findViewById(R.id.top_refresh); // FIXME: DELETE ME 暂时取消旋转效果, 测试ProgressBar // refreshButton.setBackgroundResource(R.drawable.top_refresh); // mRefreshAnimation = (AnimationDrawable) // refreshButton.getBackground(); mProgressBar = (ProgressBar) activity.findViewById(R.id.progress_bar); mLoadingProgress = (ProgressBar) activity .findViewById(R.id.top_refresh_progressBar); mRefreshButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (activity instanceof Refreshable) { ((Refreshable) activity).doRetrieve(); } else { Log.e(TAG, "The current view " + activity.getClass().getName() + " cann't be retrieved"); } } }); } /** * Start/Stop Top Refresh Button's Animation * * @param animate * start or stop * @deprecated use feedback */ public void setRefreshAnimation(boolean animate) { if (mRefreshAnimation != null) { if (animate) { mRefreshAnimation.start(); } else { mRefreshAnimation.setVisible(true, true); // restart mRefreshAnimation.start(); // goTo frame 0 mRefreshAnimation.stop(); } } else { Log.w(TAG, "mRefreshAnimation is null"); } } /** * 添加[搜索]按钮 * @param activity */ private void addSearchButtonTo(final Activity activity) { mSearchButton = (ImageButton) activity.findViewById(R.id.search); mSearchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startSearch(activity); } }); } // 这个方法会在SearchActivity里重写 protected boolean startSearch(final Activity activity) { Intent intent = new Intent(); intent.setClass(activity, SearchActivity.class); activity.startActivity(intent); return true; } /** * 添加[搜索框] * @param activity */ private void addSearchBoxTo(final Activity activity) { mSearchEdit = (EditText) activity.findViewById(R.id.search_edit); } /** * 添加[撰写]按钮 * @param activity */ private void addWriteButtonTo(final Activity activity) { mWriteButton = (ImageButton) activity.findViewById(R.id.writeMessage); mWriteButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // forward to write activity Intent intent = new Intent(); intent.setClass(v.getContext(), WriteActivity.class); v.getContext().startActivity(intent); } }); } /** * 添加[回首页]按钮 * @param activity */ @SuppressWarnings("unused") private void addHomeButton(final Activity activity) { mHomeButton = (ImageButton) activity.findViewById(R.id.home); mHomeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to TwitterActivity Intent intent = new Intent(); intent.setClass(v.getContext(), TwitterActivity.class); v.getContext().startActivity(intent); } }); } /** * 添加[返回]按钮 * @param activity */ private void addBackButtonTo(final Activity activity) { mBackButton = (Button) activity.findViewById(R.id.top_back); // 中文粗体 // TextPaint tp = backButton.getPaint(); // tp.setFakeBoldText(true); mBackButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Go back to previous activity activity.finish(); } }); } public void destroy() { // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception if (mDialog != null) { mDialog.dismiss(); mDialog = null; } mRefreshButton = null; mSearchButton = null; mWriteButton = null; mTitleButton = null; mBackButton = null; mHomeButton = null; mSearchButton = null; mSearchEdit = null; mProgressBar = null; mLoadingProgress = null; } public ImageView getRefreshButton() { return mRefreshButton; } public ImageButton getSearchButton() { return mSearchButton; } public ImageButton getWriteButton() { return mWriteButton; } public TextView getTitleButton() { return mTitleButton; } public Button getBackButton() { return mBackButton; } public ImageButton getHomeButton() { return mHomeButton; } public MenuDialog getDialog() { return mDialog; } public EditText getSearchEdit() { return mSearchEdit; } /** @deprecated 已废弃 */ public AnimationDrawable getRefreshAnimation() { return mRefreshAnimation; } public ProgressBar getProgressBar() { return mProgressBar; } public ProgressBar getLoadingProgress() { return mLoadingProgress; } @Override public Context getContext() { if (null != mDialog) { return mDialog.getContext(); } if (null != mTitleButton) { return mTitleButton.getContext(); } return null; } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.util.Log; import android.view.Gravity; import android.widget.ImageView; import android.widget.Toast; import android.widget.ViewSwitcher.ViewFactory; import com.ch_linghu.fanfoudroid.R; /** * ActivityFlipper, 和 {@link ViewFactory} 类似, 只是设计用于切换activity. * * 切换的前后顺序取决与注册时的先后顺序 * * USAGE: <code> * ActivityFlipper mFlipper = new ActivityFlipper(this); * mFlipper.addActivity(TwitterActivity.class); * mFlipper.addActivity(MentionActivity.class); * mFlipper.addActivity(DmActivity.class); * * // switch activity * mFlipper.setCurrentActivity(TwitterActivity.class); * mFlipper.showNext(); * mFlipper.showPrevious(); * * // or without set current activity * mFlipper.showNextOf(TwitterActivity.class); * mFlipper.showPreviousOf(TwitterActivity.class); * * // or auto mode, use the context as current activity * mFlipper.autoShowNext(); * mFlipper.autoShowPrevious(); * * // set toast * mFlipper.setToastResource(new int[] { * R.drawable.point_left, * R.drawable.point_center, * R.drawable.point_right * }); * * // set Animation * mFlipper.setInAnimation(R.anim.push_left_in); * mFlipper.setOutAnimation(R.anim.push_left_out); * mFlipper.setPreviousInAnimation(R.anim.push_right_in); * mFlipper.setPreviousOutAnimation(R.anim.push_right_out); * </code> * */ public class ActivityFlipper implements IFlipper { private static final String TAG = "ActivityFlipper"; private static final int SHOW_NEXT = 0; private static final int SHOW_PROVIOUS = 1; private int mDirection = SHOW_NEXT; private boolean mToastEnabled = false; private int[] mToastResourcesMap = new int[]{}; private boolean mAnimationEnabled = false; private int mNextInAnimation = -1; private int mNextOutAnimation = -1; private int mPreviousInAnimation = -1; private int mPreviousOutAnimation = -1; private Activity mActivity; private List<Class<?>> mActivities = new ArrayList<Class<?>>();; private int mWhichActivity = 0; public ActivityFlipper() { } public ActivityFlipper(Activity activity) { mActivity = activity; } /** * Launch Activity * * @param cls * class of activity */ public void launchActivity(Class<?> cls) { Log.v(TAG, "launch activity :" + cls.getName()); Intent intent = new Intent(); intent.setClass(mActivity, cls); mActivity.startActivity(intent); } public void setToastResource(int[] resourceIds) { mToastEnabled = true; mToastResourcesMap = resourceIds; } private void maybeShowToast(int whichActicity) { if (mToastEnabled && whichActicity < mToastResourcesMap.length) { final Toast myToast = new Toast(mActivity); final ImageView myView = new ImageView(mActivity); myView.setImageResource(mToastResourcesMap[whichActicity]); myToast.setView(myView); myToast.setDuration(Toast.LENGTH_SHORT); myToast.setGravity(Gravity.BOTTOM | Gravity.CENTER, 0, 0); myToast.show(); } } private void maybeShowAnimation(int whichActivity) { if (mAnimationEnabled) { boolean showPrevious = (mDirection == SHOW_PROVIOUS); if (showPrevious && mPreviousInAnimation != -1 && mPreviousOutAnimation != -1) { mActivity.overridePendingTransition( mPreviousInAnimation, mPreviousOutAnimation); return; // use Previous Animation } if (mNextInAnimation != -1 && mNextOutAnimation != -1) { mActivity.overridePendingTransition( mNextInAnimation, mNextOutAnimation); } } } /** * Launch Activity by index * * @param whichActivity * the index of Activity */ private void launchActivity(int whichActivity) { launchActivity(mActivities.get(whichActivity)); maybeShowToast(whichActivity); maybeShowAnimation(whichActivity); } /** * Add Activity NOTE: 添加的顺序很重要 * * @param cls * class of activity */ public void addActivity(Class<?> cls) { mActivities.add(cls); } /** * Get index of the Activity * * @param cls * class of activity * @return */ private int getIndexOf(Class<?> cls) { int index = mActivities.indexOf(cls); if (-1 == index) { Log.e(TAG, "No such activity: " + cls.getName()); } return index; } @SuppressWarnings("unused") private Class<?> getActivityAt(int index) { if (index > 0 && index < mActivities.size()) { return mActivities.get(index); } return null; } /** * Show next activity(already setCurrentActivity) */ @Override public void showNext() { mDirection = SHOW_NEXT; setDisplayedActivity(mWhichActivity + 1, true); } /** * Show next activity of * * @param cls * class of activity */ public void showNextOf(Class<?> cls) { setCurrentActivity(cls); showNext(); } /** * Show next activity(use current context as a activity) */ public void autoShowNext() { showNextOf(mActivity.getClass()); } /** * Show previous activity(already setCurrentActivity) */ @Override public void showPrevious() { mDirection = SHOW_PROVIOUS; setDisplayedActivity(mWhichActivity - 1, true); } /** * Show previous activity of * * @param cls * class of activity */ public void showPreviousOf(Class<?> cls) { setCurrentActivity(cls); showPrevious(); } /** * Show previous activity(use current context as a activity) */ public void autoShowPrevious() { showPreviousOf(mActivity.getClass()); } /** * Sets which child view will be displayed * * @param whichActivity * the index of the child view to display * @param display * display immediately */ public void setDisplayedActivity(int whichActivity, boolean display) { mWhichActivity = whichActivity; if (whichActivity >= getCount()) { mWhichActivity = 0; } else if (whichActivity < 0) { mWhichActivity = getCount() - 1; } if (display) { launchActivity(mWhichActivity); } } /** * Set current Activity * * @param cls * class of activity */ public void setCurrentActivity(Class<?> cls) { setDisplayedActivity(getIndexOf(cls), false); } public void setInAnimation(int resourceId) { setEnableAnimation(true); mNextInAnimation = resourceId; } public void setOutAnimation(int resourceId) { setEnableAnimation(true); mNextOutAnimation = resourceId; } public void setPreviousInAnimation(int resourceId) { mPreviousInAnimation = resourceId; } public void setPreviousOutAnimation(int resourceId) { mPreviousOutAnimation = resourceId; } public void setEnableAnimation(boolean enable) { mAnimationEnabled = enable; } /** * Count activities * * @return the number of activities */ public int getCount() { return mActivities.size(); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.view.Gravity; import android.view.View; import android.view.WindowManager.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.ch_linghu.fanfoudroid.BrowseActivity; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.FavoritesActivity; import com.ch_linghu.fanfoudroid.FollowersActivity; import com.ch_linghu.fanfoudroid.FollowingActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.UserTimelineActivity; /** * 顶部主菜单切换浮动层 * * @author lds * */ public class MenuDialog extends Dialog { private static final int PAGE_MINE = 0; private static final int PAGE_PROFILE = 1; private static final int PAGE_FOLLOWERS = 2; private static final int PAGE_FOLLOWING = 3; private static final int PAGE_HOME = 4; private static final int PAGE_MENTIONS = 5; private static final int PAGE_BROWSE = 6; private static final int PAGE_FAVORITES = 7; private static final int PAGE_MESSAGE = 8; private List<int[]> pages = new ArrayList<int[]>(); { pages.add(new int[] { R.drawable.menu_tweets, R.string.pages_mine }); pages.add(new int[] { R.drawable.menu_profile, R.string.pages_profile }); pages.add(new int[] { R.drawable.menu_followers, R.string.pages_followers }); pages.add(new int[] { R.drawable.menu_following, R.string.pages_following }); pages.add(new int[] { R.drawable.menu_list, R.string.pages_home }); pages.add(new int[] { R.drawable.menu_mentions, R.string.pages_mentions }); pages.add(new int[] { R.drawable.menu_listed, R.string.pages_browse }); pages.add(new int[] { R.drawable.menu_favorites, R.string.pages_search }); pages.add(new int[] { R.drawable.menu_create_list, R.string.pages_message }); }; private GridView gridview; public MenuDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); // TODO Auto-generated constructor stub } public MenuDialog(Context context, int theme) { super(context, theme); // TODO Auto-generated constructor stub } public MenuDialog(Context context) { super(context, R.style.Theme_Transparent); setContentView(R.layout.menu_dialog); // setTitle("Custom Dialog"); setCanceledOnTouchOutside(true); // 设置window属性 LayoutParams a = getWindow().getAttributes(); a.gravity = Gravity.TOP; a.dimAmount = 0; // 去背景遮盖 getWindow().setAttributes(a); initMenu(); } public void setPosition(int x, int y) { LayoutParams a = getWindow().getAttributes(); if (-1 != x) a.x = x; if (-1 != y) a.y = y; getWindow().setAttributes(a); } private void goTo(Class<?> cls, Intent intent) { if (getOwnerActivity().getClass() != cls) { dismiss(); intent.setClass(getContext(), cls); getContext().startActivity(intent); } else { String msg = getContext().getString(R.string.page_status_same_page); Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); } } private void goTo(Class<?> cls){ Intent intent = new Intent(); goTo(cls, intent); } private void initMenu() { // 准备要添加的数据条目 List<Map<String, Object>> items = new ArrayList<Map<String, Object>>(); for (int[] item : pages) { Map<String, Object> map = new HashMap<String, Object>(); map.put("image", item[0]); map.put("title", getContext().getString(item[1]) ); items.add(map); } // 实例化一个适配器 SimpleAdapter adapter = new SimpleAdapter(getContext(), items, // data R.layout.menu_item, // grid item layout new String[] { "title", "image" }, // data's key new int[] { R.id.item_text, R.id.item_image }); // item view id // 获得GridView实例 gridview = (GridView) findViewById(R.id.mygridview); // 将GridView和数据适配器关联 gridview.setAdapter(adapter); } public void bindEvent(Activity activity) { setOwnerActivity(activity); // 绑定监听器 gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { switch (position) { case PAGE_MINE: String user = TwitterApplication.getMyselfId(); String name = TwitterApplication.getMyselfName(); Intent intent = UserTimelineActivity.createIntent(user, name); goTo(UserTimelineActivity.class, intent); break; case PAGE_PROFILE: goTo(ProfileActivity.class); break; case PAGE_FOLLOWERS: goTo(FollowersActivity.class); break; case PAGE_FOLLOWING: goTo(FollowingActivity.class); break; case PAGE_HOME: goTo(TwitterActivity.class); break; case PAGE_MENTIONS: goTo(MentionActivity.class); break; case PAGE_BROWSE: goTo(BrowseActivity.class); break; case PAGE_FAVORITES: goTo(FavoritesActivity.class); break; case PAGE_MESSAGE: goTo(DmActivity.class); break; } } }); Button close_button = (Button) findViewById(R.id.close_menu); close_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.graphics.Color; import android.text.Editable; import android.text.InputFilter; import android.text.Selection; import android.text.TextWatcher; import android.view.View.OnKeyListener; import android.widget.EditText; import android.widget.TextView; public class TweetEdit { private EditText mEditText; private TextView mCharsRemainText; private int originTextColor; public TweetEdit(EditText editText, TextView charsRemainText) { mEditText = editText; mCharsRemainText = charsRemainText; originTextColor = mCharsRemainText.getTextColors().getDefaultColor(); mEditText.addTextChangedListener(mTextWatcher); mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter( MAX_TWEET_INPUT_LENGTH) }); } private static final int MAX_TWEET_LENGTH = 140; private static final int MAX_TWEET_INPUT_LENGTH = 400; public void setTextAndFocus(String text, boolean start) { setText(text); Editable editable = mEditText.getText(); if (!start){ Selection.setSelection(editable, editable.length()); }else{ Selection.setSelection(editable, 0); } mEditText.requestFocus(); } public void setText(String text) { mEditText.setText(text); updateCharsRemain(); } private TextWatcher mTextWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable e) { updateCharsRemain(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }; public void updateCharsRemain() { int remaining = MAX_TWEET_LENGTH - mEditText.length(); if (remaining < 0 ) { mCharsRemainText.setTextColor(Color.RED); } else { mCharsRemainText.setTextColor(originTextColor); } mCharsRemainText.setText(remaining + ""); } public String getText() { return mEditText.getText().toString(); } public void setEnabled(boolean b) { mEditText.setEnabled(b); } public void setOnKeyListener(OnKeyListener listener) { mEditText.setOnKeyListener(listener); } public void addTextChangedListener(TextWatcher watcher){ mEditText.addTextChangedListener(watcher); } public void requestFocus() { mEditText.requestFocus(); } public EditText getEditText() { return mEditText; } }
Java
package com.ch_linghu.fanfoudroid.ui.module; public interface Feedback { public boolean isAvailable(); public void start(CharSequence text); public void cancel(CharSequence text); public void success(CharSequence text); public void failed(CharSequence text); public void update(Object arg0); public void setIndeterminate (boolean indeterminate); }
Java
/** * */ package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.db.UserInfoTable; public class UserCursorAdapter extends CursorAdapter implements TweetAdapter { private static final String TAG = "TweetCursorAdapter"; private Context mContext; public UserCursorAdapter(Context context, Cursor cursor) { super(context, cursor); mContext = context; if (context != null) { mInflater = LayoutInflater.from(context); } if (cursor != null) { mScreenNametColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_USER_SCREEN_NAME); mUserIdColumn=cursor.getColumnIndexOrThrow(UserInfoTable._ID); mProfileImageUrlColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_PROFILE_IMAGE_URL); // mLastStatusColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_LAST_STATUS); } mMetaBuilder = new StringBuilder(); } private LayoutInflater mInflater; private int mScreenNametColumn; private int mUserIdColumn; private int mProfileImageUrlColumn; //private int mLastStatusColumn; private StringBuilder mMetaBuilder; private ImageLoaderCallback callback = new ImageLoaderCallback(){ @Override public void refresh(String url, Bitmap bitmap) { UserCursorAdapter.this.refresh(); } }; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.follower_item, parent, false); Log.d(TAG,"load newView"); UserCursorAdapter.ViewHolder holder = new ViewHolder(); holder.screenName=(TextView) view.findViewById(R.id.screen_name); holder.profileImage=(ImageView)view.findViewById(R.id.profile_image); //holder.lastStatus=(TextView) view.findViewById(R.id.last_status); holder.userId=(TextView) view.findViewById(R.id.user_id); view.setTag(holder); return view; } private static class ViewHolder { public TextView screenName; public TextView userId; public TextView lastStatus; public ImageView profileImage; } @Override public void bindView(View view, Context context, Cursor cursor) { UserCursorAdapter.ViewHolder holder = (UserCursorAdapter.ViewHolder) view .getTag(); Log.d(TAG, "cursor count="+cursor.getCount()); Log.d(TAG,"holder is null?"+(holder==null?"yes":"no")); SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);; boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (useProfileImage){ if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } holder.screenName.setText(cursor.getString(mScreenNametColumn)); holder.userId.setText(cursor.getString(mUserIdColumn)); } @Override public void refresh() { getCursor().requery(); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import com.ch_linghu.fanfoudroid.R; import android.app.Activity; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; /** * FlingGestureLIstener, 封装 {@link SimpleOnGestureListener} . * 主要用于识别类似向上下或向左右滑动等基本手势. * * 该类主要解决了与ListView自带的上下滑动冲突问题. * 解决方法为将listView的onTouchListener进行覆盖:<code> * FlingGestureListener gListener = new FlingGestureListener(this, * MyActivityFlipper.create(this)); * myListView.setOnTouchListener(gListener); * </code> * * 该类一般和实现了 {@link Widget.OnGestureListener} 接口的类共同协作. * 在识别到手势后会自动调用其相关的回调方法, 以实现手势触发事件效果. * * @see Widget.OnGestureListener * */ public class FlingGestureListener extends SimpleOnGestureListener implements OnTouchListener { private static final String TAG = "FlipperGestureListener"; private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_DISTANCE = 400; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private Widget.OnGestureListener mListener; private GestureDetector gDetector; private Activity activity; public FlingGestureListener(Activity activity, Widget.OnGestureListener listener) { this(activity, listener, null); } public FlingGestureListener(Activity activity, Widget.OnGestureListener listener, GestureDetector gDetector) { if (gDetector == null) { gDetector = new GestureDetector(activity, this); } this.gDetector = gDetector; mListener = listener; this.activity = activity; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.d(TAG, "On fling"); boolean result = super.onFling(e1, e2, velocityX, velocityY); float xDistance = Math.abs(e1.getX() - e2.getX()); float yDistance = Math.abs(e1.getY() - e2.getY()); velocityX = Math.abs(velocityX); velocityY = Math.abs(velocityY); try { if (xDistance > SWIPE_MAX_DISTANCE || yDistance > SWIPE_MAX_DISTANCE) { Log.d(TAG, "OFF_PATH"); return result; } if (velocityX > SWIPE_THRESHOLD_VELOCITY && xDistance > SWIPE_MIN_DISTANCE) { if (e1.getX() > e2.getX()) { Log.d(TAG, "<------"); result = mListener.onFlingLeft(e1, e1, velocityX, velocityY); activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); } else { Log.d(TAG, "------>"); result = mListener.onFlingRight(e1, e1, velocityX, velocityY); activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out); } } else if (velocityY > SWIPE_THRESHOLD_VELOCITY && yDistance > SWIPE_MIN_DISTANCE) { if (e1.getY() > e2.getY()) { Log.d(TAG, "up"); result = mListener.onFlingUp(e1, e1, velocityX, velocityY); } else { Log.d(TAG, "down"); result = mListener.onFlingDown(e1, e1, velocityX, velocityY); } } else { Log.d(TAG, "not hint"); } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "onFling error " + e.getMessage()); } return result; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub super.onLongPress(e); } @Override public boolean onTouch(View v, MotionEvent event) { Log.d(TAG, "On Touch"); // Within the MyGestureListener class you can now manage the // event.getAction() codes. // Note that we are now calling the gesture Detectors onTouchEvent. // And given we've set this class as the GestureDetectors listener // the onFling, onSingleTap etc methods will be executed. return gDetector.onTouchEvent(event); } public GestureDetector getDetector() { return gDetector; } }
Java
/** * */ package com.ch_linghu.fanfoudroid.ui.module; import java.text.ParseException; import java.util.Date; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.app.SimpleImageLoader; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.util.TextHelper; public class TweetCursorAdapter extends CursorAdapter implements TweetAdapter { private static final String TAG = "TweetCursorAdapter"; private Context mContext; public TweetCursorAdapter(Context context, Cursor cursor) { super(context, cursor); mContext = context; if (context != null) { mInflater = LayoutInflater.from(context); } if (cursor != null) { //TODO: 可使用: //Tweet tweet = StatusTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME); mTextColumn = cursor.getColumnIndexOrThrow(StatusTable.TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(StatusTable.CREATED_AT); mSourceColumn = cursor.getColumnIndexOrThrow(StatusTable.SOURCE); mInReplyToScreenName = cursor .getColumnIndexOrThrow(StatusTable.IN_REPLY_TO_SCREEN_NAME); mFavorited = cursor.getColumnIndexOrThrow(StatusTable.FAVORITED); mThumbnailPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_THUMB); mMiddlePic = cursor.getColumnIndexOrThrow(StatusTable.PIC_MID); mOriginalPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_ORIG); } mMetaBuilder = new StringBuilder(); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mCreatedAtColumn; private int mSourceColumn; private int mInReplyToScreenName; private int mFavorited; private int mThumbnailPic; private int mMiddlePic; private int mOriginalPic; private StringBuilder mMetaBuilder; /* private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){ @Override public void refresh(String url, Bitmap bitmap) { TweetCursorAdapter.this.refresh(); } }; */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.tweet, parent, false); TweetCursorAdapter.ViewHolder holder = new ViewHolder(); holder.tweetUserText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view.findViewById(R.id.profile_image); holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text); holder.fav = (ImageView) view.findViewById(R.id.tweet_fav); holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image); view.setTag(holder); return view; } private static class ViewHolder { public TextView tweetUserText; public TextView tweetText; public ImageView profileImage; public TextView metaText; public ImageView fav; public ImageView has_image; } @Override public void bindView(View view, Context context, Cursor cursor) { TweetCursorAdapter.ViewHolder holder = (TweetCursorAdapter.ViewHolder) view .getTag(); SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);; boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); holder.tweetUserText.setText(cursor.getString(mUserTextColumn)); TextHelper.setSimpleTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) { SimpleImageLoader.display(holder.profileImage, profileImageUrl); } else { holder.profileImage.setVisibility(View.GONE); } if (cursor.getString(mFavorited).equals("true")) { holder.fav.setVisibility(View.VISIBLE); } else { holder.fav.setVisibility(View.GONE); } if (!TextUtils.isEmpty(cursor.getString(mThumbnailPic))) { holder.has_image.setVisibility(View.VISIBLE); } else { holder.has_image.setVisibility(View.GONE); } try { Date createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor .getString(mCreatedAtColumn)); holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder, createdAt, cursor.getString(mSourceColumn), cursor .getString(mInReplyToScreenName))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } } @Override public void refresh() { getCursor().requery(); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * This broadcast receiver is awoken after boot and registers the service that * checks for new tweets. */ public class BootReceiver extends BroadcastReceiver { private static final String TAG = "BootReceiver"; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Twitta BootReceiver is receiving."); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { TwitterService.schedule(context); } } }
Java
package com.ch_linghu.fanfoudroid.service; import java.util.List; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; /** * Location Service * * AndroidManifest.xml <code> * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> * </code> * * TODO: 使用DDMS对模拟器GPS位置进行更新时, 会造成死机现象 * */ public class LocationService implements IService { private static final String TAG = "LocationService"; private LocationManager mLocationManager; private LocationListener mLocationListener = new MyLocationListener(); private String mLocationProvider; private boolean running = false; public LocationService(Context context) { initLocationManager(context); } private void initLocationManager(Context context) { // Acquire a reference to the system Location Manager mLocationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); mLocationProvider = mLocationManager.getBestProvider(new Criteria(), false); } public void startService() { if (!running) { Log.v(TAG, "START LOCATION SERVICE, PROVIDER:" + mLocationProvider); running = true; mLocationManager.requestLocationUpdates(mLocationProvider, 0, 0, mLocationListener); } } public void stopService() { if (running) { Log.v(TAG, "STOP LOCATION SERVICE"); running = false; mLocationManager.removeUpdates(mLocationListener); } } /** * @return the last known location for the provider, or null */ public Location getLastKnownLocation() { return mLocationManager.getLastKnownLocation(mLocationProvider); } private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub Log.v(TAG, "LOCATION CHANGED TO: " + location.toString()); } @Override public void onProviderDisabled(String provider) { Log.v(TAG, "PROVIDER DISABLED " + provider); // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { Log.v(TAG, "PROVIDER ENABLED " + provider); // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub Log.v(TAG, "STATUS CHANGED: " + provider + " " + status); } } // Only for debug public void logAllProviders() { // List all providers: List<String> providers = mLocationManager.getAllProviders(); Log.v(TAG, "LIST ALL PROVIDERS:"); for (String provider : providers) { boolean isEnabled = mLocationManager.isProviderEnabled(provider); Log.v(TAG, "Provider " + provider + ": " + isEnabled); } } // only for debug public static LocationService test(Context context) { LocationService ls = new LocationService(context); ls.startService(); ls.logAllProviders(); Location local = ls.getLastKnownLocation(); if (local != null) { Log.v("LDS", ls.getLastKnownLocation().toString()); } return ls; } }
Java
package com.ch_linghu.fanfoudroid.service; public interface IService { void startService(); void stopService(); }
Java