code
stringlengths
3
1.18M
language
stringclasses
1 value
package net.cardgame.orcalecard; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.utils.ConstantValue; import android.app.Activity; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnPreparedListener; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.model.ImageTagFactory; public class RandomActivity extends Activity implements OnClickListener, AnimationListener { ImageView img_i, img_title; int deckId; DeckBean deckBean; boolean flag = true; SettingApp setting; ImageView img_ring; int state_animation = 0; private ImageManager imageManager; private ImageTagFactory imageTagFactory; MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.random_activity_layout); img_i = (ImageView) findViewById(R.id.imageview); img_title = (ImageView) findViewById(R.id.imageview_title); img_ring = (ImageView) findViewById(R.id.img_ring); Bundle bundle = getIntent().getExtras(); deckId = bundle.getInt("deckId"); deckBean = new DeckBean(); deckBean.deckId = deckId; deckBean.deckName = bundle.getString("deckName"); deckBean.deckPrice = bundle.getInt("deckPrice"); deckBean.pathServerDownload = bundle.getString("deckPathServer"); deckBean.isUnlock = bundle.getBoolean("isUnlock"); setting = ConstantValue.getSettingApp(this); if (deckId == 999) { img_title.setImageResource(R.drawable.c999n); img_i.setImageResource(R.drawable.c999i); img_i.setVisibility(View.VISIBLE); startAnimation(); } else { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; String strTitle = deckBean.pathServerDownload + "/c" + strDeckId + "n.png"; String strDeck = deckBean.pathServerDownload + "/c" + strDeckId + "i.png"; initImageLoader(); setImageTag(img_i, strDeck); loadImage(img_i); setImageTag(img_title, strTitle); loadImage(img_title); img_i.setVisibility(View.VISIBLE); startAnimation(); } } void startAnimation() { if (setting.sound) { // Play Music playMusic(); } Animation deck_animation = AnimationUtils.loadAnimation(this, R.anim.random_deck_animation); deck_animation.setAnimationListener(this); img_i.startAnimation(deck_animation); } private void playMusic() { if (mediaPlayer == null) { mediaPlayer = MediaPlayer.create(this, R.raw.se_draw_card); mediaPlayer.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub mp.start(); } }); mediaPlayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); } mediaPlayer.start(); } @Override public void onClick(View v) { // TODO Auto-generated method stub if (!flag) return; else flag = false; if (deckId == 999 && (setting.listSpecial == null || setting.listSpecial .isEmpty())) { startActivityForResult(new Intent(RandomActivity.this, SettingSpecialActivity.class), 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); RandomActivity.this.finish(); return; } Intent intent = new Intent(RandomActivity.this, CardDeckActivity.class); intent.putExtras(getIntent().getExtras()); startActivityForResult(intent, 0); overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_fade_out); RandomActivity.this.finish(); } @Override public void onAnimationEnd(Animation animation) { // TODO Auto-generated method stub switch (state_animation) { case 0: state_animation = 1; Animation ring_animation = AnimationUtils.loadAnimation(this, R.anim.random_ring); ring_animation.setAnimationListener(this); img_ring.setVisibility(View.VISIBLE); img_ring.startAnimation(ring_animation); // Animation title_animation = AnimationUtils.loadAnimation(this, R.anim.random_title_animation); img_title.setVisibility(View.VISIBLE); img_title.startAnimation(title_animation); break; case 1: findViewById(R.id.img_click).setOnClickListener(this); img_ring.setVisibility(View.INVISIBLE); break; default: break; } } @Override public void onAnimationRepeat(Animation animation) { // TODO Auto-generated method stub } @Override public void onAnimationStart(Animation animation) { // TODO Auto-generated method stub }; private void initImageLoader() { imageManager = MyApplication.getInstance().getImageLoader(); imageTagFactory = createImageTagFactory(); } private ImageTagFactory createImageTagFactory() { ImageTagFactory imageTagFactory = ImageTagFactory.newInstance(); imageTagFactory.setHeight(248); imageTagFactory.setWidth(188); imageTagFactory.setDefaultImageResId(R.drawable.transparent_image); imageTagFactory.setErrorImageId(R.drawable.no_image); imageTagFactory.setSaveThumbnail(true); return imageTagFactory; } private void setImageTag(ImageView view, String url) { view.setTag(imageTagFactory.build(url, this)); } private void loadImage(ImageView view) { imageManager.getLoader().load(view); } @Override public void onBackPressed() { // TODO Auto-generated method stub Intent intent = new Intent(this, TopPageActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); super.onBackPressed(); } }
Java
package net.cardgame.orcalecard.asynctask; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import android.content.Context; import android.os.AsyncTask; public class GetListDeckTask extends AsyncTask<String, Integer, String> { private DownloadListener downloadListener; private NetworkUtils networkUtils; private Context context; public GetListDeckTask(Context context) { this.context = context; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); networkUtils = new NetworkUtils(); } @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub String deckXml = ""; if (NetworkUtils.isNetworkConnected(context)) { deckXml = networkUtils.getStringFromUrl(ConstantValue.BASE_URL + ConstantValue.LIST_DECK_SUB_URL); } return deckXml; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); // if download success call this if (downloadListener != null && result != "") { downloadListener.onDownloadSuccessListener(result); } // if download fail call this if ((downloadListener != null && result == "") || downloadListener != null && result == null) { downloadListener.onDownloadFailListener(result); } } @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); if (downloadListener != null) { downloadListener.onProgressUpdateListener(values[0]); } } /** * @param downloadListener * the downloadListener to set */ public void setDownloadListener(DownloadListener downloadListener) { this.downloadListener = downloadListener; } }
Java
package net.cardgame.orcalecard.asynctask; public interface DownloadListener { public void onDownloadSuccessListener(String result); public void onDownloadFailListener(String result); public void onProgressUpdateListener(Integer update); }
Java
package net.cardgame.orcalecard.asynctask; import java.io.InputStream; import jp.jma.oraclecard.MyApplication; import net.cardgame.orcalecard.utils.FileUtils; import uk.co.senab.bitmapcache.BitmapLruCache; import uk.co.senab.bitmapcache.CacheableBitmapDrawable; import android.content.Context; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; public class DecryptBitmapToCache extends AsyncTask<String, Void, Void> { private final BitmapLruCache mCache; private final BitmapFactory.Options mDecodeOpts; public DecryptBitmapToCache(Context context, BitmapFactory.Options decodeOpts) { mCache = MyApplication.getInstance().getBitmapCache(); mDecodeOpts = decodeOpts; } @Override protected Void doInBackground(String... params) { // TODO Auto-generated method stub for (String sourcePath : params) { // Now we're not on the main thread we can check all caches CacheableBitmapDrawable result = mCache .get(sourcePath, mDecodeOpts); if (null == result) { InputStream is = FileUtils.decrytToInputStream(sourcePath); // Add to cache result = mCache.put(sourcePath, is, mDecodeOpts, true); } else { Log.d("ImageUrlAsyncTask", "Got from Cache: " + sourcePath); } } return null; } }
Java
package net.cardgame.orcalecard; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.NoSuchPaddingException; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.ImageClickable; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.FileUtils; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.webkit.WebView; import android.widget.Button; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.TextView; public class CardDetailActivity extends Activity implements OnClickListener { private Button btnBack, btnHelp; private TextView tv_title; private TextView tv_title_jp; private WebView tv_content1; private WebView tv_content2; private WebView tv_content3; private ImageClickable iv_card; private ImageClickable iv_background; private int cardId = 0; private int deckId = -1; // Chỉ số ID của bộ bài private int indexTypeHelp = 5; private String pathImageSmall = ""; ProgressBar progress; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.card_detail_activity); ScrollView scrollView = (ScrollView) findViewById(R.id.ScrollView01); scrollView.setFadingEdgeLength(0); progress = (ProgressBar) findViewById(R.id.progressBar); tv_title = (TextView) findViewById(R.id.tv_title); tv_title_jp = (TextView) findViewById(R.id.tv_title_jp); // WebView tv_content1 = (WebView) findViewById(R.id.tv_content1); tv_content2 = (WebView) findViewById(R.id.tv_content2); tv_content3 = (WebView) findViewById(R.id.tv_content3); // Set background cho webview tv_content1.setBackgroundColor(0x00000000); tv_content2.setBackgroundColor(0x00000000); tv_content3.setBackgroundColor(0x00000000); // disable copy paste in webview tv_content1.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); tv_content1.setLongClickable(false); tv_content2.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); tv_content2.setLongClickable(false); tv_content3.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); tv_content3.setLongClickable(false); btnBack = (Button) findViewById(R.id.btnBack); btnHelp = (Button) findViewById(R.id.btnHelp); iv_card = (ImageClickable) findViewById(R.id.iv_card); iv_background = (ImageClickable) findViewById(R.id.iv_background); iv_card.setClickable(false); iv_background.setClickable(false); Bundle bundle = this.getIntent().getExtras(); if (bundle.containsKey("deckId")) deckId = bundle.getInt("deckId"); if (bundle.containsKey("cardId")) cardId = bundle.getInt("cardId"); new loadDataBackground().execute(); loadDataImage(); btnBack.setOnClickListener(this); btnHelp.setOnClickListener(this); } void setFontTextView(TextView tv, String patch) { Typeface type = Typeface.createFromAsset(getAssets(), patch); tv.setTypeface(type); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnBack: finish(); break; case R.id.btnHelp: onClickButtonHelp(); break; default: break; } } public void onClickButtonHelp() { Intent i = new Intent(this, net.cardgame.orcalecard.HelpActivity.class); i.putExtra(HelpActivity.KEY_HELP_INDEX, indexTypeHelp); startActivityForResult(i, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } private class loadDataBackground extends AsyncTask<Void, Void, Void> { String content = ""; @Override protected Void doInBackground(Void... params) { content = loadContent(deckId, cardId); return null; } @Override protected void onPostExecute(Void result) { try { content = content.replaceAll("%", "&#37"); String[] subContent = content.split("---"); String header = subContent[0]; String title = header.substring(0, header.indexOf('\n')); String title_jp = header.substring(content.indexOf('\n'), content.indexOf("---")); tv_title.setText(title); tv_title_jp.setText(title_jp); String temp_subContent1 = processContent(subContent[1]); String htmlText1 = "<html><body style=\"text-align:justify\">" + "<font color='#0e3759' font-size='14px' > " + temp_subContent1 + "</font>" + " </body></Html>"; String temp_subContent2 = processContent(subContent[2]); String htmlText2 = "<html><body style=\"text-align:justify\">" + "<font color='#0e3759' font-size='14px' > " + temp_subContent2 + "</font>" + " </body></Html>"; tv_content1.loadDataWithBaseURL(null, String.format(htmlText1, temp_subContent1), "text/html", "utf-8", null); tv_content2.loadDataWithBaseURL(null, String.format(htmlText2, temp_subContent2), "text/html", "utf-8", null); if (subContent.length >= 4) { String temp_subContent3 = processContent(subContent[3]); String htmlText3 = "<html><body style=\"text-align:justify\">" + "<font color='#0e3759' font-size='14px' > " + temp_subContent3 + "</font>" + " </body></html>"; tv_content3.loadDataWithBaseURL(null, String.format(htmlText3, temp_subContent3), "text/html", "utf-8", null); } } catch (Exception e) { Utils.ELog("Substring errors", e == null ? "Errors occur when substring text of Card" : e.toString()); } super.onPostExecute(result); } } // Thực hiện việc xử lý xâu kết quả private String processContent(String src) { String des = ""; for (int i = 0; i < src.length() - 2; i++) { if ((src.charAt(i) == '○') && (src.charAt(i + 1) == ' ')) { des += src.charAt(i) + ""; i += 2; } else if ((src.charAt(i) == '・') && (src.charAt(i + 1) == ' ')) { des += src.charAt(i) + ""; i += 2; } else if ((src.charAt(i) == '→') && (src.charAt(i + 1) == ' ')) { des += src.charAt(i) + ""; i += 2; } if (src.charAt(i) == '\n') { des += "<br>"; } else des += src.charAt(i) + ""; } return des; } public void loadDataImage() { String strDECKID = (deckId < 10) ? ("0" + deckId) : ("" + deckId); String strCARDID = (cardId < 10) ? ("0" + cardId) : ("" + cardId); String pathImageCard = ConstantValue.getPatchCardData(this) + "Card_" + strDECKID + "/en_c" + strDECKID + strCARDID + ".png"; String pathImageBackground = ConstantValue.getPatchCardData(this) + "Card_" + strDECKID + "/en_bg" + strDECKID + ".jpg"; iv_background.setPath(pathImageBackground); iv_card.setPath(pathImageCard); iv_background.loadImage(pathImageBackground); iv_card.loadImage(pathImageCard); // new ThreadLoadImage(this, handlerLoadImage, pathImageBackground, // iv_background, 1).start(); // new ThreadLoadImage(this, handlerLoadImage, pathImageCard, null, 2) // .start(); } // Handler handlerLoadImage = new Handler() { // public void handleMessage(android.os.Message msg) { // switch (msg.what) { // case 1: // if (msg.obj == null) { // iv_background.setImageResource(R.drawable.image_not_found); // return; // } // Drawable result1 = ((Drawable) msg.obj); // Bitmap bitmap1 = ((BitmapDrawable) result1).getBitmap(); // if (!bitmap1.isRecycled()) // iv_background.setImageBitmap(bitmap1); // break; // case 2: // if (msg.obj == null) { // iv_card.setImageResource(R.drawable.image_not_found); // return; // } // Drawable result = ((Drawable) msg.obj); // Bitmap bitmap = ((BitmapDrawable) result).getBitmap(); // if (!bitmap.isRecycled()) // iv_card.setImageBitmap(bitmap); // progress.setVisibility(View.INVISIBLE); // iv_card.setBackgroundResource(R.drawable.shadow_card_detail); // break; // default: // break; // } // }; // }; // Tra ve noi dung content ung voi cardId @SuppressWarnings("static-access") public String loadContent(int _deckId, int _cardId) { FileUtils fUtils = new FileUtils(); String strDECKID = ""; String strCARDID = ""; String pathTextFile = ""; String _content = ""; byte[] bytes; InputStream is = null; BufferedReader bfReader = null; if (_deckId < 10) strDECKID = "0" + _deckId; else strDECKID = "" + _deckId; if (_cardId < 10) strCARDID = "0" + _cardId; else strCARDID = "" + _cardId; pathTextFile = ConstantValue.getPatchCardData(this) + "Card_" + strDECKID + "/en_t" + strDECKID + strCARDID + ".txt"; try { bytes = fUtils.decryptToByteArray(pathTextFile, ""); _content = new String(bytes, "UTF-8"); // Va ma hoa ve utf-8 // is = new ByteArrayInputStream(bytes); // bfReader = new BufferedReader(new InputStreamReader(is)); // String str = ""; // while ((str = bfReader.readLine()) != null) { // _content += str; // } } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return _content; } // private void writeToFile(String data) { // try { // File file = new File(Environment.getExternalStorageDirectory() // + "/test.txt"); // if (!file.exists()) { // file.createNewFile(); // } // BufferedWriter buf = new BufferedWriter(new FileWriter(file, true)); // buf.append(data); // buf.newLine(); // buf.close(); // } catch (IOException e) { // // TODO: handle exception // } // } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } }
Java
package net.cardgame.orcalecard; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import jp.jma.oraclecard.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; @SuppressWarnings({ "unchecked", "rawtypes" }) public class AdapterInfoApp extends ArrayAdapter { private Context context; private ArrayList<HashMap<String, String>> list; private int idIconNew = R.drawable.new_release; public AdapterInfoApp(Context context, ArrayList<HashMap<String, String>> list) { super(context, R.layout.item_listview_infoapp, list); this.context = context; this.list = list; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.item_listview_infoapp, parent, false); TextView tvTitle = (TextView) rowView.findViewById(R.id.tv_title); TextView tvSummary = (TextView) rowView.findViewById(R.id.tv_summary); TextView tvPosted = (TextView) rowView.findViewById(R.id.tv_posted); ImageView ivIconNew = (ImageView) rowView.findViewById(R.id.iv_newicon); String summary = " " + list.get(position).get("summary"); String posted = list.get(position).get("posted"); String title = ""; if (checkNew(posted)) { ivIconNew.setImageResource(idIconNew); title = " " + list.get(position).get("title"); } else { title = " " + list.get(position).get("title"); } posted = analysePost(posted); tvTitle.setText(title); tvSummary.setText(summary); tvPosted.setText(posted); return rowView; } // Phan tich string "posted" thanh dang year month day (thu) hour:minute public String analysePost(String posted) { String result = ""; String strYear = ""; String strMonth = ""; String strDay = ""; String strHour = ""; String strMinute = ""; strYear = posted.substring(0, 4); strMonth = posted.substring(4, 6); strDay = posted.substring(6, 8); strHour = posted.substring(8, 10); strMinute = posted.substring(10, 12); int year = Integer.parseInt(strYear); int month = Integer.parseInt(strMonth); int day = Integer.parseInt(strDay); String thu = ""; int index = DetectThu(year, month, day); switch (index) { case 0: thu = "(SAT)"; break; case 1: thu = "(SUN)"; break; case 2: thu = "(MON)"; break; case 3: thu = "(TUE)"; break; case 4: thu = "(WED)"; break; case 5: thu = "(THU)"; break; case 6: thu = "(FRI)"; break; default: break; } result = strYear + "年" + strMonth + "月" + strDay + "日 " + thu + " " + strHour + ":" + strMinute; return result; } // Nhung tin nao < 30 ngay la tin moi ==> return true; // Nguoc lai ==> return false; public boolean checkNew(String posted) { boolean isNew = false; String strYear = ""; String strMonth = ""; String strDay = ""; strYear = posted.substring(0, 4); strMonth = posted.substring(4, 6); strDay = posted.substring(6, 8); int posYear = Integer.parseInt(strYear); int posMonth = Integer.parseInt(strMonth); int posDay = Integer.parseInt(strDay); Calendar current = Calendar.getInstance(); int curYear = current.get(Calendar.YEAR); int curMonth = current.get(Calendar.MONTH) + 1; int curDay = current.get(Calendar.DATE); Calendar posCal = new GregorianCalendar(); Calendar curCal = new GregorianCalendar(); posCal.set(posYear, posMonth, posDay); curCal.set(curYear, curMonth, curDay); int betweenDate = daysBetween(posCal.getTime(), curCal.getTime()); if (betweenDate > 30) isNew = false; else isNew = true; return isNew; } public int daysBetween(Date d1, Date d2) { return (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24)); } // Tim thu may khi biet ngay, thang, nam public int DetectThu(int year, int month, int day) { final int a[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int soNgay = ((year - 1) % 7) * 365 + (year - 1) / 4; if (year % 4 == 0) a[1] = 29; for (int i = 0; i < (month - 1); i++) soNgay += a[i]; soNgay += day; int thu = soNgay % 7; return thu; } }
Java
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.ImageClickable; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.bean.HistoryBean; import net.cardgame.orcalecard.bean.NewsBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.KeyboardHelper; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.model.ImageTagFactory; public class SaveHistoryActivity extends Activity implements OnClickListener { ImageClickable card1, card2, card3, card4; ImageView img_bg, img_deck, btnSave, btnShareFacebook; EditText txtQuestion, txtMemory; TextView txtDateTime, txtTitle; int number_of_card, card1Id, card2Id, card3Id, card4Id, deckId; String question; ArrayList<CardBean> listCardBean; Date datetime; String strDatetime; CardBean cardBean1; CardBean cardBean2; CardBean cardBean3; CardBean cardBean4; boolean saved = false; boolean flag = true; ImageView frame2, frame3, frame4; private ImageManager imageManager; private ImageTagFactory imageTagFactory; private SecurePreferences contentPreferences; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.save_sharefacebook_activity); contentPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); initImageLoader(); setupUI(findViewById(R.id.parent)); ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView1); scrollView.setFadingEdgeLength(0); findViewById(R.id.btn_back_save).setOnClickListener(this); findViewById(R.id.btn_help_save).setOnClickListener(this); frame2 = (ImageView) findViewById(R.id.img_frame_card2); frame3 = (ImageView) findViewById(R.id.img_frame_card3); frame4 = (ImageView) findViewById(R.id.img_frame_card4); btnSave = (ImageView) findViewById(R.id.btn_save); btnShareFacebook = (ImageView) findViewById(R.id.btn_sharefacebook); btnShareFacebook.setOnClickListener(this); btnSave.setOnClickListener(this); txtTitle = (TextView) findViewById(R.id.txttitle_deck_save); card1 = (ImageClickable) findViewById(R.id.img_card1_save); card2 = (ImageClickable) findViewById(R.id.img_card2_save); card3 = (ImageClickable) findViewById(R.id.img_card3_save); card4 = (ImageClickable) findViewById(R.id.img_card4_save); img_bg = (ImageView) findViewById(R.id.img_bg_save); img_deck = (ImageView) findViewById(R.id.img_deck_save); txtQuestion = (EditText) findViewById(R.id.txtquestion_save); txtMemory = (EditText) findViewById(R.id.txtmemory_save); txtDateTime = (TextView) findViewById(R.id.txt_datetime_save); getExtra(); loadImage(); } void getExtra() { Intent intent = getIntent(); Bundle bundle = intent.getExtras(); deckId = bundle.getInt("deckId"); number_of_card = bundle.getInt("number_of_card"); question = bundle.getString("question"); cardBean1 = bundle.getParcelable("cardBean1"); cardBean2 = bundle.getParcelable("cardBean2"); cardBean3 = bundle.getParcelable("cardBean3"); cardBean4 = bundle.getParcelable("cardBean4"); listCardBean = new ArrayList<CardBean>(); listCardBean.add(cardBean1); listCardBean.add(cardBean2); listCardBean.add(cardBean3); listCardBean.add(cardBean4); } private Handler handlerLoadImage = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: card1.setImageDrawable((Drawable) msg.obj); card1.setOnClickListener(SaveHistoryActivity.this); break; case 2: card2.setImageDrawable((Drawable) msg.obj); card2.setOnClickListener(SaveHistoryActivity.this); frame2.setVisibility(View.INVISIBLE); break; case 3: card3.setImageDrawable((Drawable) msg.obj); card3.setOnClickListener(SaveHistoryActivity.this); frame3.setVisibility(View.INVISIBLE); break; case 4: card4.setImageDrawable((Drawable) msg.obj); card4.setOnClickListener(SaveHistoryActivity.this); frame4.setVisibility(View.INVISIBLE); break; case 5: img_bg.setImageDrawable((Drawable) msg.obj); break; default: break; } }; }; void loadImage() { ImageView img_number_card = (ImageView) findViewById(R.id.img_number_of_card_save); // Set text question if (question != null) txtQuestion.setText(question); displayDateTime(); // load DeckTitle if (deckId == 999) { txtTitle.setText(R.string.title_special); img_bg.setImageResource(R.drawable.bg999); img_deck.setImageResource(R.drawable.c999i); } else { String key = "content_" + deckId; String deckName; if (contentPreferences.containsKey(key)) { deckName = contentPreferences.getString(key); String[] arr = deckName.split("---"); deckName = arr[0]; if (deckName.contains("←")) deckName = deckName.substring(0, deckName.indexOf("←")); txtTitle.setText(deckName); } // Load BackGround image new ThreadLoadImage(this, handlerLoadImage, ConstantValue.getPatchCardData(this) + "Card_" + convertIdToStringId(deckId) + "/en_bg" + convertIdToStringId(deckId) + ".jpg", img_bg, 5) .start(); String pathImageDeck = ConstantValue.BASE_URL + "Card_" + convertIdToStringId(deckId) + "/c" + convertIdToStringId(deckId) + "i.png"; setImageTag(img_deck, pathImageDeck); loadImage(img_deck); } // load card1 loadCard1(); // Load card 2,3,4 switch (number_of_card) { case 3: loadCard2(); loadCard3(); img_number_card.setImageResource(R.drawable.result_draw3); break; case 4: loadCard2(); loadCard3(); loadCard4(); img_number_card.setImageResource(R.drawable.result_draw4); break; default: break; } // Load Jump Card findViewById(R.id.img_jump_card1_save).setVisibility( listCardBean.get(0).isJump ? View.VISIBLE : View.INVISIBLE); findViewById(R.id.img_jump_card2_save).setVisibility( listCardBean.get(1).isJump ? View.VISIBLE : View.INVISIBLE); findViewById(R.id.img_jump_card3_save).setVisibility( listCardBean.get(2).isJump ? View.VISIBLE : View.INVISIBLE); findViewById(R.id.img_jump_card4_save).setVisibility( listCardBean.get(3).isJump ? View.VISIBLE : View.INVISIBLE); } // Load card1 void loadCard1() { String path = getCardPatchByCardId(listCardBean.get(0)); card1.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card1, 1).start(); } void loadCard2() { String path = getCardPatchByCardId(listCardBean.get(1)); card2.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card2, 2).start(); card2.setVisibility(View.VISIBLE); } void loadCard3() { String path = getCardPatchByCardId(listCardBean.get(2)); card3.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card3, 3).start(); card3.setVisibility(View.VISIBLE); } void loadCard4() { String path = getCardPatchByCardId(listCardBean.get(3)); card4.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card4, 4).start(); card4.setVisibility(View.VISIBLE); } /** * display get card datetime */ void displayDateTime() { Calendar c = Calendar.getInstance(); datetime = c.getTime(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); int hh = c.get(Calendar.HOUR_OF_DAY); int mm = c.get(Calendar.MINUTE); String dayWeek = ""; switch (dayOfWeek) { case 2: dayWeek = "Mon"; break; case 3: dayWeek = "Tue"; break; case 4: dayWeek = "Wed"; break; case 5: dayWeek = "Thu"; break; case 6: dayWeek = "Fri"; break; case 7: dayWeek = "Sat"; break; case 8: dayWeek = "Sun"; break; default: break; } strDatetime = year + "年" + convertIdToStringId(month) + "月" + convertIdToStringId(day) + "日(" + dayWeek + ") " + convertIdToStringId(hh) + ":" + convertIdToStringId(mm); txtDateTime.setText(strDatetime); } String convertIdToStringId(int id) { return id < 10 ? "0" + id : "" + id; } /** * Get patch image file * * @param id * cardId * @return patch to image */ String getCardPatchByCardId(int id) { return ConstantValue.getPatchCardData(this) + "Card_" + convertIdToStringId(deckId) + "/X3/en_c" + convertIdToStringId(deckId) + convertIdToStringId(id) + ".png"; } String getCardPatchByCardId(CardBean cardBean) { return ConstantValue.getPatchCardData(this) + "Card_" + convertIdToStringId(cardBean.deckId) + "/X3/en_c" + convertIdToStringId(cardBean.deckId) + convertIdToStringId(cardBean.cardId) + ".png"; } @Override public void onClick(View v) { // TODO Auto-generated method stub if (!flag) return; else flag = false; switch (v.getId()) { case R.id.btn_back_save: this.finish(); break; case R.id.btn_help_save: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 10); startActivityForResult(intent, ConstantValue.SAVE_HISTORY_ACTIVITY); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_save: if (!saved) { saved = true; btnSave.setSelected(true); saveHistory(); } flag = true; break; case R.id.btn_sharefacebook: gotoPostFacebook(); break; case R.id.img_card1_save: gotoCardDetail(listCardBean.get(0)); break; case R.id.img_card2_save: gotoCardDetail(listCardBean.get(1)); break; case R.id.img_card3_save: gotoCardDetail(listCardBean.get(2)); break; case R.id.img_card4_save: gotoCardDetail(listCardBean.get(3)); break; default: break; } } void gotoPostFacebook() { Intent intent = new Intent(this, PostFacebookActivity.class); intent.putExtra("number_of_card", number_of_card); intent.putExtra("deckId", deckId); intent.putExtra("cardBean1", cardBean1); intent.putExtra("cardBean2", cardBean2); intent.putExtra("cardBean3", cardBean3); intent.putExtra("cardBean4", cardBean4); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } void gotoCardDetail(CardBean cardBean) { Intent intent = new Intent(this, CardDetailActivity.class); intent.putExtra("deckId", cardBean.deckId); intent.putExtra("cardId", cardBean.cardId); startActivityForResult(intent, ConstantValue.SAVE_HISTORY_ACTIVITY); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } /** * save history get card to shared reference */ void saveHistory() { List<HistoryBean> listHistory = null; Gson gson = new Gson(); Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() { }.getType(); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.HISTORY_KEY)) { String strHistory = appPreferences .getString(ConstantValue.HISTORY_KEY); listHistory = gson.fromJson(strHistory, listOfHistoryBean); } if (listHistory == null) { listHistory = new ArrayList<HistoryBean>(); } int size = listHistory.isEmpty() ? 0 : listHistory.size(); HistoryBean history = new HistoryBean(); if (size == 0) history.id = 1; else { history.id = listHistory.get(size - 1).id + 1; if (size == 100) { String sumary = "保存件数が 100件に達しているため、今回の結果は保存できません。\n" + " 次回以降新しく保存したい場合は保存したデータを削除して空きスペースを作って\n ください"; showDialog(null, sumary, true); } } history.deckbeanId = deckId; history.question = txtQuestion.getText().toString(); String memo = txtMemory.getText().toString(); if (!memo.matches("")) { ArrayList<NewsBean> listNews = new ArrayList<NewsBean>(); NewsBean newsBean = new NewsBean(); newsBean.id = 1; newsBean.datetime = strDatetime; newsBean.time = datetime; newsBean.sumary = memo; listNews.add(newsBean); history.newsBeans = listNews; } history.datetime = datetime; history.strDateTime = strDatetime; history.deckTitle = txtTitle.getText().toString(); history.cardBeans = getListCardBean(); listHistory.add(history); String save = gson.toJson(listHistory, listOfHistoryBean); appPreferences.put(ConstantValue.HISTORY_KEY, save); size++; if (size == 100) { String title = "保存件数が 100件に達しました。これ以上保存できません。\n新しく保存したい場合は保存したデータを削除して空きスペースを作ってくださ い"; String sumary = "100件保存状態の場合「保存」したら\n" + "「保存件数が 100件に達しているため、今回の結果は保存できません。\n" + "次回以降新しく保存したい場合は保存したデータを削除して空きスペース\n" + "を作ってください」\n" + "と表示し、保存しない。"; showDialog(title, sumary, true); } else if (size > 90) { int add = 100 - size; String title = "保存可能件数は残り" + add + "件です"; showDialog(title, null, false); } else { String title = "本体に保 存しました"; showDialog(title, null, false); } } /** * Show dialog when save history * * @param title * Title of dialog * @param sumary * message of dialog * @param fullHistory * true if history record =100 */ void showDialog(String title, String sumary, boolean fullHistory) { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage(sumary); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); flag = true; } }); AlertDialog dialog = builder.show(); // Create custom message TextView messageText = (TextView) dialog .findViewById(android.R.id.message); if (messageText != null) messageText.setGravity(Gravity.CENTER); } /** * @return list card bean to save history */ private ArrayList<CardBean> getListCardBean() { switch (number_of_card) { case 1: CardBean cardBean = listCardBean.get(0); listCardBean = new ArrayList<CardBean>(); listCardBean.add(cardBean); break; case 3: listCardBean.remove(3); break; default: break; } return listCardBean; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); flag = true; } public void setupUI(View view) { // Set up touch listener for non-text box views to hide keyboard. if (!(view instanceof EditText)) { view.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { v.requestFocus(); KeyboardHelper.hideSoftKeyboard(SaveHistoryActivity.this); return false; } }); } // If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView); } } } private void initImageLoader() { imageManager = MyApplication.getInstance().getImageLoader(); imageTagFactory = createImageTagFactory(); } private ImageTagFactory createImageTagFactory() { ImageTagFactory imageTagFactory = ImageTagFactory.newInstance(); imageTagFactory.setHeight(248); imageTagFactory.setWidth(188); imageTagFactory.setDefaultImageResId(R.drawable.cardi_tranparent); imageTagFactory.setErrorImageId(R.drawable.cardi_tranparent); imageTagFactory.setSaveThumbnail(true); return imageTagFactory; } private void setImageTag(ImageView view, String url) { view.setTag(imageTagFactory.build(url, this)); } private void loadImage(ImageView view) { imageManager.getLoader().load(view); } @Override public void onBackPressed() { // TODO Auto-generated method stub overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); super.onBackPressed(); } }
Java
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.Helper; import net.cardgame.oraclecard.common.ImageClickable; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.oraclecard.common.onDeleteNewsBeanListener; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.bean.HistoryBean; import net.cardgame.orcalecard.bean.NewsBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.Utils; import uk.co.senab.bitmapcache.BitmapLruCache; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.model.ImageTagFactory; public class EditHistoryActivity extends Activity implements OnClickListener, onDeleteNewsBeanListener { ArrayList<HistoryBean> listHistory = new ArrayList<HistoryBean>(); HistoryBean history; ArrayList<NewsBean> listNews = new ArrayList<NewsBean>(); ImageView btnSave, img_deck; NewsBeanAdapter adapter; TextView txtMemory; ListView listView; int index; private ImageManager imageManager; private ImageTagFactory imageTagFactory; ImageClickable card1, card2, card3, card4; final static String X1 = ""; final static String X2 = "X2"; final static String X3 = "X3"; private BitmapLruCache cache; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); cache = MyApplication.getInstance().getBitmapCache(); setContentView(R.layout.edit_history_activity); initView(); getHistory(); loadHistoryInfo(); } void initView() { findViewById(R.id.btnhelp_edit_history).setOnClickListener(this); findViewById(R.id.btnBack_edit_history).setOnClickListener(this); findViewById(R.id.btnSave_comment).setOnClickListener(this); txtMemory = (TextView) findViewById(R.id.txtmemory_edit_history); card1 = (ImageClickable) findViewById(R.id.img_card1_save); card2 = (ImageClickable) findViewById(R.id.img_card2_save); card3 = (ImageClickable) findViewById(R.id.img_card3_save); card4 = (ImageClickable) findViewById(R.id.img_card4_save); img_deck = (ImageView) findViewById(R.id.img_deck_save); } void getHistory() { Gson gson = new Gson(); Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() { }.getType(); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.HISTORY_KEY)) { String strHistory = appPreferences .getString(ConstantValue.HISTORY_KEY); listHistory = gson.fromJson(strHistory, listOfHistoryBean); } Bundle bundle = getIntent().getExtras(); int historyId = bundle.getInt("historyId"); int size = listHistory.size(); for (int i = 0; i < size; i++) { if (listHistory.get(i).id == historyId) { index = i; history = listHistory.get(i); listNews = history.newsBeans; break; } } } void loadHistoryInfo() { ImageView img_number_card = (ImageView) findViewById(R.id.img_number_of_card_save); TextView txtQuestion = (TextView) findViewById(R.id.txtquestion_edithistory); if (history.question != null && history.question != "") txtQuestion.setText(history.question); TextView txtTitle = (TextView) findViewById(R.id.txttitle_edit_history); txtTitle.setText(history.strDateTime + " の結果"); TextView txtDeckTitle = (TextView) findViewById(R.id.txttitle_deck_save); txtDeckTitle.setText(history.deckTitle); if (history.deckbeanId != 999) { String tt = convertIdToStringId(history.deckbeanId); String patch_img_deck = ConstantValue.BASE_URL + "Card_" + tt + "/c" + tt + "i.png"; initImageLoader(); setImageTag(img_deck, patch_img_deck); loadImage(img_deck); } else { img_deck.setImageResource(R.drawable.c999i); } String path = getCardPatchByCardId(history.cardBeans.get(0)); card1.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card1, 1).start(); if (history.cardBeans.get(0).isJump) findViewById(R.id.img_jump_card1_save).setVisibility(View.VISIBLE); switch (history.cardBeans.size()) { case 3: path = getCardPatchByCardId(history.cardBeans.get(1)); card2.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card2, 2).start(); path = getCardPatchByCardId(history.cardBeans.get(2)); card3.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card3, 3).start(); card2.setVisibility(View.VISIBLE); card3.setVisibility(View.VISIBLE); img_number_card.setImageResource(R.drawable.result_draw3); if (history.cardBeans.get(1).isJump) findViewById(R.id.img_jump_card2_save).setVisibility( View.VISIBLE); if (history.cardBeans.get(2).isJump) findViewById(R.id.img_jump_card3_save).setVisibility( View.VISIBLE); break; case 4: path = getCardPatchByCardId(history.cardBeans.get(1)); card2.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card2, 2).start(); path = getCardPatchByCardId(history.cardBeans.get(2)); card3.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card3, 3).start(); path = getCardPatchByCardId(history.cardBeans.get(3)); card4.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, card4, 4).start(); card2.setVisibility(View.VISIBLE); card3.setVisibility(View.VISIBLE); card4.setVisibility(View.VISIBLE); img_number_card.setImageResource(R.drawable.result_draw4); if (history.cardBeans.get(1).isJump) findViewById(R.id.img_jump_card2_save).setVisibility( View.VISIBLE); if (history.cardBeans.get(2).isJump) findViewById(R.id.img_jump_card3_save).setVisibility( View.VISIBLE); if (history.cardBeans.get(3).isJump) findViewById(R.id.img_jump_card4_save).setVisibility( View.VISIBLE); break; default: break; } listView = (ListView) findViewById(R.id.listView_edit_history); if (history.newsBeans != null) { adapter = new NewsBeanAdapter(this, history.newsBeans); listView.setAdapter(adapter); Helper.getListViewSize(listView); } } Handler handlerLoadImage = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 1: card1.setImageDrawable((Drawable) msg.obj); card1.setOnClickListener(EditHistoryActivity.this); break; case 2: card2.setImageDrawable((Drawable) msg.obj); card2.setOnClickListener(EditHistoryActivity.this); break; case 3: card3.setImageDrawable((Drawable) msg.obj); card3.setOnClickListener(EditHistoryActivity.this); break; case 4: card4.setImageDrawable((Drawable) msg.obj); card4.setOnClickListener(EditHistoryActivity.this); break; default: break; } }; }; String convertIdToStringId(int id) { return id < 10 ? "0" + id : "" + id; } /** * Get patch image file * * @param cardBean * * @return patch to image */ String getCardPatchByCardId(CardBean cardBean) { return ConstantValue.getPatchCardData(this) + "Card_" + convertIdToStringId(cardBean.deckId) + "/X3/en_c" + convertIdToStringId(cardBean.deckId) + convertIdToStringId(cardBean.cardId) + ".png"; } void showDialog(String title) { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); // builder.setMessage("Check your email and verify your username and password..."); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); AlertDialog dialog = builder.show(); // Create custom message // TextView messageText = (TextView) dialog // .findViewById(android.R.id.message); // messageText.setGravity(Gravity.CENTER); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btnhelp_edit_history: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 1); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btnBack_edit_history: saveHistory(); this.finish(); break; case R.id.btnSave_comment: if (!txtMemory.getText().toString().matches("")) { showDialog("本体に保存しました"); NewsBean newsBean = getNewsBean(); if (adapter == null) { listNews = new ArrayList<NewsBean>(); newsBean.id = 1; listNews.add(newsBean); adapter = new NewsBeanAdapter(this, listNews); listView.setAdapter(adapter); } else { newsBean.id = listNews.size() + 1; adapter.addNewsBean(newsBean); } Helper.getListViewSize(listView); // for (NewsBean newss : listNews) { // Utils.DLog("list News bean", newss.toString()); // } } break; case R.id.img_card1_save: gotoCardDetail(history.cardBeans.get(0)); break; case R.id.img_card2_save: gotoCardDetail(history.cardBeans.get(1)); break; case R.id.img_card3_save: gotoCardDetail(history.cardBeans.get(2)); break; case R.id.img_card4_save: gotoCardDetail(history.cardBeans.get(3)); break; default: break; } } NewsBean getNewsBean() { Calendar c = Calendar.getInstance(); Date now = c.getTime(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); int hh = c.get(Calendar.HOUR_OF_DAY); int mm = c.get(Calendar.MINUTE); String dayWeek = ""; switch (dayOfWeek) { case 2: dayWeek = "Mon"; break; case 3: dayWeek = "Tue"; break; case 4: dayWeek = "Wed"; break; case 5: dayWeek = "Thu"; break; case 6: dayWeek = "Fri"; break; case 7: dayWeek = "Sat"; break; case 8: dayWeek = "Sun"; break; default: break; } String strDatetime = year + "年" + convertIdToStringId(month) + "月" + convertIdToStringId(day) + "日(" + dayWeek + ") " + convertIdToStringId(hh) + ":" + convertIdToStringId(mm); NewsBean newsBean = new NewsBean(); newsBean.sumary = txtMemory.getText().toString(); newsBean.datetime = strDatetime; newsBean.time = now; return newsBean; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } void saveHistory() { history.newsBeans = listNews; listHistory.set(index, history); Gson gson = new Gson(); Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() { }.getType(); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); String save = gson.toJson(listHistory, listOfHistoryBean); appPreferences.put(ConstantValue.HISTORY_KEY, save); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { saveHistory(); this.finish(); } return super.onKeyDown(keyCode, event); } @Override public void onDeleted(NewsBean newsBean) { // TODO Auto-generated method stub listNews.remove(newsBean); Helper.getListViewSize(listView); } void gotoCardDetail(CardBean cardBean) { Intent intent = new Intent(this, CardDetailActivity.class); intent.putExtra("deckId", cardBean.deckId); intent.putExtra("cardId", cardBean.cardId); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } String getCardPatchByCardId(CardBean cardBean, String typeImage) { if (typeImage == X1) typeImage = ""; else typeImage = "/" + typeImage + "/"; String result = ConstantValue.getPatchCardData(this) + "Card_" + convertIdToStringId(cardBean.deckId) + typeImage + "en_c" + convertIdToStringId(cardBean.deckId) + convertIdToStringId(cardBean.cardId) + ".png"; return result; } private void ClearCache() { List<CardBean> list = history.cardBeans; for (CardBean card : list) { cache.removeFromMemory(getCardPatchByCardId(card, X1)); cache.removeFromMemory(getCardPatchByCardId(card, X3)); } } @Override protected void onDestroy() { // TODO Auto-generated method stub ClearCache(); super.onDestroy(); } private void initImageLoader() { imageManager = MyApplication.getInstance().getImageLoader(); imageTagFactory = createImageTagFactory(); } private ImageTagFactory createImageTagFactory() { ImageTagFactory imageTagFactory = ImageTagFactory.newInstance(); imageTagFactory.setHeight(248); imageTagFactory.setWidth(188); imageTagFactory.setDefaultImageResId(R.drawable.cardi_tranparent); imageTagFactory.setErrorImageId(R.drawable.cardi_tranparent); imageTagFactory.setSaveThumbnail(true); return imageTagFactory; } private void setImageTag(ImageView view, String url) { view.setTag(imageTagFactory.build(url, this)); } private void loadImage(ImageView view) { imageManager.getLoader().load(view); } }
Java
package net.cardgame.orcalecard.bean; import android.os.Parcel; import android.os.Parcelable; /** * Lớp dữ liệu thể hiện từng quân bài * */ public class CardBean implements Parcelable { // id của là bài public int cardId; // id của bộ bài chứa lá bài public int deckId; // vị trí của lá bài trong bộ bài public int cardPosition; // tên lá bài public String cardName; // thể hiện lá bài bị rơi public boolean isJump = false; // đường dẫn thể hiện ảnh lá bài public String pathImage; // tiêu đề lá bài public String textTitle; // Nội dung của lá bài public String textDetail; public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public CardBean createFromParcel(Parcel in) { return new CardBean(in); } @Override public CardBean[] newArray(int size) { // TODO Auto-generated method stub return new CardBean[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub dest.writeInt(cardId); dest.writeInt(deckId); dest.writeInt(isJump ? 1 : 0); } @Override public String toString() { return "CardBean [cardId=" + cardId + ", deckId=" + deckId + ", isJump=" + isJump + "]"; } public CardBean(Parcel source) { this.cardId = source.readInt(); this.deckId = source.readInt(); this.isJump = source.readInt() == 1 ? true : false; } public CardBean() { // TODO Auto-generated constructor stub } public CardBean(int deckId, String cardName, String pathImage, String textTitle, String textDetail) { this.deckId = deckId; this.cardName = cardName; this.pathImage = pathImage; this.textTitle = textTitle; this.textDetail = textDetail; } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } }
Java
package net.cardgame.orcalecard.bean; import java.util.Date; /** * Lớp dữ liệu thể hiện bộ bài * */ public class DeckBean { // ID của bộ bài public int deckId; @Override public String toString() { return "DeckBean [\ndeckId=" + deckId + ", \ndeckName=" + deckName + ", \nisFree=" + isFree + ", \nisUnlock=" + isUnlock + ", \ndeckPrice=" + deckPrice + ", \ncardNumber=" + cardNumber + ", \nreleaseDate=" + releaseDate + ", \ninAppPurchaseId=" + inAppPurchaseId + ", \npathServerDownload=" + pathServerDownload + ", \npercentDownloaded=" + percentDownloaded + ", \nbuyDate=" + buyDate + ", \nlastUsedDate=" + lastUsedDate + "\n]"; } // Tên bộ bài public String deckName; // Bộ bài có thu phí hay không public boolean isFree; // Bộ bài đã được mua hay chưa public boolean isUnlock; // Giá của bộ bài public int deckPrice; // Số lương quân bài public int cardNumber; // ngày xuất hiện bộ bài public Date releaseDate; // ID dùng trong việc xử lý In App Billing public String inAppPurchaseId; // �ư�ng dẫn đến file ảnh thể hiện tên bộ bài public String pathImageTitle; // �ư�ng dẫn đến file ảnh thể hiện n�n bộ bài public String pathImageBackground; // �ư�ng dẫn đến file text thể hiện thông tin bộ bài public String pathTextDetail; // �ư�ng link để download data bộ bài public String pathServerDownload; // public int percentDownloaded = -1; // public Date buyDate; // public Date lastUsedDate; public DeckBean() { Date defaultDate = new Date(2000, 1, 1); this.buyDate = defaultDate; this.releaseDate = defaultDate; this.lastUsedDate = defaultDate; } }
Java
package net.cardgame.orcalecard.bean; import java.util.ArrayList; import java.util.Date; /** * Lớp thể hiện lịch sử rút bài * */ public class HistoryBean { public int id; // Deckbean Id public int deckbeanId; // question of this history public String question; // Deck Bean title public String deckTitle; // comment list of this history public ArrayList<NewsBean> newsBeans; // card list of this history public ArrayList<CardBean> cardBeans; // datetime of history public Date datetime; // String datetime public String strDateTime; }
Java
package net.cardgame.orcalecard.bean; import java.util.ArrayList; import java.util.List; public class SettingApp { public final static int SORT_BY_RELEASE = 1; public final static int SORT_BY_BUY = 2; public final static int SORT_BY_USED = 3; // setting co jumpcard trong khi rut hay khong(true: co jumpcard) public boolean jumCard; // setting adviseCard co them cay thu 4 trong truong hop rut 3 cay public boolean adviseCard; // Bat hieu ung am thanh doi voi app public boolean sound; // chuc nang sort cac bo bai trong man hinh top page( 1:release, 2: theo thu // tu mua, 3: theo thu tu su dung gan nhat) public int sortToppage; /** * */ public SettingApp() { } // setting special deck cho tung bo bai (mang int[] chua id cac bo bai) public List<Integer> listSpecial; // setting chuc nang restore cho app public boolean restore; /** * @param jumCard * @param adviseCard * @param sound * @param sortToppage * @param listSpecial * @param restore */ public SettingApp(boolean jumCard, boolean adviseCard, boolean sound, int sortToppage, ArrayList<Integer> listSpecial, boolean restore) { super(); this.jumCard = jumCard; this.adviseCard = adviseCard; this.sound = sound; this.sortToppage = sortToppage; this.listSpecial = listSpecial; this.restore = restore; } /** * Load default setting for app */ public void setDefault() { this.jumCard = false; this.adviseCard = false; this.sound = true; this.restore = false; this.listSpecial = new ArrayList<Integer>(); this.sortToppage = 1; } }
Java
package net.cardgame.orcalecard.bean; import java.util.Date; /** * Lớp thể hiện tin tức mới * */ public class NewsBean { @Override public String toString() { return "NewsBean [sumary=" + sumary + ", datetime=" + datetime + ", time=" + time + "]"; } public int id; public String sumary; public String datetime; public Date time; }
Java
package net.cardgame.orcalecard; import jp.jma.oraclecard.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.TextView; public class HelpActivity extends Activity implements OnClickListener { TextView tvHelpTitle; TextView tvHelpContent; Button btnBack; String helpTitle = ""; String helpContent = ""; int helpType; public static final String KEY_HELP_INDEX = "indexTypeHelp"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.help_screen); tvHelpTitle = (TextView) findViewById(R.id.tvHelpTitle); tvHelpContent = (TextView) findViewById(R.id.tvHelpContent); Bundle bundle = this.getIntent().getExtras(); helpType = bundle.getInt(KEY_HELP_INDEX); getHelpType(); tvHelpTitle.setText(helpTitle); tvHelpContent.setText(helpContent); btnBack = (Button) findViewById(R.id.btnBack); btnBack.setOnClickListener(this); } public void getHelpType() { switch (helpType) { case 0: // "kHelpTypeMyPage": helpTitle = "「マイページ」"; helpContent = " ここでは、リリース済みのオラクルカードを確認できます。ロックされているデッキは、購入後にロックが外れて使用可能になります。\n\n「保存データ」をタップすると、過去に自分が行い、保存したリーディング結果を見ることができます。\n\n「設定」をタップすると、アドバイスカードやジャンプカードの有無などについての各種設定を行うことができます。"; break; case 1: // "kHelpTypeRecord": helpTitle = "「保存データ一覧」"; helpContent = " 過去に保存したリーディング結果が一覧で表示されます。保存最大件数は 100件です。\n\n日時で区切られた部分をタップすると詳細表示を行います。また、削除したい日時を横にスワイプ(スライド)すると、その日時のデータを削除することができます。"; break; case 2: // "kHelpTypeMemo": helpTitle = "「保存データ詳細」"; helpContent = " 過去に保存したリーディング結果の詳細を表示しています。使用したデッキと、質問内容、引いたカード、カードを引いたときにメモした内容が表示されます。カード画像をタップすると、カード詳細を確認することができます。また、ここには「振り返りメモ」という欄を設置してあります。\n\n大切な質問の結果は時々確認してみましょう。そして、何か気づいたことがあったら「振り返りメモ」にそのことをしっかり記録しておきましょう。\n\nご自分で「この質問は完結した」と感じたら、感謝の気持ちを込めて、保存データ一覧から削除し、その質問をそっとリリースしましょう。"; break; case 3: // kHelpTypeSetting: helpTitle = "「設定」"; helpContent = " ここでは、リーディングを行う際の各種設定を行います。設定できる項目は「ジャンプカードの有無」「アドバイスカードの有無」「効果音の有無」「マイページでのデッキ並び順」です。\n\n「ジャンプカード」の設定が「ON」になっていると、シャッフル中にカードが勝手に飛び出す「ジャンプカード」が発生するようになります。ジャンプカードには強いメッセージが込められているとされていて、このジャンプカードだけでリーディングを行う人もいるほどです。「OFF」にするとジャンプカードは発生しなくなるので、完全に自分のタイミングでカードを引くことができます。\n\n「アドバイスカード」の設定が「ON」になっていると、3枚引きリーディングを行った際、最後にもう1枚カードを引くことができます。この追加で引いた4枚目のカードは前に引いた3枚のカードのメッセージを補う役割があり、3枚だけではわかりにくいメッセージには、この最後の1枚が重要なヒントになるでしょう。\n\n「効果音」の設定が「ON」になっていると、リーディング中に効果音が流れます。「OFF」にすると消音されます。\n\n「デッキ並び順」は「リリース順」「購入順」「使用順」が選択できます。お好みの並び順を選択してください。なお「購入順」「使用順」を選択した場合、未購入のデッキはリリース順に並べられます。"; break; case 4: // kHelpTypeCard: helpTitle = "「デッキタイトル」"; helpContent = " 画面上のカード1枚のアイコンをタップすると1枚引き、カード3枚のアイコンをタップすると3枚引きリーディングを行います。\n\n下部のメニューからは選択したデッキの紹介を見る「デッキ紹介」、選択したデッキに含まれる全カードを閲覧する「カードギャラリー」、各種設定を行う「設定」に移動できます。"; break; case 5: // kHelpTypeCardItemDetail: helpTitle = "「カード詳細」"; helpContent = " ここでは選択したカードをじっくり観ることができます。カード画像の下にはカードごとの解説があり、カードの持つ基本的な意味が記載されています。\n\nただし、解説に書いてあることが全てではありません。むしろリーディング時にはカードのアートワークのモチーフや色などの情報から直感で感じた内容が大切なメッセージとなります。そしてその内容をしっかりメモに残し、「直感でリーディングする」という感覚を身につけましょう。"; break; case 6: // kHelpTypeCardDetail: helpTitle = "「デッキ紹介」"; helpContent = " デッキの紹介です。また、未購入のデッキはこちらから購入の手続きを行うことができます。"; break; case 7: // kHelpTypeGallery: helpTitle = "「カードギャラリー」"; helpContent = " ここでは選択したデッキに含まれる全カード情報を閲覧できます。画面上を左右にスワイプ(スライド)することでカードを選択し、中央に表示されたカードをタップすると、カードの詳細情報を見ることができます。\n\n新しいデッキを手に入れたら、まず最初に全てのカードを確認しましょう。「カードへのあいさつ」をすることで、カードと仲良くなり、リーディングの精度も上がります。"; break; case 8: // kHelpTypeCleanup: helpTitle = "「浄化」"; helpContent = " リーディングを行う際には、デッキに溜まったエネルギーを浄化し、リセットすることで、新しい質問に対する回答の精度をも高めることができます。\n\n「浄化」と言っても難しいことはありません。利き手ではない方の手に本体を持ち、もう一方の手でカードを一度軽くタッチしてください。それだけでデッキは浄化され、新しい質問に対しての準備が整います。"; break; case 9: // kHelpTypeCardSuft: helpTitle = "「シャッフル&ドロー」"; helpContent = " ここでは、選択したデッキをシャッフルし、好きなタイミングでカードを引きます(ドロー)。デッキ画像をタップするとシャッフルされ、デッキ画像を上にスライドさせると一番上のカードが1枚スライドします。デッキの半分を超えた位置で指を離すと、そのカードが選ばれます。デッキの半分より下に戻した位置で指を離すと、カードはデッキに戻ります。\n\nドローするタイミングはあなたの自由です。ここだ! と思ったタイミングでカードを選んでください。\n\nここでは質問内容を書き込むことができます(最大 200文字)。心の中で思うだけでも問題ありませんが、質問内容を文字として書き込むことで自分が聞きたい質問をはっきりさせ、回答を理解する手助けになります。また、結果を保存した際には質問内容を記載しておくことで後からの振り返りがしやすくなります。質問はなるべく簡潔にまとめることが大切です。\n\nなお、設定で「ジャンプカード」が ON になっている場合は、シャッフル動作の時に勝手にカードが飛び出すことがあります。飛び出したカードには、より強い意思が込められていますので、しっかりとそのメッセージを受け取りましょう。"; break; case 10: // kHelpTypeSave: helpTitle = "「保存&投稿」"; helpContent = " ここでは、リーディング結果の本体への保存(最大 100件)ができます。質問内容(最大 200文字)と、結果を見た時の感想をメモとして書き込んで(最大 400文字)保存することができるので、後から見直した時の手助けになります。\n\n保存したデータは、マイページの下部メニュー「保存データ」からいつでも閲覧できます。\n\nまた、facebook にコメント付きで引いたカード画像を投稿できます。印象に残る結果が出た時や、朝に引いた「今日の1枚」を投稿して結果をみんなとシェアしましょう。プライバシー保護のため、facebook への投稿時には質問内容やメモの内容は投稿対象とはなりませんのでご安心ください。"; break; case 11: // kHelpTypeFacebook: helpTitle = "「facebook 投稿」"; helpContent = " 結果の画像を投稿することができます。また投稿する際にコメント(最大 200文字)を付けることもできます。プライバシー保護のため、facebook への投稿時には質問内容やメモの内容は投稿対象とはなりませんのでご安心ください。"; break; case 12: // kHelpTypeCardSpecial: helpTitle = "「スペシャルデッキ設定」"; helpContent = " ここでは、スペシャルデッキの設定を行います。「使用する」にしたデッキに含まれる全カードでリーディングを行います。デッキを組み合わせてあなただけのオリジナルデッキでリーディングをしてみましょう。きっと新しい発見がありますよ!"; break; default: break; } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnBack: finish(); break; default: break; } } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // switch (keyCode) { // case KeyEvent.KEYCODE_BACK: // // do something here // return true; // } // return super.onKeyDown(keyCode, event); // } }
Java
package net.cardgame.orcalecard.utils; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Date; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import net.cardgame.orcalecard.bean.DeckBean; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; 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.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import android.util.Log; public class XmlParser { /** * Method to get xml content from url HTTP Get request * */ public ArrayList<DeckBean> Parser(String url) { String xml = null; ArrayList<DeckBean> list = new ArrayList<DeckBean>(); try { // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Document doc = getDomElement(xml); NodeList cardList = doc.getElementsByTagName("Card"); for (int i = 0; i < cardList.getLength(); i++) { Node nodeCard = cardList.item(i); Element CardElement = (Element) nodeCard; DeckBean deckBean = new DeckBean(); deckBean.deckId = Integer.parseInt(CardElement .getAttribute("cardId")); deckBean.deckName = CardElement.getAttribute("name"); deckBean.isFree = Boolean.getBoolean(CardElement .getAttribute("free")); String date = CardElement.getAttribute("releaseDate"); String[] str = date.split("."); Date d = new Date(); d.setDate(Integer.parseInt(str[2])); d.setMonth(Integer.parseInt(str[1]) - 1); d.setYear(Integer.parseInt(str[0])); deckBean.releaseDate = d; deckBean.inAppPurchaseId = CardElement.getAttribute("purchaseId"); deckBean.deckPrice = Integer.parseInt(CardElement .getAttribute("price")); deckBean.cardNumber = Integer.parseInt(CardElement .getAttribute("numberOfCardsNewVersion")); deckBean.pathServerDownload = CardElement.getAttribute("server"); list.add(deckBean); } return list; } public String putToXmlString(ArrayList<DeckBean> list) { String result = ""; try { DocumentBuilderFactory docFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("root"); doc.appendChild(rootElement); for (DeckBean deckBean : list) { // Card elements Element card = doc.createElement("Card"); rootElement.appendChild(card); // set cardId Attribute for Card element card.setAttribute("cardId", deckBean.deckId + ""); // set name Attribute for Card element card.setAttribute("name", deckBean.deckName); // set free Attribute for Card element card.setAttribute("free", deckBean.isFree ? "1" : "0"); // set releaseDate Attribute for Card element card.setAttribute("releaseDate", deckBean.releaseDate.toString()); // set purchaseId Attribute for Card element card.setAttribute("purchaseId", deckBean.inAppPurchaseId); // set price Attribute for Card element card.setAttribute("price", deckBean.deckPrice + ""); // set numberOfCards Attribute for Card element card.setAttribute("numberOfCards", deckBean.cardNumber + ""); // set server Attribute for Card element card.setAttribute("server", deckBean.pathServerDownload); // set isUnlock Attribute for Card element card.setAttribute("isUnlock", deckBean.isUnlock ? "1" : "0"); // set percentDownloaded for Card element card.setAttribute("percentDownloaded", deckBean.percentDownloaded + ""); } result = toString(doc); } catch (Exception e) { // TODO: handle exception } return result; } public String toString(Document doc) { try { StringWriter sw = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); } catch (Exception ex) { throw new RuntimeException("Error converting to String", ex); } } public ArrayList<DeckBean> getDeckBeans(String configXML) { ArrayList<DeckBean> list = new ArrayList<DeckBean>(); try { Document doc = getDomElement(configXML); NodeList cardList = doc.getElementsByTagName("Card"); int minute = 60; for (int i = 0; i < cardList.getLength(); i++) { Node nodeCard = cardList.item(i); Element CardElement = (Element) nodeCard; DeckBean deckBean = new DeckBean(); deckBean.deckId = Integer.parseInt(CardElement .getAttribute("cardId")); deckBean.deckName = CardElement.getAttribute("name"); if (Integer.parseInt(CardElement.getAttribute("free")) == 1) deckBean.isFree = true; String date = CardElement.getAttribute("releaseDate"); String delimiter = "\\."; String[] str = date.split(delimiter); int year = Integer.parseInt(str[0]); int month = Integer.parseInt(str[1]) - 1; int day = Integer.parseInt(str[2]); deckBean.releaseDate = new Date(year - 1900, month, day); // Utils.ELog("release Date:" + deckBean.deckId, // deckBean.releaseDate.toGMTString()); deckBean.buyDate = new Date(0, 1, 1); deckBean.lastUsedDate = new Date(0, 1, 1); if (minute > 0) { deckBean.releaseDate.setMinutes(minute); deckBean.buyDate.setMinutes(minute); deckBean.lastUsedDate.setMinutes(minute); } minute--; deckBean.inAppPurchaseId = CardElement .getAttribute("purchaseId"); deckBean.deckPrice = Integer.parseInt(CardElement .getAttribute("price")); deckBean.cardNumber = Integer.parseInt(CardElement .getAttribute("numberOfCardsNewVersion")); deckBean.pathServerDownload = CardElement .getAttribute("server"); if (CardElement.hasAttribute("isUnlock")) { if (Integer.parseInt(CardElement.getAttribute("isUnlock")) == 1) deckBean.isUnlock = true; } if (CardElement.hasAttribute("percentDownloaded")) { deckBean.percentDownloaded = Integer.parseInt(CardElement .getAttribute("percentDownloaded")); } list.add(deckBean); } } catch (Exception ex) { } return list; } public Document getDomElement(String xml) { Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = (Document) db.parse(is); } catch (ParserConfigurationException e) { Log.e("Error: ", e.getMessage()); return null; } catch (SAXException e) { Log.e("Error: ", e.getMessage()); return null; } catch (IOException e) { Log.e("Error: ", e.getMessage()); return null; } return doc; } }
Java
package net.cardgame.orcalecard.utils; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.DisplayMetrics; import android.view.Display; /** * Lớp xử lý chung các vấn đề về ảnh * */ public class ImageUtils { // google loading bitmap Efficiently public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); } // google loading bitmap Efficiently public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; options.inScaled = false; // options.inDither = true; // options.inPreferQualityOverSpeed = true; return BitmapFactory.decodeFile(path, options); } // google loading bitmap Efficiently public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will // guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } /** * Chuyển từ DPp sang pixel * * @param dp * @param context * @return */ public static int convertDpToPixels(int dp, Context context) { DisplayMetrics metrics = new DisplayMetrics(); Display display = ((Activity) context).getWindowManager() .getDefaultDisplay(); display.getMetrics(metrics); float logicalDensity = metrics.density; int px = (int) (dp * logicalDensity + 0.5); return px; } }
Java
package net.cardgame.orcalecard.utils; import android.util.Log; public class Utils { private static final Boolean DEBUG = true; public static void ILog(String tag, String content) { if (DEBUG) { Log.i(tag, content); } } public static void ELog(String tag, String content) { if (DEBUG) { Log.e(tag, content); } } public static void DLog(String tag, String content) { if (DEBUG) { Log.d(tag, content); } } }
Java
package net.cardgame.orcalecard.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import android.util.Log; public class XmlParserInfoApp { public XmlParserInfoApp() { } public String getXmlFromUrl(String url) { String xml = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); // xml = EntityUtils.toString(httpEntity); InputStream inputStream = httpEntity.getContent(); xml = convertStreamToString(inputStream); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return xml; } public static String convertStreamToString(InputStream is) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); return sb.toString(); } public Document getDomElement(String xml) { Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = (Document) db.parse(is); } catch (ParserConfigurationException e) { Log.e("Error1: ", e.getMessage()); return null; } catch (SAXException e) { Log.e("Error2: ", e.getMessage()); return null; } catch (IOException e) { Log.e("Error3: ", e.getMessage()); return null; } return doc; } /** * Getting node value * * @param elem * element */ public final String getElementValue(Node elem) { Node child; if (elem != null) { if (elem.hasChildNodes()) { for (child = elem.getFirstChild(); child != null; child = child .getNextSibling()) { if (child.getNodeType() == Node.TEXT_NODE) { return child.getNodeValue(); } } } } return ""; } /** * Getting node value * * @param Element * node * @param key * string * */ public String getValue(Element item, String str) { NodeList n = item.getElementsByTagName(str); return this.getElementValue(n.item(0)); } }
Java
package net.cardgame.orcalecard.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import net.cardgame.oraclecard.service.DownloadUnzipObject; import net.cardgame.oraclecard.service.ServiceDownloadListener; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.io.ZipInputStream; import net.lingala.zip4j.model.FileHeader; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Shader.TileMode; import android.os.Environment; import android.os.StatFs; import android.util.Log; /** * Lớp xử lý chung các vấn đề về File * */ public class FileUtils { static double totalTime = 0; private ServiceDownloadListener listener; private DownloadUnzipObject downloadUnzipObject; private boolean cancel = false; public void stopUnzip() { cancel = true; } private synchronized void setPercentDownload(int percent) { downloadUnzipObject.setPercent(percent); synchronized (listener) { if (listener != null) { listener.onUpdateProgressListener( downloadUnzipObject.getPercent(), downloadUnzipObject.getPosition(), downloadUnzipObject.getDeckId()); } } } public void registryUnzipListener(ServiceDownloadListener listener) { this.listener = listener; } public FileUtils() { // TODO Auto-generated constructor stub } /** * Mã hóa file * * @param sourcePath * @param destinationPath * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public static void encrypt(String sourcePath, String destinationPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { // Here you read the cleartext. FileInputStream fis = new FileInputStream(sourcePath); // This stream write the encrypted text. This stream will be wrapped by // another stream. FileOutputStream fos = new FileOutputStream(destinationPath); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fos, cipher); // Write bytes int b; byte[] d = new byte[4096]; while ((b = fis.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); fis.close(); } /** * Giải mã file * * @param sourcePath * @param destinationPath * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public static void decrypt(String sourcePath, String destinationPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(sourcePath); FileOutputStream fos = new FileOutputStream(destinationPath); SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); CipherInputStream cis = new CipherInputStream(fis, cipher); int b; byte[] d = new byte[4096]; while ((b = cis.read(d)) != -1) { fos.write(d, 0, b); } fos.flush(); fos.close(); cis.close(); } /** * * Giải mã file thành byte[] để xử lý * * @param sourcePath * @param destinationPath * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public static byte[] decryptToByteArray(String sourcePath, String destinationPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(sourcePath); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); CipherInputStream cis = new CipherInputStream(fis, cipher); int b; byte[] d = new byte[4096]; while ((b = cis.read(d)) != -1) { bos.write(d, 0, b); } bos.flush(); cis.close(); return bos.toByteArray(); } public static byte[] testDecrytToByteArray(String sourcePath, String destinationPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(sourcePath); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); CipherInputStream cis = new CipherInputStream(fis, cipher); int b; byte[] d = new byte[4096]; b = cis.read(d); cis.close(); bos.write(d, 0, b); boolean firstByte = true; while ((b = fis.read(d)) != -1) { if (firstByte) { firstByte = false; continue; } bos.write(d, 0, b); } bos.flush(); fis.close(); return bos.toByteArray(); } public static InputStream decrytToInputStream(String sourcePath) { try { return new ByteArrayInputStream(decryptToByteArray(sourcePath, "")); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* Checks if external storage is available for read and write */ public static boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } /* Checks if external storage is available to at least read */ public static boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } static final int FILE_IMAGE_RESIZE = 1; static final int FILE_IMAGE_UNZIP = 2; static final int FILE_TEXT = 3; int getFileType(String fileName, String strDeckId) { if (fileName.contains("txt")) return FILE_TEXT; else if (fileName.contains("c" + strDeckId)) { fileName = fileName.substring(3, 5); if (convertStringToNumber(fileName) > 0) return FILE_IMAGE_RESIZE; else return FILE_IMAGE_UNZIP; } return FILE_IMAGE_UNZIP; } int convertStringToNumber(String str) { try { int i = Integer.parseInt(str); return i; } catch (Exception ex) { return -1; } } void testEncryptInputStream(byte[] data, String pathOutput) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException { InputStream inStreamX = new ByteArrayInputStream(data); FileOutputStream fosX = new FileOutputStream(pathOutput); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipherX = Cipher.getInstance("AES"); cipherX.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cosX = new CipherOutputStream(fosX, cipherX); // Writes bytes int b; byte[] d = new byte[4096]; // boolean firstByte = true; while ((b = inStreamX.read(d)) != -1) { cosX.write(d, 0, b); } cosX.flush(); cosX.close(); inStreamX.close(); } void testEncryptInputStream(ZipInputStream inputStream, FileOutputStream outputStream) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException { // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(outputStream, cipher); // Writes bytes int b; byte[] d = new byte[4096]; while ((b = inputStream.read(d)) != -1) { cos.write(d, 0, b); } cos.flush(); cos.close(); inputStream.close(); } public boolean unzipFile(DownloadUnzipObject object) { this.downloadUnzipObject = object; return unzipFile(object.getPathSaveFile(), object.getDeckId(), object.getPosition()); } /** * Create by hungcv * * perform unzipFile, create images X/2, X/3 and encrypt file * * @param path * path of zip file * @param deckId * deckBeanId * @return */ public boolean unzipFile(String path, int deckId, int position) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; String pathFolderUnzip = path.replaceAll(".zip", ""); String pathX2 = pathFolderUnzip + "/X2"; String pathX3 = pathFolderUnzip + "/X3"; File dirX2 = new File(pathX2); File dirX3 = new File(pathX3); dirX2.mkdirs(); dirX3.mkdirs(); try { ZipFile zipFile = new ZipFile(path); // if Zip file is password protected then set the password if (zipFile.isEncrypted()) { zipFile.setPassword(ConstantValue.PASSWORD); } // Get a list of FileHeader. FileHeader is the header information // for all the files in the ZipFile List listFileHeader = zipFile.getFileHeaders(); int size = listFileHeader.size(); int cardNumber = 0; for (int i = 0; i < size; i++) { FileHeader fileHeader = (FileHeader) listFileHeader.get(i); if (fileHeader.isDirectory()) continue; String fileName = fileHeader.getFileName(); fileName = fileName.split("\\/")[1]; if (getFileType(fileName, strDeckId) == FILE_IMAGE_RESIZE) { cardNumber++; } } int numberFileFinished = 0; for (int i = 0; i < size; i++) { if (cancel) return false; FileHeader fileHeader = (FileHeader) listFileHeader.get(i); if (fileHeader.isDirectory()) { continue; } String fileName = fileHeader.getFileName(); fileName = fileName.split("\\/")[1]; int typeFile = getFileType(fileName, strDeckId); if (typeFile != FILE_IMAGE_RESIZE) { // Utils.DLog("File Type", "FILE_ONLY_UNZIP"); String pathFileJPG = pathFolderUnzip + "/en_" + fileName; ZipInputStream in = zipFile.getInputStream(fileHeader); FileOutputStream fosjpg = new FileOutputStream(pathFileJPG); // encypt file testEncryptInputStream(in, fosjpg); } else { // Utils.DLog("File Type", "FILE_IMAGE_RESIZE"); String pathFileX = pathFolderUnzip + "/en_" + fileName; String pathFileX2 = pathX2 + "/en_" + fileName; String pathFileX3 = pathX3 + "/en_" + fileName; Bitmap bmpX = BitmapFactory.decodeStream(zipFile .getInputStream(fileHeader)); ByteArrayOutputStream streamX = new ByteArrayOutputStream(); bmpX.compress(Bitmap.CompressFormat.PNG, 0, streamX); byte[] byteArrayX = streamX.toByteArray(); testEncryptInputStream(byteArrayX, pathFileX); // // Create image X2 Bitmap bmpX2 = resizeBitmap(bmpX, 2); bmpX.recycle(); ByteArrayOutputStream streamX2 = new ByteArrayOutputStream(); bmpX2.compress(Bitmap.CompressFormat.PNG, 0, streamX2); byte[] byteArrayX2 = streamX2.toByteArray(); testEncryptInputStream(byteArrayX2, pathFileX2); // Create image X3 Bitmap bmpX3 = resizeBitmap(bmpX2, 4); bmpX2.recycle(); ThreadCreateX3Image threadX3 = new ThreadCreateX3Image( bmpX3, pathFileX3); threadX3.start(); numberFileFinished++; // report percent download if (downloadUnzipObject != null) { int percent = (int) (((float) numberFileFinished / (float) cardNumber) * 49); this.setPercentDownload(50 + percent); } } } } catch (ZipException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } if (downloadUnzipObject != null) { this.setPercentDownload(100); } File fileRoot = new File(path); fileRoot.delete(); return true; } class ThreadCreateX3Image extends Thread { Bitmap bmp; String path; public ThreadCreateX3Image(Bitmap bmp, String path) { this.bmp = bmp; this.path = path; } @Override public void run() { // TODO Auto-generated method stub try { ByteArrayOutputStream arrayOs = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 0, arrayOs); bmp.recycle(); byte[] byteArray = arrayOs.toByteArray(); InputStream inStreamX = new ByteArrayInputStream(byteArray); FileOutputStream fosX = new FileOutputStream(path); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipherX = Cipher.getInstance("AES"); cipherX.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cosX = new CipherOutputStream(fosX, cipherX); // Writes bytes int b; byte[] d = new byte[4096]; // boolean firstByte = true; while ((b = inStreamX.read(d)) != -1) { cosX.write(d, 0, b); } cosX.flush(); cosX.close(); inStreamX.close(); ; } catch (Exception ex) { } } } /* * Sau khi download xong file zip ve thuc hien xu ly: - Load tu dau toi cuoi * file zip - Toi fileHeader nao: + Neu header la PNG: * Tao cac X2, X3 * Ma * hoa cac X, X3, X2 * Ghi X, X2, X3 ra sdcard + Neu header la TXT: * ma hoa * cac text file * ghi cac text file ra sdcard */ public boolean processFileZip(String pathFileZip) { String strDECKID = getDeckId(pathFileZip); String pathFolderUnzip = getFolder(pathFileZip) + "/Card_" + strDECKID; String pathFolderX2 = pathFolderUnzip + "/X2"; String pathFolderX3 = pathFolderUnzip + "/X3"; File dirX2 = new File(pathFolderX2); File dirX3 = new File(pathFolderX3); dirX2.mkdirs(); dirX3.mkdirs(); try { ZipFile zipFile = new ZipFile(pathFileZip); // if Zip file is password protected then set the password if (zipFile.isEncrypted()) { zipFile.setPassword(ConstantValue.PASSWORD); } // Get a list of FileHeader. FileHeader is the header information // for all the files in the ZipFile List listFileHeader = zipFile.getFileHeaders(); // Loop through all the fileHeaders for (int i = 0; i < listFileHeader.size(); i++) { FileHeader fileHeader = (FileHeader) listFileHeader.get(i); // Checks if the file is a directory if (fileHeader.isDirectory()) { continue; } /* * THUC HIEN XU LY FILE Background "*.jpg" */ boolean kJPG = filterFileHeader(fileHeader.getFileName(), "jpg"); if (kJPG) { String nameFile = fileHeader.getFileName().split("\\/")[1]; String pathFileJPG = pathFolderUnzip + "/en_" + nameFile; ZipInputStream in = zipFile.getInputStream(fileHeader); FileOutputStream fosjpg = new FileOutputStream(pathFileJPG); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fosjpg, cipher); // Write bytes int b; byte[] d = new byte[4096]; while ((b = in.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); in.close(); } /* * THUC HIEN XU LY CAC FILE *.txt */ boolean kTXT = filterFileHeader(fileHeader.getFileName(), "txt"); if (kTXT) { String nameFile = fileHeader.getFileName().split("\\/")[1]; String pathFileText = pathFolderUnzip + "/en_" + nameFile; ZipInputStream inputStream = zipFile .getInputStream(fileHeader); FileOutputStream fostext = new FileOutputStream( pathFileText); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fostext, cipher); // Write bytes int b; byte[] d = new byte[4096]; while ((b = inputStream.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); inputStream.close(); } /* * THUC HIEN XU LY CAC FILE *.png */ boolean kPNG = filterFileHeader(fileHeader.getFileName(), "png"); if (kPNG) { String nameFile = fileHeader.getFileName().split("\\/")[1]; String pathFileX = pathFolderUnzip + "/en_" + nameFile; String pathFileX2 = pathFolderX2 + "/en_" + nameFile; String pathFileX3 = pathFolderX3 + "/en_" + nameFile; // File fileX = new File("", // fileHeader.getFileName().split("\\/")[1]); Bitmap bmpX = BitmapFactory.decodeStream(zipFile .getInputStream(fileHeader)); Bitmap bmpX2 = resizeBitmap(bmpX, 2); Bitmap bmpX3 = resizeBitmap(bmpX, 3); // convert bitmap -> byte array ByteArrayOutputStream streamX = new ByteArrayOutputStream(); ByteArrayOutputStream streamX2 = new ByteArrayOutputStream(); ByteArrayOutputStream streamX3 = new ByteArrayOutputStream(); bmpX.compress(Bitmap.CompressFormat.PNG, 0, streamX); bmpX.recycle(); bmpX2.compress(Bitmap.CompressFormat.PNG, 0, streamX2); bmpX2.recycle(); bmpX3.compress(Bitmap.CompressFormat.PNG, 0, streamX3); bmpX3.recycle(); byte[] byteArrayX = streamX.toByteArray(); byte[] byteArrayX2 = streamX2.toByteArray(); byte[] byteArrayX3 = streamX3.toByteArray(); // convert byte array -> inputstream InputStream inStreamX = new ByteArrayInputStream(byteArrayX); InputStream inStreamX2 = new ByteArrayInputStream( byteArrayX2); InputStream inStreamX3 = new ByteArrayInputStream( byteArrayX3); FileOutputStream fosX = new FileOutputStream(pathFileX); FileOutputStream fosX2 = new FileOutputStream(pathFileX2); FileOutputStream fosX3 = new FileOutputStream(pathFileX3); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipherX = Cipher.getInstance("AES"); Cipher cipherX2 = Cipher.getInstance("AES"); Cipher cipherX3 = Cipher.getInstance("AES"); cipherX.init(Cipher.ENCRYPT_MODE, sks); cipherX2.init(Cipher.ENCRYPT_MODE, sks); cipherX3.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cosX = new CipherOutputStream(fosX, cipherX); CipherOutputStream cosX2 = new CipherOutputStream(fosX2, cipherX2); CipherOutputStream cosX3 = new CipherOutputStream(fosX3, cipherX3); // Writes bytes int b; byte[] d = new byte[4096]; while ((b = inStreamX.read(d)) != -1) { cosX.write(d, 0, b); } cosX.flush(); cosX.close(); inStreamX.close(); while ((b = inStreamX2.read(d)) != -1) { cosX2.write(d, 0, b); } cosX2.flush(); cosX2.close(); inStreamX2.close(); while ((b = inStreamX3.read(d)) != -1) { cosX3.write(d, 0, b); } cosX3.flush(); cosX3.close(); inStreamX3.close(); } Log.d("Done extracting: ", fileHeader.getFileName()); } } catch (ZipException e) { Log.e("ZipException", e.toString()); return false; } catch (FileNotFoundException e) { Log.e("FileNotFoundException", e.toString()); return false; } catch (IOException e) { Log.e("IOException", e.toString()); return false; } catch (Exception e) { Log.e("Exception", e.toString()); return false; } // Xoa file zip sau khi xu ly hoan thanh File f = new File(pathFileZip); f.delete(); return true; } public boolean filterFileHeader(String fileHeader, String filter) { boolean check = false; String[] sub = fileHeader.split("\\."); String s = sub[1]; if (s.equalsIgnoreCase(filter)) check = true; return check; } // Nếu s = "/mnt/sdcard/testpass.zip" // Thì folderName = "/mnt/sdcard" public String getFolder(String s) { String folderName = ""; for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == '/') { folderName = s.substring(0, i); break; } } return folderName; } // Lấy về tất cả các file trong folder ung voi bo loc "filter" public ArrayList<String> getListFile(String pathFolder, String filter) { ArrayList<String> tmpList = new ArrayList<String>(); ArrayList<String> list = new ArrayList<String>(); File f = new File(pathFolder); // Kiểm tra folder tồn tại hay không // Hoặc có phải là thư mục hay không if (!f.exists() || !f.isDirectory()) { return null; } String[] files = f.list(); if (files.length == 0) { // Không có file nào trong folder return null; } for (int i = 0; i < files.length; i++) { tmpList.add(files[i]); } for (int i = 0; i < tmpList.size(); i++) { String s = tmpList.get(i); String typeFile = s.substring(s.length() - 3, s.length()); if (typeFile.equalsIgnoreCase(filter)) list.add(s); } return list; } /* * Resize lai kich thuoc bitmap */ public Bitmap resizeBitmap(Bitmap bmp, int i) { int width = 0, height = 0; switch (i) { case 2: width = bmp.getWidth() / 2; height = bmp.getHeight() / 2; break; case 3: width = bmp.getWidth() / 3; height = bmp.getHeight() / 3; case 4: width = (int) (bmp.getWidth() / 1.5); height = (int) (bmp.getHeight() / 1.5); default: break; } Bitmap resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height, true); return resizedbitmap; } @SuppressWarnings("resource") public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); // Get the size of the file long length = file.length(); // You cannot create an array using a long type. // It needs to be an int type. // Before converting to an int type, check // to ensure that file is not larger than Integer.MAX_VALUE. if (length > Integer.MAX_VALUE) { // File is too large } // Create the byte array to hold the data byte[] bytes = new byte[(int) length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, Math.min(bytes.length - offset, 512 * 1024))) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } // Close the input stream and return bytes is.close(); return bytes; } // get deckId from path filezip public String getDeckId(String pathFileZip) { String subPath = ""; String[] arr = null; arr = pathFileZip.split("\\/"); subPath = arr[arr.length - 1]; arr = subPath.split("\\_"); subPath = arr[arr.length - 1]; arr = subPath.split("\\."); subPath = arr[0]; return subPath; } public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size = 1024; try { byte[] bytes = new byte[buffer_size]; for (;;) { int count = is.read(bytes, 0, buffer_size); if (count == -1) break; os.write(bytes, 0, count); } } catch (Exception ex) { } } public static Bitmap createReflectedImage(Bitmap b) { final int reflectionGap = 10; Bitmap originalImage = b; int width = originalImage.getWidth(); int height = originalImage.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(originalImage, 0, 0, null); // Paint deafaultPaint = new Paint(); // canvas.drawRect(0, height, width, height + reflectionGap, // deafaultPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } /** * @param downloadsize * byte * @return true: SDCARD available * * <br> * false:SDCARD unvailable */ public static boolean availableDownload(double downloadsize) { StatFs stat = new StatFs(Environment.getExternalStorageDirectory() .getPath()); double sdAvailSize = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize(); return sdAvailSize > 3 * downloadsize; } }
Java
package net.cardgame.orcalecard.utils; import android.app.Activity; import android.view.inputmethod.InputMethodManager; public class KeyboardHelper { public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity .getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus() .getWindowToken(), 0); } }
Java
package net.cardgame.orcalecard.utils; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.HistoryBean; public class Sort { public static final Comparator<DeckBean> RELEASE_ORDER = new Comparator<DeckBean>() { public int compare(DeckBean d1, DeckBean d2) { return d1.releaseDate.compareTo(d2.releaseDate); } }; static final Comparator<DeckBean> BUY_ORDER = new Comparator<DeckBean>() { public int compare(DeckBean d1, DeckBean d2) { return d1.buyDate.compareTo(d2.buyDate); } }; static final Comparator<DeckBean> USED_ORDER = new Comparator<DeckBean>() { public int compare(DeckBean d1, DeckBean d2) { return d1.lastUsedDate.compareTo(d2.lastUsedDate); } }; static final Comparator<HistoryBean> DATE_ORDER = new Comparator<HistoryBean>() { public int compare(HistoryBean d1, HistoryBean d2) { return d1.datetime.compareTo(d2.datetime); } }; public static ArrayList<HistoryBean> sortHistoryByDate( ArrayList<HistoryBean> list) { Collections.sort(list, DATE_ORDER); Collections.reverse(list); return list; } public static ArrayList<DeckBean> sortByRelease(ArrayList<DeckBean> list) { Collections.sort(list, RELEASE_ORDER); Collections.reverse(list); return list; } public static ArrayList<DeckBean> sortByBuy(ArrayList<DeckBean> list) { Collections.sort(list, BUY_ORDER); Collections.reverse(list); return list; } public static ArrayList<DeckBean> sortByLastUsed(ArrayList<DeckBean> list) { Collections.sort(list, USED_ORDER); Collections.reverse(list); return list; } }
Java
package net.cardgame.orcalecard.utils; import java.lang.reflect.Type; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import android.content.Context; import android.os.Environment; import android.os.StatFs; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class ConstantValue { public static final int RESULT_ACTIVITY = 7; public static final int SAVE_HISTORY_ACTIVITY = 8; public static final String CONFIG_DECKBEAN_KEY = "list_deckbean"; public static final int CURRENT_API_VERSION = android.os.Build.VERSION.SDK_INT; // base url cho API public static final String BASE_URL = "http://www.jma-inc.jp/appdata/OracleCard/"; // key history shared reference public static final String HISTORY_KEY = "history_sharedreference"; // key setting app shared reference public static final String SETTING_KEY = "setting_sharedreference"; // url của file chứa danh sách deck public static final String LIST_DECK_SUB_URL = "ConfigAndroid.xml"; // key sharedreference để kiểm tra đã load hết dữ liệu màn hình toppage chưa public static final String KEY_LOAD_FINISHED_TOPPAGE = "key_toppage_finished"; // key để mã hóa/giải mã File public static String FILE_SECRET_KEY = "MyDifficultPassw"; public static String PREFERENCES_SECRET_KEY = "runsystem"; // public static final String ACTION_DOWNLOAD = "download action"; // Cú pháp shared preferences public static String PREFERENCES_DECK_PREFIX = "DECK"; public static String PREFERENCES_CARD_PREFIX = "CARD"; // Name shared preferences public static String APP_PREFERENCES = "net.oraclecard"; // Key shared preferences public static String CONFIG_XML = "CONFIG_XML"; // public static String PASSWORD = "105af58a06470c1c0d686fdf0134485c"; public static String URL_XML_INFOAPP = "http://doreen.jp/apnews.xml"; public static SettingApp getSettingApp(Context context) { SettingApp setting = new SettingApp(); SecurePreferences appPreferences = new SecurePreferences(context, APP_PREFERENCES, PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); setting = gson.fromJson(strSetting, SettingAppType); } return setting; } public static String getBasePatchApp(Context context) { return context.getApplicationContext().getExternalFilesDir(null) .getPath(); } public static String getPatchCardData(Context context) { return getBasePatchApp(context) + "/Card_Data/"; } public static String getPathCard00(Context context, int deckId) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; return getPatchCardData(context) + "Card_" + strDeckId + "/en_c" + strDeckId + "d.png"; } public static String getPathDeckImage(Context context, int deckId, String prefix) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; return getPatchCardData(context) + "Card_" + strDeckId + "/en_c" + strDeckId + prefix + ".png"; } public static String getPathBackgroundByDeckId(Context context, int deckId) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; return getPatchCardData(context) + "Card_" + strDeckId + "/en_bg" + strDeckId + ".jpg"; } public static final int X1 = 1; public static final int X2 = 2; public static final int X3 = 3; public static String getPathCardDetail(Context context, int deckId, int cardId, int sizeType) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; String strCardId = cardId < 10 ? "0" + cardId : "" + cardId; String strSize = ""; switch (sizeType) { case X2: strSize = "/X2/"; break; case X3: strSize = "/X3/"; break; default: break; } String path = getPatchCardData(context) + "Card_" + strDeckId + strSize + "/en_c" + strDeckId + strCardId + ".png"; return path; } /** * Check available free space on SD card * * @return true if free space SD card > required size */ public static boolean isAvailableSpaceSDCard(int sizeRequiredMB) { StatFs stat = new StatFs(Environment.getExternalStorageDirectory() .getPath()); double sdAvailSize = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize(); // One binary MB equals 1024*1024 bytes. double minSize = sizeRequiredMB * 1024 * 1024; if (sdAvailSize > minSize) return true; else return false; } }
Java
package net.cardgame.orcalecard; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.MySwitch; import net.cardgame.orcalecard.bean.SettingApp; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; public class SettingSortActivity extends Activity implements OnClickListener, OnCheckedChangeListener { int sortby = 0; MySwitch switchRelease, switchPayment, switchUsed; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.setting_sort_layout); findViewById(R.id.btn_back_setting_sort).setOnClickListener(this); Bundle bundle = this.getIntent().getExtras(); sortby = bundle.getInt("sort_by"); switchRelease = (MySwitch) findViewById(R.id.switch_by_release); switchPayment = (MySwitch) findViewById(R.id.switch_by_payment); switchUsed = (MySwitch) findViewById(R.id.switch_by_used); switchUsed.setOnCheckedChangeListener(this); switchRelease.setOnCheckedChangeListener(this); switchPayment.setOnCheckedChangeListener(this); switchUsed.setChecked(false); switchRelease.setChecked(false); switchPayment.setChecked(false); switch (sortby) { case SettingApp.SORT_BY_RELEASE: switchRelease.setChecked(true); break; case SettingApp.SORT_BY_USED: switchUsed.setChecked(true); break; case SettingApp.SORT_BY_BUY: switchPayment.setChecked(true); break; default: break; } } @Override public void onClick(View v) { // TODO Auto-generated method stub setResult(sortby); this.finish(); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (!isChecked && !switchUsed.isChecked() && !switchRelease.isChecked() && !switchPayment.isChecked()) { sortby = SettingApp.SORT_BY_RELEASE; } switch (buttonView.getId()) { case R.id.switch_by_payment: if (isChecked) { sortby = SettingApp.SORT_BY_BUY; switchUsed.setChecked(false); switchRelease.setChecked(false); } break; case R.id.switch_by_release: if (isChecked) { sortby = SettingApp.SORT_BY_RELEASE; switchUsed.setChecked(false); switchPayment.setChecked(false); } break; case R.id.switch_by_used: if (isChecked) { sortby = SettingApp.SORT_BY_USED; switchRelease.setChecked(false); switchPayment.setChecked(false); } break; default: break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { setResult(sortby); this.finish(); } return super.onKeyDown(keyCode, event); } }
Java
package net.cardgame.orcalecard; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import android.graphics.Bitmap; import android.util.Log; public class GalleryMemoryCache { private static final String TAG = "MemoryCache"; // Last argument true for LRU ordering private Map<String, Bitmap> cache = Collections .synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true)); // current allocated size private long size = 0; // max memory in bytes private long limit = 1000000; public GalleryMemoryCache() { // use 25% of available heap size setLimit(Runtime.getRuntime().maxMemory() / 4); } public void setLimit(long new_limit) { limit = new_limit; Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB"); } public Bitmap get(String id) { try { if (!cache.containsKey(id)) return null; // NullPointerException sometimes happen here // http://code.google.com/p/osmdroid/issues/detail?id=78 return cache.get(id); } catch (NullPointerException ex) { ex.printStackTrace(); return null; } } public void put(String id, Bitmap bitmap) { try { if (cache.containsKey(id)) size -= getSizeInBytes(cache.get(id)); cache.put(id, bitmap); size += getSizeInBytes(bitmap); checkSize(); } catch (Throwable th) { th.printStackTrace(); } } private void checkSize() { Log.i(TAG, "cache size=" + size + " length=" + cache.size()); if (size > limit) { // Least recently accessed item will be the first one iterated Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator(); while (iter.hasNext()) { Entry<String, Bitmap> entry = iter.next(); size -= getSizeInBytes(entry.getValue()); iter.remove(); if (size <= limit) break; } Log.i(TAG, "Clean cache. New size " + cache.size()); } } public void clear() { try { // NullPointerException sometimes happen here // http://code.google.com/p/osmdroid/issues/detail?id=78 cache.clear(); size = 0; } catch (NullPointerException ex) { ex.printStackTrace(); } } long getSizeInBytes(Bitmap bitmap) { if (bitmap == null) return 0; return bitmap.getRowBytes() * bitmap.getHeight(); } }
Java
package net.cardgame.orcalecard.pref; import java.util.Iterator; import java.util.Map; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class GalleryPreferences { public static final int MODE = Context.MODE_PRIVATE; public static final String PREF_GALLERY = "GALLERY_PREFERENCES"; public static void writeString(Context context, String key, String value) { getEditor(context).putString(key, value).commit(); } public static String readString(Context context, String key, String defValue) { return getPreferences(context).getString(key, defValue); } public static SharedPreferences getPreferences(Context context) { return context.getSharedPreferences(PREF_GALLERY, MODE); } public static Editor getEditor(Context context) { return getPreferences(context).edit(); } @SuppressWarnings("rawtypes") public static boolean checkKey(Context context, String key) { SharedPreferences sharedPreferences = getPreferences(context); Iterator iter = sharedPreferences.getAll().entrySet().iterator(); while (iter.hasNext()) { Map.Entry pair = (Map.Entry)iter.next(); if (pair.getKey().toString().equals(key)) return true; } return false; } }
Java
package net.cardgame.orcalecard.pref; /* Copyright (C) 2012 Sveinung Kval Bakken, sveinung.bakken@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import android.content.Context; import android.content.SharedPreferences; import android.util.Base64; /** * Lớp share Preferences đã xử lý mã hóa Sử dụng hàm put, get String * */ public class SecurePreferences { public static class SecurePreferencesException extends RuntimeException { public SecurePreferencesException(Throwable e) { super(e); } } private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; private static final String KEY_TRANSFORMATION = "AES/ECB/PKCS5Padding"; private static final String SECRET_KEY_HASH_TRANSFORMATION = "SHA-256"; private static final String CHARSET = "UTF-8"; private final boolean encryptKeys; private final Cipher writer; private final Cipher reader; private final Cipher keyWriter; private final SharedPreferences preferences; /** * This will initialize an instance of the SecurePreferences class * * @param context * your current context. * @param preferenceName * name of preferences file (preferenceName.xml) * @param secureKey * the key used for encryption, finding a good key scheme is * hard. Hardcoding your key in the application is bad, but * better than plaintext preferences. Having the user enter the * key upon application launch is a safe(r) alternative, but * annoying to the user. * @param encryptKeys * settings this to false will only encrypt the values, true will * encrypt both values and keys. Keys can contain a lot of * information about the plaintext value of the value which can * be used to decipher the value. * @throws SecurePreferencesException */ public SecurePreferences(Context context, String preferenceName, String secureKey, boolean encryptKeys) throws SecurePreferencesException { try { this.writer = Cipher.getInstance(TRANSFORMATION); this.reader = Cipher.getInstance(TRANSFORMATION); this.keyWriter = Cipher.getInstance(KEY_TRANSFORMATION); initCiphers(secureKey); this.preferences = context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE); this.encryptKeys = encryptKeys; } catch (GeneralSecurityException e) { throw new SecurePreferencesException(e); } catch (UnsupportedEncodingException e) { throw new SecurePreferencesException(e); } } protected void initCiphers(String secureKey) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException { IvParameterSpec ivSpec = getIv(); SecretKeySpec secretKey = getSecretKey(secureKey); writer.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); reader.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); keyWriter.init(Cipher.ENCRYPT_MODE, secretKey); } protected IvParameterSpec getIv() { byte[] iv = new byte[writer.getBlockSize()]; System.arraycopy("fldsjfodasjifudslfjdsaofshaufihadsf".getBytes(), 0, iv, 0, writer.getBlockSize()); return new IvParameterSpec(iv); } protected SecretKeySpec getSecretKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException { byte[] keyBytes = createKeyBytes(key); return new SecretKeySpec(keyBytes, TRANSFORMATION); } protected byte[] createKeyBytes(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest .getInstance(SECRET_KEY_HASH_TRANSFORMATION); md.reset(); byte[] keyBytes = md.digest(key.getBytes(CHARSET)); return keyBytes; } public void put(String key, String value) { if (value == null) { preferences.edit().remove(toKey(key)).commit(); } else { putValue(toKey(key), value); } } public boolean containsKey(String key) { return preferences.contains(toKey(key)); } public void removeValue(String key) { preferences.edit().remove(toKey(key)).commit(); } public String getString(String key) throws SecurePreferencesException { if (preferences.contains(toKey(key))) { String securedEncodedValue = preferences.getString(toKey(key), ""); return decrypt(securedEncodedValue); } return null; } public void clear() { preferences.edit().clear().commit(); } private String toKey(String key) { if (encryptKeys) return encrypt(key, keyWriter); else return key; } private void putValue(String key, String value) throws SecurePreferencesException { String secureValueEncoded = encrypt(value, writer); preferences.edit().putString(key, secureValueEncoded).commit(); } protected String encrypt(String value, Cipher writer) throws SecurePreferencesException { byte[] secureValue; try { secureValue = convert(writer, value.getBytes(CHARSET)); } catch (UnsupportedEncodingException e) { throw new SecurePreferencesException(e); } String secureValueEncoded = Base64.encodeToString(secureValue, Base64.NO_WRAP); return secureValueEncoded; } protected String decrypt(String securedEncodedValue) { byte[] securedValue = Base64 .decode(securedEncodedValue, Base64.NO_WRAP); byte[] value = convert(reader, securedValue); try { return new String(value, CHARSET); } catch (UnsupportedEncodingException e) { throw new SecurePreferencesException(e); } } private static byte[] convert(Cipher cipher, byte[] bs) throws SecurePreferencesException { try { return cipher.doFinal(bs); } catch (Exception e) { throw new SecurePreferencesException(e); } } }
Java
package net.cardgame.orcalecard; import java.util.ArrayList; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.SelectedHistoryListener; import net.cardgame.orcalecard.bean.HistoryBean; import android.annotation.SuppressLint; import android.app.Activity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; @SuppressLint("ResourceAsColor") public class HistoryAdapter extends ArrayAdapter<HistoryBean> implements OnTouchListener, OnClickListener { ArrayList<HistoryBean> listHistory = new ArrayList<HistoryBean>(); Activity context; int x_old = 0, y_old = 0; int selectedId = 0; boolean ontouch = false; SelectedHistoryListener listener; boolean clear = false; public HistoryAdapter(Activity context, ArrayList<HistoryBean> objects) { super(context, R.layout.item_listview_history, objects); // TODO Auto-generated constructor stub this.listHistory = objects; this.context = context; this.listener = (SelectedHistoryListener) context; } static class ViewHolder { TextView txtDateTime; ImageView imgNumberOfCard; TextView txtDeckTitle; TextView txtQuestion; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.item_listview_history, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.txtDateTime = (TextView) rowView .findViewById(R.id.txtDatetime_history); viewHolder.txtDeckTitle = (TextView) rowView .findViewById(R.id.txtdecktitle_history); viewHolder.txtQuestion = (TextView) rowView .findViewById(R.id.txtQuestion_history); viewHolder.imgNumberOfCard = (ImageView) rowView .findViewById(R.id.img_numberofcard_history); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); HistoryBean history = listHistory.get(position); holder.txtDateTime.setText(history.strDateTime); holder.txtDeckTitle.setText(history.deckTitle); holder.txtQuestion.setText(history.question); rowView.setId(listHistory.get(position).id); int size = history.cardBeans.size(); switch (size) { case 1: holder.imgNumberOfCard.setImageResource(R.drawable.result_draw1); break; case 3: holder.imgNumberOfCard.setImageResource(R.drawable.result_draw3); break; case 4: holder.imgNumberOfCard.setImageResource(R.drawable.result_draw4); break; default: break; } rowView.findViewById(R.id.btnDelete_history).setVisibility( View.INVISIBLE); rowView.setOnTouchListener(this); return rowView; } @Override public boolean onTouch(View v, MotionEvent event) { int id = v.getId(); int x = (int) event.getRawX(); int y = (int) event.getRawY(); if (id != selectedId && selectedId != 0) { // clear all row focus this.notifyDataSetChanged(); selectedId = 0; } switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: x_old = x; y_old = y; v.setSelected(true); break; case MotionEvent.ACTION_MOVE: if (x - x_old > 10) { v.setSelected(true); selectedId = v.getId(); ImageView btnDelete = (ImageView) v .findViewById(R.id.btnDelete_history); btnDelete.setVisibility(View.VISIBLE); ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f); anim.setDuration(500); btnDelete.startAnimation(anim); btnDelete.setOnClickListener(this); return false; } break; case MotionEvent.ACTION_UP: if (selectedId == 0) v.setSelected(false); if (Math.abs(x - x_old) < 3 && Math.abs(y - y_old) < 3) { listener.onSelectedItemListener(v.getId()); v.setSelected(false); } break; case MotionEvent.ACTION_CANCEL: if (selectedId == 0) v.setSelected(false); break; default: break; } return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub for (HistoryBean history : listHistory) { if (history.id == selectedId) { selectedId = 0; listHistory.remove(history); this.notifyDataSetChanged(); listener.onDeleteHistory(history); return; } } } }
Java
package net.cardgame.orcalecard; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.NoSuchPaddingException; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.FileUtils; import net.cardgame.orcalecard.utils.Utils; import uk.co.senab.bitmapcache.BitmapLruCache; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; public class CardDeckActivity extends Activity implements OnClickListener { int deckId; DeckBean deckBean; final static int SWITCH_1_3 = 99; SettingApp setting; ImageView img_bg_card_deck, img_csdt1_3; Intent intent; boolean flag = true; boolean continueFlow = false; int number_of_card = 0; final static int requestcodeInfoDeck = 10; int cardTotal = 0; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setting = ConstantValue.getSettingApp(this); deckBean = new DeckBean(); Bundle bundle = this.getIntent().getExtras(); deckId = bundle.getInt("deckId"); deckBean.deckId = deckId; if (bundle.containsKey("deckName")) deckBean.deckName = bundle.getString("deckName"); if (bundle.containsKey("deckPrice")) deckBean.deckPrice = bundle.getInt("deckPrice"); if (bundle.containsKey("deckPathServer")) deckBean.pathServerDownload = bundle.getString("deckPathServer"); if (bundle.containsKey("cardTotal")) { cardTotal = bundle.getInt("cardTotal"); } setContentView(R.layout.card_deck_activity); img_csdt1_3 = (ImageView) findViewById(R.id.img_csdt1_3); img_bg_card_deck = (ImageView) findViewById(R.id.img_bg_card_deck); findViewById(R.id.btnhelp_card_deck).setOnClickListener(this); findViewById(R.id.btn_back_to_mypage).setOnClickListener(this); findViewById(R.id.btn_info_deck).setOnClickListener(this); findViewById(R.id.btn_goto_gallery).setOnClickListener(this); findViewById(R.id.btn_setting_card_deck).setOnClickListener(this); findViewById(R.id.btn_select_one_card).setOnClickListener(this); findViewById(R.id.btn_select_three_card).setOnClickListener(this); loadImage(); if (deckId != 999) { loadDataImageThread loadBitmap = new loadDataImageThread(); loadBitmap.start(); } else { continueFlow = true; } } void loadImage() { if (deckId == 999) { img_bg_card_deck.setImageResource(R.drawable.c999t); img_csdt1_3.setImageResource(R.drawable.c999t1_3); return; } new ThreadLoadImage(this, handler1, ConstantValue.getPathDeckImage( this, deckId, "t"), img_bg_card_deck, 1).start(); new ThreadLoadImage(this, handler1, ConstantValue.getPathDeckImage( this, deckId, "t1-3"), img_csdt1_3, 2).start(); } Handler handler1 = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch (msg.what) { case 1: img_bg_card_deck.setImageDrawable((Drawable) msg.obj); break; case 2: BitmapDrawable drawabe = (BitmapDrawable) msg.obj; if (drawabe != null && !drawabe.getBitmap().isRecycled()) { img_csdt1_3.setImageDrawable((Drawable) msg.obj); continueFlow = true; } break; case 10: gotoSplashActivity(); break; default: break; } } }; @Override public void onClick(View v) { // TODO Auto-generated method stub if (!flag) return; else flag = false; switch (v.getId()) { case R.id.btnhelp_card_deck:// go to help Activity intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 4); startActivityForResult(intent, 4); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_back_to_mypage:// back to My Page if (bitmapBackImage != null) { bitmapBackImage.recycle(); } backtoToppageActivity(); break; case R.id.btn_info_deck:// go to deck bean information activity passDeck(deckBean); break; case R.id.btn_goto_gallery:// go to card gallery activity intent = new Intent(this, GalleryActivity.class); intent.putExtras(getIntent().getExtras()); startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); this.finish(); break; case R.id.btn_setting_card_deck: // go to deck bean setting activity Intent intent2 = new Intent(this, SettingActiviy.class); startActivityForResult(intent2, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_select_three_card: // selected get three card number_of_card = setting.adviseCard ? 4 : 3; if (deckId == 999) { gotoSplashActivity(); } else new ThreadLoadImage(this, handler1, ConstantValue.getPathBackgroundByDeckId(this, deckId), null, 10).start(); break; case R.id.btn_select_one_card: // selected get one card number_of_card = 1; if (deckId == 999) { gotoSplashActivity(); } else new ThreadLoadImage(this, handler1, ConstantValue.getPathBackgroundByDeckId(this, deckId), null, 10).start(); break; default: break; } } private void gotoSplashActivity() { if (continueFlow) { intent = new Intent(this, SplashDeckBeanActivity.class); intent.putExtras(getIntent().getExtras()); intent.putExtra("number_of_card", number_of_card); startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); if (bitmapBackImage != null) { bitmapBackImage.recycle(); } this.finish(); } } /** * @param dec * DeckBean pass to InfoDeckActivity */ public void passDeck(DeckBean dec) { Intent intent = new Intent(this, InfoDeckActivity.class); intent.putExtras(getIntent().getExtras()); intent.putExtra("requestCode", requestcodeInfoDeck); startActivityForResult(intent, requestcodeInfoDeck); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == requestcodeInfoDeck && resultCode == RESULT_FIRST_USER) { this.finish(); } else { setting = ConstantValue.getSettingApp(this); flag = true; overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } } public static Bitmap bitmapBackImage = null; public void loadBitmapToCache() { String strDeckId = (deckId < 10) ? ("0" + deckId) : ("" + deckId); String path = ConstantValue.getPatchCardData(this) + "Card_" + strDeckId + "/en_c" + strDeckId + "d.png"; byte[] bytes = null; try { bytes = FileUtils.decryptToByteArray(path, ""); bitmapBackImage = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (bitmapBackImage != null) bitmapBackImage = FileUtils.createReflectedImage(bitmapBackImage); } Handler handler = new Handler(); class loadDataImageThread extends Thread { public void run() { handler.post(new Runnable() { @Override public void run() { loadBitmapToCache(); } }); } } private void clearCache() { if (deckId != 999) { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "s")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "p")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "m")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "d")); cache.removeFromMemory(ConstantValue.getPathBackgroundByDeckId( this, deckId)); } } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); backtoToppageActivity(); } void backtoToppageActivity() { clearCache(); Intent i = new Intent(this, TopPageActivity.class); startActivity(i); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } }
Java
package net.cardgame.orcalecard; import java.util.ArrayList; import java.util.HashMap; import jp.jma.oraclecard.R; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.XmlParserInfoApp; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; public class InfoAppActivity extends Activity implements OnClickListener, OnItemClickListener { // XML node keys private static final String KEY_ENTRY = "entry"; private static final String KEY_TITLE = "title"; private static final String KEY_LINK = "link"; private static final String KEY_SUMMARY = "summary"; private static final String KEY_POSTED = "posted"; private ArrayList<HashMap<String, String>> entrysList; private XmlParserInfoApp parser; private String xml = ""; private String url = ConstantValue.URL_XML_INFOAPP; private ListView listView; private Button btnBack; private ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.info_app_layout); btnBack = (Button) findViewById(R.id.btnBack); btnBack.setOnClickListener(this); if (NetworkUtils.isNetworkConnected(InfoAppActivity.this)) new LoadDataAsyncTask().execute(); else { showAlertDialog(InfoAppActivity.this, "No Internet Connection", "You don't have internet connection."); } } private class LoadDataAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { dialog = ProgressDialog.show(InfoAppActivity.this, "", "Loading..Wait..", true); dialog.show(); super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { processData(); return null; } @Override protected void onPostExecute(Void result) { dialog.dismiss(); listView = (ListView) findViewById(R.id.listView); AdapterInfoApp adapter = new AdapterInfoApp(InfoAppActivity.this, entrysList); listView.setAdapter(adapter); listView.setOnItemClickListener(InfoAppActivity.this); super.onPostExecute(result); } } public void processData() { entrysList = new ArrayList<HashMap<String, String>>(); parser = new XmlParserInfoApp(); xml = parser.getXmlFromUrl(url); if (xml != null) { xml = xml.substring(xml.indexOf("<entry>"), xml.length()); // Chen tag "<root>" va "</root>" vao dau va cuoi xml xml = "<root>" + xml + "</root>"; Document doc = parser.getDomElement(xml); NodeList nl = doc.getElementsByTagName(KEY_ENTRY); // looping through all song nodes <song> for (int i = 0; i < nl.getLength(); i++) { // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); Element e = (Element) nl.item(i); // adding each child node to HashMap key => value map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE)); map.put(KEY_LINK, parser.getValue(e, KEY_LINK)); map.put(KEY_SUMMARY, parser.getValue(e, KEY_SUMMARY)); map.put(KEY_POSTED, parser.getValue(e, KEY_POSTED)); // adding HashList to ArrayList entrysList.add(map); } } } @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { String url = entrysList.get(position).get(KEY_LINK); if (url != null && url != "") { Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(myIntent); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnBack: finish(); break; default: break; } } // Show dialog alert no internet connection public void showAlertDialog(Context context, String title, String message) { AlertDialog alertDialog = new AlertDialog.Builder(context).create(); // Setting Dialog Title alertDialog.setTitle(title); // Setting Dialog Message alertDialog.setMessage(message); // Setting alert dialog icon alertDialog.setIcon(R.drawable.fail_connect_internet); // Setting OK Button alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); // Showing Alert Message alertDialog.show(); } }
Java
package net.cardgame.orcalecard; import java.util.ArrayList; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.onDeleteNewsBeanListener; import net.cardgame.orcalecard.bean.NewsBean; import android.annotation.SuppressLint; import android.app.Activity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; class NewsBeanAdapter extends ArrayAdapter<NewsBean> implements OnTouchListener, OnClickListener { ArrayList<NewsBean> listNewsBean = new ArrayList<NewsBean>(); Activity context; boolean ontouch; int x_old; int selectedId = 0; onDeleteNewsBeanListener listener; public NewsBeanAdapter(Activity context, ArrayList<NewsBean> objects) { super(context, R.layout.item_listview_newsbean, objects); // TODO Auto-generated constructor stub listener = (onDeleteNewsBeanListener) context; this.listNewsBean = objects; this.context = context; } static class ViewHolder { TextView txtMemory; TextView txtDatetime; ImageView btnDelete; } public void addNewsBean(NewsBean newsbean) { listNewsBean.add(newsbean); this.notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.item_listview_newsbean, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.txtMemory = (TextView) rowView .findViewById(R.id.txtmemory_item_listnewsbean); viewHolder.txtDatetime = (TextView) rowView .findViewById(R.id.txtDatetime_edit_history); viewHolder.btnDelete = (ImageView) rowView .findViewById(R.id.btnDelete_edit_history); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); NewsBean newsbean = listNewsBean.get(position); holder.txtMemory.setText(newsbean.sumary); holder.txtDatetime.setText(newsbean.datetime); holder.btnDelete.setVisibility(View.INVISIBLE); rowView.setId(newsbean.id); rowView.setOnTouchListener(this); return rowView; } @Override public void onClick(View v) { // TODO Auto-generated method stub for (NewsBean newsBean : listNewsBean) { if (newsBean.id == selectedId) { // delete NewsBean listener.onDeleted(newsBean); listNewsBean.remove(newsBean); notifyDataSetChanged(); return; } } } @SuppressLint("ResourceAsColor") @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: x_old = (int) event.getRawX(); if (ontouch) { selectedId = 0; notifyDataSetChanged(); ontouch = false; return false; } break; case MotionEvent.ACTION_MOVE: int x = (int) event.getRawX(); if (Math.abs(x - x_old) > 5) { ontouch = true; ImageView btnDelete = (ImageView) v .findViewById(R.id.btnDelete_edit_history); btnDelete.setVisibility(View.VISIBLE); selectedId = v.getId(); btnDelete.setOnClickListener(this); ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f); anim.setDuration(500); btnDelete.startAnimation(anim); } break; case MotionEvent.ACTION_UP: break; default: break; } return true; } }
Java
package net.cardgame.orcalecard; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jp.jma.oraclecard.R; import net.cardgame.orcalecard.utils.FileUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.widget.ImageView; public class GalleryLoader { GalleryMemoryCache memoryCache = new GalleryMemoryCache(); GalleryFileCache fileCache; private Map<ImageView, String> imageViews = Collections .synchronizedMap(new WeakHashMap<ImageView, String>()); ExecutorService executorService; Handler handler = new Handler();// handler to display images in UI thread private Context mContext; // Ảnh phía sau đối với quân bài thông thường private Bitmap bmpNormalBehind; // Ảnh phía sau của quân bài special private Bitmap bmpSpecialBehind; private int bmpSpecialId = R.drawable.c999d; private boolean isSpecial; public GalleryLoader(Context context, boolean isSpecial) { this.mContext = context; this.isSpecial = isSpecial; fileCache = new GalleryFileCache(context); executorService = Executors.newFixedThreadPool(5); initBitmap(); } private void initBitmap() { bmpSpecialBehind = BitmapFactory.decodeResource( mContext.getResources(), bmpSpecialId); bmpSpecialBehind = Bitmap.createScaledBitmap(bmpSpecialBehind, 280, 400, true); bmpSpecialBehind = FileUtils.createReflectedImage(bmpSpecialBehind); bmpNormalBehind = CardDeckActivity.bitmapBackImage; } public void DisplayImage(String url, ImageView imageView) { imageViews.put(imageView, url); Bitmap bitmap = memoryCache.get(url); if (bitmap != null && !bitmap.isRecycled()) // if (bitmap != null) imageView.setImageBitmap(bitmap); else { // Neu bitmap ma null thi load ảnh phía sau quân bài queuePhoto(url, imageView); // Nếu là bộ deck bình thường if (!isSpecial) { if (bmpNormalBehind != null) { imageView.setImageBitmap(bmpNormalBehind); } } else { // nếu là deck Special if (bmpSpecialBehind != null) { imageView.setImageBitmap(bmpSpecialBehind); } } } } private void queuePhoto(String url, ImageView imageView) { PhotoToLoad p = new PhotoToLoad(url, imageView); executorService.submit(new PhotosLoader(p)); } private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from Cache Bitmap b = decodeFile(f); if (b != null) return b; // from SDCard try { Bitmap bitmap = null; byte[] bytes = FileUtils.decryptToByteArray(url, ""); InputStream is = new ByteArrayInputStream(bytes); OutputStream os = new FileOutputStream(f); FileUtils.CopyStream(is, os); is.close(); os.close(); bytes = null; bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } } // decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f) { try { // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream stream1 = new FileInputStream(f); BitmapFactory.decodeStream(stream1, null, o); stream1.close(); // Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = 100; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; FileInputStream stream2 = new FileInputStream(f); Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2); stream2.close(); return bitmap; } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } return null; } // Task for the queue private class PhotoToLoad { public String url; public ImageView imageView; public PhotoToLoad(String u, ImageView i) { url = u; imageView = i; } } class PhotosLoader implements Runnable { PhotoToLoad photoToLoad; PhotosLoader(PhotoToLoad photoToLoad) { this.photoToLoad = photoToLoad; } @Override public void run() { try { if (imageViewReused(photoToLoad)) return; Bitmap bmp = FileUtils .createReflectedImage(getBitmap(photoToLoad.url)); memoryCache.put(photoToLoad.url, bmp); if (imageViewReused(photoToLoad)) return; BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad); handler.post(bd); } catch (Throwable th) { th.printStackTrace(); } } } boolean imageViewReused(PhotoToLoad photoToLoad) { String tag = imageViews.get(photoToLoad.imageView); if (tag == null || !tag.equals(photoToLoad.url)) return true; return false; } // Used to display bitmap in the UI thread class BitmapDisplayer implements Runnable { Bitmap bitmap; PhotoToLoad photoToLoad; public BitmapDisplayer(Bitmap b, PhotoToLoad p) { bitmap = b; photoToLoad = p; } public void run() { if (imageViewReused(photoToLoad)) return; if (bitmap != null) photoToLoad.imageView.setImageBitmap(bitmap); else { if (!isSpecial) { if (bmpNormalBehind != null) { photoToLoad.imageView.setImageBitmap(bmpNormalBehind); } } else { if (bmpSpecialBehind != null) { photoToLoad.imageView.setImageBitmap(bmpSpecialBehind); } } } } } public void clearCache() { memoryCache.clear(); fileCache.clear(); } }
Java
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import java.util.Random; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.oraclecard.service.DownloadUnzipObject; import net.cardgame.oraclecard.service.ServiceDownload; import net.cardgame.oraclecard.service.ServiceDownloadListener; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.Sort; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * Top Page Screen */ public class TopPageActivity extends Activity implements OnClickListener, OnItemClickListener, ServiceDownloadListener { private static final int HELP_REQUESTCODE = 0; private static final int RANDOM_REQUESTCODE = 1; private static final int INFO_DECK_REQUESTCODE = 2; private static final int SETTING_REQUESTCODE = 3; private static final int HISTORY_REQUESTCODE = 4; GridView gridView; Intent _i; boolean cancel; ArrayList<DeckBean> listDeckBean; GridViewAdapter adapter; int selectedPosition = 1000; SettingApp setting; SecurePreferences appPreferences; boolean flag = true; private ProgressDialog pDialog; // public final static String KEY_TOPPAGE = "toppage"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.top_activity_layout); gridView = (GridView) findViewById(R.id.grid_view_flash); findViewById(R.id.icon_help_top).setOnClickListener(this); findViewById(R.id.btn_home_toppage).setOnClickListener(this); findViewById(R.id.btn_history_toppage).setOnClickListener(this); findViewById(R.id.btn_setting_toppage).setOnClickListener(this); // init shared reference appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); getStatus(); loadSettingApp(); adapter = new GridViewAdapter(this, listDeckBean); adapter.registryBroadcast(); gridView.setAdapter(adapter); gridView.setOnItemClickListener(this); if (NetworkUtils.isNetworkConnected(this) && getIntent().getExtras() != null) { handlerLoadImage.postDelayed(resumeDownload, 1000); // resumeDownload(); } } Runnable resumeDownload = new Runnable() { @Override public void run() { // TODO Auto-generated method stub resumeDownload(); } }; void getStatus() { Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); listDeckBean = gson.fromJson(listSaved, listOfDeckBean); } private void startDownloadService(DeckBean deckBean, int position) { String id = deckBean.deckId < 10 ? "0" + deckBean.deckId : "" + deckBean.deckId; Intent intentService = new Intent(this, ServiceDownload.class); intentService.putExtra(ServiceDownload.KEY_DECK_ID, deckBean.deckId); intentService.putExtra(ServiceDownload.KEY_PATH_SERVER, deckBean.pathServerDownload + ".zip"); intentService.putExtra(ServiceDownload.KEY_POSITION, position); intentService.putExtra(ServiceDownload.KEY_PATH_SAVE, ConstantValue.getPatchCardData(this) + "Card_" + id + ".zip"); startService(intentService); } void resumeDownload() { int i = 0; for (DeckBean deckBean : listDeckBean) { if (deckBean.percentDownloaded >= 0 && deckBean.percentDownloaded < 100) { adapter.setPercentDownloaded(i, deckBean.percentDownloaded); startDownloadService(deckBean, i); showDialogDownload(); return; } i++; } } void loadSettingApp() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); setting = gson.fromJson(strSetting, SettingAppType); } switch (setting.sortToppage) { case SettingApp.SORT_BY_BUY: listDeckBean = Sort.sortByBuy(listDeckBean); break; case SettingApp.SORT_BY_RELEASE: listDeckBean = Sort.sortByRelease(listDeckBean); break; case SettingApp.SORT_BY_USED: listDeckBean = Sort.sortByLastUsed(listDeckBean); break; default: break; } } /** * goto InfoDeck activity * * @param dec */ public void passDeck(DeckBean dec) { if (dec.deckId == 999 || dec.deckId == 998 || appPreferences.containsKey("content_" + dec.deckId) || NetworkUtils.isNetworkConnected(this)) { Intent i = new Intent(this, InfoDeckActivity.class); i.putExtra("deckId", dec.deckId); i.putExtra("deckName", dec.deckName); i.putExtra("deckPrice", dec.deckPrice); i.putExtra("deckPathServer", dec.pathServerDownload); i.putExtra("position", selectedPosition); i.putExtra("isUnlock", dec.isUnlock); i.putExtra("isFree", dec.isFree); i.putExtra("inAppPurchaseId", dec.inAppPurchaseId); i.putExtra("releaseDate", dec.releaseDate.getTime()); startActivityForResult(i, INFO_DECK_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } else { flag = true; showDialogSetting(); } } public void passDeckToCardDeckActivity(DeckBean dec) { _i = new Intent(this, CardDeckActivity.class); _i.putExtra("deckId", dec.deckId); _i.putExtra("deckName", dec.deckName); _i.putExtra("deckPrice", dec.deckPrice); _i.putExtra("deckPathServer", dec.pathServerDownload); _i.putExtra("position", selectedPosition); _i.putExtra("isUnlock", dec.isUnlock); _i.putExtra("cardTotal", dec.cardNumber); if (dec.deckId == 999) { startActivity(_i); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); this.finish(); return; } String tt = dec.deckId < 10 ? "0" + dec.deckId : "" + dec.deckId; new ThreadLoadImage(this, handlerLoadImage, ConstantValue.getPatchCardData(this) + "Card_" + tt + "/en_c" + tt + "t.png", null, 1).start(); } private Handler handlerLoadImage = new Handler() { public void handleMessage(Message msg) { startActivity(_i); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); TopPageActivity.this.finish(); }; }; public void passHelpType(int iType) { Intent i = new Intent(this, HelpActivity.class); i.putExtra("indexTypeHelp", iType); startActivityForResult(i, HELP_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } /* * Receive result from another activity */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); switch (requestCode) { case HISTORY_REQUESTCODE: break; case HELP_REQUESTCODE: break; case SETTING_REQUESTCODE: if (resultCode == RESULT_OK) { getStatus(); adapter.updateStatus(listDeckBean); } break; case INFO_DECK_REQUESTCODE: if (resultCode == RESULT_OK) { int positionDownload = data.getExtras().getInt("position"); if (data.getExtras().containsKey("isUnlock")) { Utils.ELog("unlock deckbeans", "ok"); boolean isUnlock = data.getExtras().getBoolean("isUnlock"); listDeckBean.get(positionDownload).isUnlock = isUnlock; adapter.updateStatus(listDeckBean); saveStatus(); } else { Utils.ELog("unlock deckbeans", "no"); if (!listDeckBean.get(positionDownload).isFree) { listDeckBean.get(positionDownload).isUnlock = true; } listDeckBean.get(positionDownload).percentDownloaded = 0; listDeckBean.get(positionDownload).buyDate = new Date(); adapter.setPercentDownloaded(positionDownload, 0); adapter.unlockDeckBean(positionDownload); saveStatus(); showDialogDownload(); } } break; default: break; } } @Override protected void onDestroy() { // TODO Auto-generated method stub adapter.unRegistryBroadcast(); super.onDestroy(); } @Override public void onClick(View v) { // TODO Auto-generated method stub if (!flag) return; switch (v.getId()) { case R.id.icon_help_top: passHelpType(0); flag = false; break; case R.id.btn_home_toppage: backtoMainActivity(); break; case R.id.btn_setting_toppage: Intent intent2 = new Intent(this, SettingActiviy.class); startActivityForResult(intent2, SETTING_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); flag = false; break; case R.id.btn_history_toppage: Intent intent = new Intent(this, HistoryActivity.class); startActivityForResult(intent, HISTORY_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); flag = false; break; default: break; } } /** * Save status downloading DeckBean */ private void saveStatus() { SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String save = gson.toJson(listDeckBean, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) { // TODO Auto-generated method stub if (flag == false) return; flag = false; selectedPosition = position; DeckBean deckBean; try { deckBean = listDeckBean.get(position); } catch (Exception ex) { flag = true; return; } switch (deckBean.deckId) { // case Special Deck case 999: if (deckBean.isUnlock) { if (setting.listSpecial == null || setting.listSpecial.isEmpty()) { // goto setting special deck startActivityForResult(new Intent(this, SettingSpecialActivity.class), SETTING_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } else { listDeckBean.get(position).lastUsedDate = new Date(); saveStatus(); passDeckToCardDeckActivity(deckBean);// goto card deck } // activity } else passDeck(deckBean); // go to info deck activity return; // case Random Deck case 998: if (deckBean.isUnlock) { // goto random card deck listDeckBean.get(position).lastUsedDate = new Date(); saveStatus(); // gotoRandomDeck(); } else { // go to info deck passDeck(deckBean); } return; default: if (deckBean.percentDownloaded == -2) { listDeckBean.get(position).lastUsedDate = new Date(); saveStatus(); passDeckToCardDeckActivity(deckBean); } else passDeck(deckBean); break; } } void gotoRandomDeck() { ArrayList<DeckBean> list = new ArrayList<DeckBean>(); for (DeckBean deck : listDeckBean) { if (deck.percentDownloaded == -2 || deck.deckId == 999) list.add(deck); } int size = list.size(); Random random = new Random(); DeckBean deckBean = list.get(random.nextInt(size)); Intent intent = new Intent(this, RandomActivity.class); intent.putExtra("deckId", deckBean.deckId); intent.putExtra("deckName", deckBean.deckName); intent.putExtra("deckPrice", deckBean.deckPrice); intent.putExtra("deckPathServer", deckBean.pathServerDownload); intent.putExtra("position", selectedPosition); intent.putExtra("isUnlock", deckBean.isUnlock); intent.putExtra("cardTotal", deckBean.cardNumber); startActivityForResult(intent, RANDOM_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); this.finish(); } @Override protected void onPrepareDialog(int id, Dialog dialog) { // TODO Auto-generated method stub super.onPrepareDialog(id, dialog); } void showDialogDownloadError() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); String title = getResources().getString(R.string.download_error); String message = getResources().getString(R.string.message_redownload); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.show(); } void showDialogSetting() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); String title = getResources().getString( R.string.dialog_errornetwork_title); String message = getResources().getString( R.string.dialog_errornetwork_message); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); } }); builder.show(); } void backtoMainActivity() { Intent i = new Intent(this, MainActivity.class); startActivity(i); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); getStatus(); flag = true; // Load new setting setting = ConstantValue.getSettingApp(this); listDeckBean = adapter.sortDeckBean(setting.sortToppage); } @Override public void onUpdateProgressListener(int percent, int position, int deckId) { // TODO Auto-generated method stub if (pDialog == null || !pDialog.isShowing()) showDialogDownload(); pDialog.setProgress(percent); } @Override public void onDownloadFailListener(DownloadUnzipObject object, String message) { // TODO Auto-generated method stub if (pDialog != null && pDialog.isShowing()) pDialog.dismiss(); if (message != null && message != "") { showDialog(message); return; } if (!NetworkUtils.isNetworkConnected(this)) { showDialogSetting(); } } private void showDialog(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.show(); } @Override public void onFinishedListener(DownloadUnzipObject object) { // TODO Auto-generated method stub getStatus(); if (pDialog != null && pDialog.isShowing()) pDialog.dismiss(); if (adapter != null) adapter.updateStatus(listDeckBean); } private void stopDownload() { Intent intentService = new Intent(this, ServiceDownload.class); intentService.putExtra("cancel", true); startService(intentService); } void showDialogDownload() { pDialog = new ProgressDialog(this); String message = getResources().getString(R.string.downloading_message); String button_cancle = getResources().getString( R.string.btn_cancle_download); pDialog.setMessage(message); pDialog.setIndeterminate(false); pDialog.setMax(100); pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pDialog.setCancelable(false); pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, button_cancle, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); stopDownload(); } }); pDialog.setProgress(0); pDialog.show(); } }
Java
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.billingutils.IabHelper; import net.cardgame.oraclecard.billingutils.IabResult; import net.cardgame.oraclecard.billingutils.Inventory; import net.cardgame.oraclecard.billingutils.Purchase; import net.cardgame.oraclecard.common.MySwitch; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class SettingActiviy extends Activity implements OnClickListener, OnCheckedChangeListener { SettingApp setting; SecurePreferences appPreferences; ArrayList<DeckBean> listDeckBean; LinearLayout wait_layout; // / BILLING static final String BILLING_TAG = "DECK BILLING"; static final int PURCHASE_REQUEST = 10001; // The helper object IabHelper mHelper; // public key in developer console String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; boolean isBillingSupport = false; boolean isWait = false; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.setting_app_layout); appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); getStatus(); loadSettingApp(); MySwitch switchJumpCard = (MySwitch) findViewById(R.id.switchJumcard); MySwitch switchAdvise = (MySwitch) findViewById(R.id.switchAdviseCard); MySwitch switchSound = (MySwitch) findViewById(R.id.switchSound); switchJumpCard.setOnCheckedChangeListener(this); switchAdvise.setOnCheckedChangeListener(this); switchSound.setOnCheckedChangeListener(this); switchJumpCard.setChecked(setting.jumCard); switchAdvise.setChecked(setting.adviseCard); switchSound.setChecked(setting.sound); findViewById(R.id.btn_help_setting).setOnClickListener(this); findViewById(R.id.btn_back_setting).setOnClickListener(this); findViewById(R.id.layout_confirm_restore).setOnClickListener(this); findViewById(R.id.layout_sortTop).setOnClickListener(this); findViewById(R.id.layout_special).setOnClickListener(this); wait_layout = (LinearLayout) findViewById(R.id.layout_wait_restore); // / INIT BILLING base64EncodedPublicKey = this.getResources().getString( R.string.app_public_key); // Create the helper, passing it our context and the public key to // verify signatures with Utils.ELog(BILLING_TAG, "Creating IAB helper."); mHelper = new IabHelper(this, base64EncodedPublicKey); // enable debug logging (for a production application, you should set // this to false). mHelper.enableDebugLogging(true); } void getStatus() { // get config app string Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); listDeckBean = gson.fromJson(listSaved, listOfDeckBean); } void loadSettingApp() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); // Utils.ELog("str_History", strHistory); setting = gson.fromJson(strSetting, SettingAppType); } } /** * Save status DeckBean */ private void saveStatus() { SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String save = gson.toJson(listDeckBean, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); } @Override public void onClick(View v) { // TODO Auto-generated method stub if (isWait) { return; } switch (v.getId()) { case R.id.btn_help_setting: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 3); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_back_setting: this.finish(); break; case R.id.layout_confirm_restore: dialogRestore(); break; case R.id.layout_sortTop: Intent intentSort = new Intent(this, SettingSortActivity.class); intentSort.putExtra("sort_by", setting.sortToppage); startActivityForResult(intentSort, 1); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.layout_special: startActivityForResult(new Intent(this, SettingSpecialActivity.class), 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; default: break; } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub switch (buttonView.getId()) { case R.id.switchJumcard: setting.jumCard = isChecked; saveSetting(); break; case R.id.switchAdviseCard: setting.adviseCard = isChecked; saveSetting(); break; case R.id.switchSound: setting.sound = isChecked; saveSetting(); break; default: break; } } void saveSetting() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); String save = gson.toJson(setting, SettingAppType); appPreferences.put(ConstantValue.SETTING_KEY, save); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); if (requestCode == 1) { setting.sortToppage = resultCode; saveSetting(); } } private void dialogRestore() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle("hỏi thoát chương trình"); String message = getResources().getString( R.string.dialog_restore_message); builder.setMessage(message); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { billingRestore(); // finish(); } }); builder.setCancelable(false); builder.create().show(); } private void billingRestore() { setWaitScreen(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. Utils.ELog(BILLING_TAG, "Starting setup."); if (!isBillingSupport) { mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Utils.ELog(BILLING_TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. Utils.ELog(BILLING_TAG, "Problem setting up in-app billing: " + result); setWaitScreen(false); return; } // Hooray, IAB is fully set up. Now, let's get an inventory // of // stuff we own. Utils.ELog(BILLING_TAG, "Setup successful. Querying inventory."); isBillingSupport = true; mHelper.queryInventoryAsync(mGotInventoryListener); } }); } else { Utils.ELog(BILLING_TAG, "billing support. Querying inventory."); mHelper.queryInventoryAsync(mGotInventoryListener); } } // Listener that's called when we finish querying the items and // subscriptions we own // Lấy thông tin các item mà user đã mua (sở hữu) IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Utils.ELog(BILLING_TAG, "Query inventory finished."); if (result.isFailure()) { Utils.ELog(BILLING_TAG, "Failed to query inventory: " + result); setWaitScreen(false); return; } Utils.ELog(BILLING_TAG, "Query inventory was successful."); Utils.ELog(BILLING_TAG, "Query inventory info: " + inventory.toString()); for (int i = 0; i < listDeckBean.size(); i++) { Purchase testPurchase = inventory.getPurchase(listDeckBean .get(i).inAppPurchaseId); Utils.ELog(BILLING_TAG, "item inventory info: " + listDeckBean.get(i).inAppPurchaseId); if (testPurchase != null && verifyDeveloperPayload(testPurchase)) { Utils.ELog(BILLING_TAG, " deck already bought id: " + listDeckBean.get(i).inAppPurchaseId); listDeckBean.get(i).isUnlock = true; Date purchaseDate = new Date(testPurchase.getPurchaseTime()); listDeckBean.get(i).buyDate = purchaseDate; } } saveStatus(); setWaitScreen(false); setResult(RESULT_OK); } }; /** Verifies the developer payload of a purchase. */ // Xác thực đoạn pay load trả về boolean verifyDeveloperPayload(Purchase p) { String payloadReturn = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. * It will be the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase * and verifying it here might seem like a good approach, but this will * fail in the case where the user purchases an item on one device and * then uses your app on a different device, because on the other device * you will not have access to the random string you originally * generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different * between them, so that one user's purchase can't be replayed to * another user. * * 2. The payload must be such that you can verify it even when the app * wasn't the one who initiated the purchase flow (so that items * purchased by the user on one device work on other devices owned by * the user). * * Using your own server to store and verify developer payloads across * app installations is recommended. */ return true; } // Tắt/Bật màn hình chờ void setWaitScreen(boolean set) { wait_layout.setVisibility(set ? View.VISIBLE : View.GONE); isWait = set ? true : false; } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); // very important: Utils.ELog(BILLING_TAG, "Destroying helper."); if (mHelper != null) mHelper.dispose(); mHelper = null; } }
Java
package net.cardgame.orcalecard; import java.io.File; import java.lang.reflect.Type; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.service.ServiceUpdateFileConfig; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * Màn hình Splash khi khởi động app */ public class SplashActivity extends Activity { private static String TAG = SplashActivity.class.getName(); private static long SLEEP_TIME = 2000; // Sleep for some time /** * The thread to process splash screen events */ private Thread mSplashThread; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_layout); startService(new Intent(this, ServiceUpdateFileConfig.class)); // The thread to wait for splash screen events mSplashThread = new Thread() { @Override public void run() { try { synchronized (this) { // Wait given period of time or exit on touch wait(SLEEP_TIME); } } catch (InterruptedException ex) { } handler.sendMessage(handler.obtainMessage()); } }; mSplashThread.start(); createAppFolder(); loadSettingApp(); } void loadSettingApp() { SettingApp setting = new SettingApp(); setting.setDefault(); Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (!appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String save = gson.toJson(setting, SettingAppType); appPreferences.put(ConstantValue.SETTING_KEY, save); } } Handler handler = new Handler() { public void handleMessage(Message msg) { Intent intent = new Intent(SplashActivity.this, MainActivity.class); startActivity(intent); finish(); }; }; private void createAppFolder() { File file = new File(ConstantValue.getBasePatchApp(this)); if (!file.exists()) file.mkdirs(); } /** * Processes splash screen touch events */ @Override public boolean onTouchEvent(MotionEvent evt) { if (evt.getAction() == MotionEvent.ACTION_DOWN) { synchronized (mSplashThread) { mSplashThread.notifyAll(); } } return true; } }
Java
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.CustomAnimationListener; import net.cardgame.oraclecard.common.CustomImageView; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.KeyboardHelper; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.SoundPool; import android.media.SoundPool.OnLoadCompleteListener; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.TranslateAnimation; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.nineoldandroids.animation.ObjectAnimator; public class GetCardActivity extends Activity implements OnClickListener, OnTouchListener, CustomAnimationListener { final static int JUMCARD_STATE = 5, GETCARD_STATE = 4, DEFAULT_STATE = 0; ImageView img_Jump, img_bg, img_number_getcard, card0; CustomImageView card1, card2, card3, img_ef_ring_getcard; RelativeLayout.LayoutParams paramsFront, paramsBehind, paramsCard3; ViewGroup parent; int deckId, numcards, numberOfCard, state_machine = 0, y_old = 0, x_old = 0, _yDelta, state, top_margin; SettingApp setting; boolean flag = true; final int DURATION = 700; SoundPool soundPool; int height_getcard; CardBean cardBean1, cardBean2, cardBean3, cardBean4; int cardTotal = 0; HashMap<Integer, Integer> mapCardNumber = new HashMap<Integer, Integer>(); int sound_getcard, sound_jumcard, sound_getcard1, sound_getcard2; boolean loaded = false; float volume; Bitmap mBitmapTemp; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.get_card_activity); height_getcard = getResources().getInteger(R.integer.height_getcard); parent = (ViewGroup) findViewById(R.id.card_parent); setupUI((ViewGroup) findViewById(R.id.parent)); state_machine = DEFAULT_STATE; Bundle bundle = getIntent().getExtras(); deckId = bundle.getInt("deckId"); numberOfCard = bundle.getInt("number_of_card"); if (bundle.containsKey("cardTotal")) { cardTotal = bundle.getInt("cardTotal"); } numcards = numberOfCard; setting = ConstantValue.getSettingApp(this); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub loadCardBean(); } }).start(); initView(); loadImage(); loadMedia(); } void initView() { findViewById(R.id.btnBack_getcard).setOnClickListener(this); findViewById(R.id.txtquestion_getcard).clearFocus(); img_number_getcard = (ImageView) findViewById(R.id.img_number_getcard); ImageView btnHelp = (ImageView) findViewById(R.id.btnhelp_getcard); btnHelp.setOnClickListener(this); img_ef_ring_getcard = (CustomImageView) findViewById(R.id.img_ef_ring_getcard); img_ef_ring_getcard.registryListener(this); card1 = (CustomImageView) findViewById(R.id.card1_getcard); card2 = (CustomImageView) findViewById(R.id.card2_getcard); card3 = (CustomImageView) findViewById(R.id.card3_getcard); card3.registryListener(this); card1.registryListener(this); card2.registryListener(this); card0 = (ImageView) findViewById(R.id.card0_getcard); img_Jump = (ImageView) findViewById(R.id.img_jumpcard_getcard); img_bg = (ImageView) findViewById(R.id.img_bg_getcard); paramsFront = (RelativeLayout.LayoutParams) card2.getLayoutParams(); paramsBehind = (RelativeLayout.LayoutParams) card1.getLayoutParams(); paramsCard3 = (LayoutParams) card3.getLayoutParams(); top_margin = paramsCard3.topMargin; card3.setOnTouchListener(this); } /** * Setting CardBean1,2,3,4 */ void loadCardBean() { // create card bean cardBean1 = new CardBean(); cardBean2 = new CardBean(); cardBean3 = new CardBean(); cardBean4 = new CardBean(); if (deckId == 999) { ranDomCardSpecialDeck(); } else { cardBean4.deckId = cardBean3.deckId = cardBean2.deckId = cardBean1.deckId = deckId; // Set random cardId if (cardTotal == 0) cardTotal = 44; Random random1 = new Random(); cardBean1.cardId = random1.nextInt(cardTotal - 1) + 1; do { Random random = new Random(); cardBean2.cardId = random.nextInt(cardTotal - 1) + 1; } while (cardBean2.cardId == cardBean1.cardId); do { Random random = new Random(); cardBean3.cardId = random.nextInt(cardTotal - 1) + 1; } while (cardBean3.cardId == cardBean1.cardId || cardBean3.cardId == cardBean2.cardId); do { Random random = new Random(); cardBean4.cardId = random.nextInt(cardTotal - 1) + 1; } while (cardBean4.cardId == cardBean1.cardId || cardBean4.cardId == cardBean2.cardId || cardBean4.cardId == cardBean3.cardId); } // Utils.ELog("CardBean1", cardBean1.toString()); // Utils.ELog("CardBean2", cardBean2.toString()); // Utils.ELog("CardBean3", cardBean3.toString()); // Utils.ELog("CardBean4", cardBean4.toString()); } private void ranDomCardSpecialDeck() { SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); ArrayList<DeckBean> listDeckBean = gson.fromJson(listSaved, listOfDeckBean); for (int decId : setting.listSpecial) { for (DeckBean deckBean : listDeckBean) { if (decId == deckBean.deckId) { mapCardNumber.put(decId, deckBean.cardNumber); break; } } } cardBean1 = randomCardBean(); cardBean2 = randomCardBean(); cardBean3 = randomCardBean(); cardBean4 = randomCardBean(); mapCardNumber.clear(); } private CardBean randomCardBean() { CardBean cardBean = new CardBean(); int size, index, cardNumber; size = setting.listSpecial.size(); do { Random random = new Random(); index = random.nextInt(size); cardBean.deckId = setting.listSpecial.get(index); cardNumber = mapCardNumber.get(cardBean.deckId); cardBean.cardId = random.nextInt(cardNumber - 1) + 1; } while ((cardBean.deckId == cardBean1.deckId && cardBean.cardId == cardBean1.cardId) || (cardBean.deckId == cardBean2.deckId && cardBean.cardId == cardBean2.cardId) || (cardBean.deckId == cardBean3.deckId && cardBean.cardId == cardBean3.cardId) || (cardBean.deckId == cardBean4.deckId && cardBean.cardId == cardBean4.cardId)); return cardBean; } void getVolume() { // Getting the user sound settings AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); float actualVolume = (float) audioManager .getStreamVolume(AudioManager.STREAM_MUSIC); float maxVolume = (float) audioManager .getStreamMaxVolume(AudioManager.STREAM_MUSIC); volume = actualVolume / maxVolume; } void playSound(int soundId) { getVolume(); if (setting.sound) { soundPool.play(soundId, volume, volume, 1, 0, 1f); } } void loadMedia() { this.setVolumeControlStream(AudioManager.STREAM_MUSIC); soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { loaded = true; } }); sound_getcard = soundPool.load(this, R.raw.se_draw_card, 1); sound_jumcard = soundPool.load(this, R.raw.se_jump_card, 1); sound_getcard1 = soundPool.load(this, R.raw.get_card_001, 1); sound_getcard2 = soundPool.load(this, R.raw.get_card_002, 1); } /** * // * Set encrypt image from SD card to Image View */ private void loadImage() { notifyCardNumber(); if (deckId == 999) { img_bg.setImageResource(R.drawable.bg999); card1.setImageResource(R.drawable.c999s); card0.setImageResource(R.drawable.c999s); card2.setImageResource(R.drawable.c999s); mBitmapTemp = BitmapFactory.decodeResource(getResources(), R.drawable.c999d); img_Jump.setImageResource(R.drawable.c999j); return; } new ThreadLoadImage(this, mHandler, ConstantValue.getPathBackgroundByDeckId(this, deckId), img_bg, 1).start(); new ThreadLoadImage(this, mHandler, ConstantValue.getPathDeckImage( this, deckId, "s"), card1, 2).start(); new ThreadLoadImage(this, mHandler, ConstantValue.getPathDeckImage( this, deckId, "d"), card3, 3).start(); new ThreadLoadImage(this, mHandler, ConstantValue.getPathDeckImage( this, deckId, "j"), img_Jump, 4).start(); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: img_bg.setImageDrawable((Drawable) msg.obj); break; case 2: card0.setImageDrawable((Drawable) msg.obj); card1.setImageDrawable((Drawable) msg.obj); card2.setImageDrawable((Drawable) msg.obj); break; case 3: BitmapDrawable drawable = (BitmapDrawable) msg.obj; if (drawable != null) { mBitmapTemp = drawable.getBitmap(); } break; case 4: img_Jump.setImageDrawable((Drawable) msg.obj); break; case 5: img_Jump.setVisibility(View.INVISIBLE); break; case 6: ringGetCardAnimation(); break; case 10: ImageView imageview = (ImageView) msg.obj; if (imageview != null && paramsBehind != null) { imageview.setLayoutParams(paramsBehind); if (imageview.getId() == R.id.card1_getcard) { card2.setLayoutParams(paramsFront); parent.bringChildToFront(card2); } else { card1.setLayoutParams(paramsFront); parent.bringChildToFront(card1); } } default: break; } }; }; /** * Change number of cards haven't gotten */ private void notifyCardNumber() { if (numberOfCard <= 0) { img_number_getcard.setImageResource(R.drawable.draw_this); } else switch (numberOfCard) { case 1: img_number_getcard.setImageResource(R.drawable.draw_1); break; case 2: img_number_getcard.setImageResource(R.drawable.draw_2); break; case 3: img_number_getcard.setImageResource(R.drawable.draw_3); break; case 4: img_number_getcard.setImageResource(R.drawable.draw_4); break; default: break; } } Runnable mRunableSleep = new Runnable() { @Override public void run() { // TODO Auto-generated method stub mHandler.sendEmptyMessage(6); } }; class ThreadCardCut extends Thread { ImageView imageView; public ThreadCardCut(ImageView imageview) { imageView = imageview; }; @Override public void run() { // TODO Auto-generated method stub super.run(); try { Thread.sleep(DURATION / 2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Message msg = mHandler.obtainMessage(10); msg.obj = imageView; mHandler.sendMessage(msg); } } private void putListJump() { // for (int i = 0; i < 4; i++) { // if (listJumcard[i] == 0) { // listJumcard[i] = numcards - numberOfCard; // break; // } // } int card = numcards - numberOfCard; switch (card) { case 1: cardBean1.isJump = true; break; case 2: cardBean2.isJump = true; break; case 3: cardBean3.isJump = true; break; case 4: cardBean4.isJump = true; break; default: break; } } public void CustomOnclick(View v) { if (numberOfCard <= 0) { return; } ringCutCardAnimation(); if (setting.jumCard) { Random random = new Random(); int i = random.nextInt(20); if (i == 5) { // Jump card numberOfCard--; putListJump(); state_machine = JUMCARD_STATE; playSound(sound_jumcard); if (mBitmapTemp != null && !mBitmapTemp.isRecycled()) { card3.setImageBitmap(mBitmapTemp); Animation jump_animation = AnimationUtils.loadAnimation( this, R.anim.jumcard_animation); card3.startAnimation(jump_animation); card3.registryListener(this); img_Jump.setVisibility(View.VISIBLE); } defaultSetupCard(); notifyCardNumber(); if (numberOfCard <= 0) { gotoResultActivity(); } Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub mHandler.sendEmptyMessage(5); } }, 1500); return; } else { // Flip card playSound(sound_getcard1); } } else playSound(sound_getcard1); card3.setImageDrawable(null); ((CustomImageView) v).registryListener(this); new ThreadCardCut((ImageView) v).start(); ObjectAnimator.ofFloat(v, "translationY", 0, -height_getcard, 0) .setDuration(DURATION).start(); } @Override public void onClick(View view) { // TODO Auto-generated method stub if (!flag) return; switch (view.getId()) { case R.id.btnBack_getcard: goBack(); break; case R.id.btnhelp_getcard: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 9); startActivityForResult(intent, 6); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; default: break; } } private void ringCutCardAnimation() { Animation ef_ring = AnimationUtils.loadAnimation(this, R.anim.ring_cutcard_animation); img_ef_ring_getcard.setImageResource(R.drawable.ef_ring); img_ef_ring_getcard.startAnimation(ef_ring); } private void ringGetCardAnimation() { Animation ef_ring = AnimationUtils.loadAnimation(this, R.anim.ring_getcard_animation); img_ef_ring_getcard.setImageResource(R.drawable.ef_ring); img_ef_ring_getcard.startAnimation(ef_ring); } void defaultSetupCard() { state = 2; card2.setLayoutParams(paramsFront); card1.setLayoutParams(paramsBehind); parent.bringChildToFront(card2); } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (numberOfCard <= 0) return false; final int Y = (int) event.getRawY(); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: KeyboardHelper.hideSoftKeyboard(this); findViewById(R.id.txtquestion_getcard).clearFocus(); RelativeLayout.LayoutParams lParams2 = (RelativeLayout.LayoutParams) v .getLayoutParams(); _yDelta = Y - lParams2.topMargin; y_old = Y; x_old = (int) event.getRawX(); break; case MotionEvent.ACTION_UP: notifyCardNumber(); int x = (int) event.getRawX(); if (Math.abs(Y - y_old) < 10 && Math.abs(x - x_old) < 10) { if (state == 1) { state = 2; CustomOnclick(card1); } else { state = 1; CustomOnclick(card2); } } else { v.setLayoutParams(paramsCard3); int s = Y - y_old; int speed = 50; int t = Math.abs(100 * s / speed); TranslateAnimation animation = new TranslateAnimation(0, 0, 0, -s); animation.setDuration(t); card3.startAnimation(animation); } if (y_old - Y >= paramsCard3.height / 2) {// perform get Card if (numberOfCard <= 0) return true; numberOfCard--; if (numberOfCard <= 0) { gotoResultActivity(); } notifyCardNumber(); Animation getcard_animation = AnimationUtils.loadAnimation( this, R.anim.getcard_animation); card3.startAnimation(getcard_animation); mHandler.postDelayed(mRunableSleep, 150); state_machine = GETCARD_STATE; playSound(sound_getcard); } break; case MotionEvent.ACTION_MOVE: if (mBitmapTemp != null && !mBitmapTemp.isRecycled() && card3.getDrawable() == null) { card3.setImageBitmap(mBitmapTemp); } RelativeLayout.LayoutParams layoutParams = (LayoutParams) v .getLayoutParams(); layoutParams.topMargin = Y - _yDelta; layoutParams.leftMargin = -250; layoutParams.rightMargin = -250; layoutParams.bottomMargin = -250; v.setLayoutParams(layoutParams); if (y_old - Y >= paramsCard3.height / 2) { img_number_getcard.setImageResource(R.drawable.draw_this); } else { notifyCardNumber(); } break; default: break; } return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { flag = true; overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } public void setupUI(View view) { // Set up touch listener for non-text box views to hide keyboard. if (!(view instanceof EditText)) { view.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { v.requestFocus(); KeyboardHelper.hideSoftKeyboard(GetCardActivity.this); return false; } }); } // If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView); } } } void gotoResultActivity() { EditText textInput = (EditText) findViewById(R.id.txtquestion_getcard); final String text = textInput.getText().toString(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub Intent intent = new Intent(GetCardActivity.this, ResultActivity.class); Bundle bundle = getIntent().getExtras(); intent.putExtra("cardBean1", cardBean1); intent.putExtra("cardBean2", cardBean2); intent.putExtra("cardBean3", cardBean3); intent.putExtra("cardBean4", cardBean4); bundle.putString("text_input", text); intent.putExtras(bundle); startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); GetCardActivity.this.finish(); } }, 1000); } @Override public synchronized void onEndAnimation(ImageView imageview) { // TODO Auto-generated method stub if (imageview.getId() == R.id.img_ef_ring_getcard) { imageview.setImageDrawable(null); return; } if (imageview.getId() == R.id.card1_getcard || imageview.getId() == R.id.card2_getcard) { playSound(sound_getcard2); } switch (state_machine) { case JUMCARD_STATE: imageview.setImageDrawable(null); state_machine = DEFAULT_STATE; img_Jump.setVisibility(View.INVISIBLE); notifyCardNumber(); break; case DEFAULT_STATE: if (imageview.getId() == R.id.card3_getcard) { imageview.setImageDrawable(null); RelativeLayout.LayoutParams layoutParams = (LayoutParams) imageview .getLayoutParams(); layoutParams.topMargin = top_margin; layoutParams.leftMargin = -250; layoutParams.rightMargin = -250; layoutParams.bottomMargin = -250; imageview.setLayoutParams(layoutParams); return; } imageview.setLayoutParams(paramsBehind); break; case GETCARD_STATE: state_machine = DEFAULT_STATE; if (imageview.getId() == R.id.card3_getcard) { imageview.setImageDrawable(null); RelativeLayout.LayoutParams layoutParams = (LayoutParams) imageview .getLayoutParams(); layoutParams.topMargin = top_margin; layoutParams.leftMargin = -250; layoutParams.rightMargin = -250; layoutParams.bottomMargin = -250; imageview.setLayoutParams(layoutParams); imageview.setImageDrawable(null); // ringGetCardAnimation(); return; } break; default: break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { goBack(); return true; } return super.onKeyDown(keyCode, event); } private void goBack() { if (mBitmapTemp != null && !mBitmapTemp.isRecycled()) { mBitmapTemp.recycle(); } Intent intent = new Intent(this, SplashDeckBeanActivity.class); intent.putExtras(getIntent().getExtras()); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } }
Java
package net.cardgame.orcalecard; import java.util.ArrayList; import java.util.List; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.MySwitch; import net.cardgame.oraclecard.common.SavedListener; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.TextView; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.model.ImageTagFactory; public class ListSpecialAdapter extends ArrayAdapter<DeckBean> implements OnCheckedChangeListener { ArrayList<DeckBean> listDeck; Activity context; List<Integer> special; SavedListener listener; private ImageManager imageManager; private ImageTagFactory imageTagFactory; boolean flag = true; SecurePreferences contentPreferences; public ListSpecialAdapter(Activity context, int textViewResourceId, ArrayList<DeckBean> objects, List<Integer> listSpecial) { super(context, textViewResourceId, objects); // TODO Auto-generated constructor stub this.listDeck = objects; listener = (SavedListener) context; this.context = context; this.special = listSpecial; if (special == null) special = new ArrayList<Integer>(); contentPreferences = new SecurePreferences(context, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); initImageLoader(); } public void setFlag(boolean flag) { this.flag = flag; } static class ViewHolder { TextView txtTitle; ImageView img_deck; MySwitch switch_button; } public List<Integer> getSpecialList() { return special; } private String getDeckName(DeckBean deckbean) { String deckName = ""; String key = "content_" + deckbean.deckId; if (contentPreferences.containsKey(key)) { String content = contentPreferences.getString(key); String[] arr = content.split("---"); deckName = arr[0]; if (deckName.contains("←")) deckName = deckName.substring(0, deckName.indexOf("←")); } return deckName; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.item_listview_setting_special, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.txtTitle = (TextView) rowView .findViewById(R.id.txt_deck_title); viewHolder.img_deck = (ImageView) rowView .findViewById(R.id.img_deck); viewHolder.switch_button = (MySwitch) rowView .findViewById(R.id.switch_on_off); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); DeckBean deck = listDeck.get(position); holder.txtTitle.setText(getDeckName(deck)); if (special.contains(deck.deckId)) { holder.switch_button.setChecked(true); } else { holder.switch_button.setChecked(false); } String tt = deck.deckId < 10 ? "0" + deck.deckId : "" + deck.deckId; holder.switch_button.setTag(deck.deckId); holder.switch_button.setOnCheckedChangeListener(this); String strDeck = deck.pathServerDownload + "/c" + tt + "i.png"; setImageTag(holder.img_deck, strDeck); loadImage(holder.img_deck); return rowView; } String convertIdtoString(int id) { return id < 10 ? "0" + id : "" + id; } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (!flag) return; int deckId = (Integer) buttonView.getTag(); // Utils.ELog("OnCheckedChanged", "DeckId:" + deckId + " ischeck:" // + isChecked); if (isChecked) special.add(deckId); else if (special.contains((Integer) deckId)) special.remove((Integer) deckId); if (special.isEmpty()) listener.onSave(false); else listener.onSave(true); // this.notifyDataSetChanged(); } private void initImageLoader() { imageManager = MyApplication.getInstance().getImageLoader(); imageTagFactory = createImageTagFactory(); } private ImageTagFactory createImageTagFactory() { ImageTagFactory imageTagFactory = ImageTagFactory.newInstance(); imageTagFactory.setHeight(248); imageTagFactory.setWidth(188); imageTagFactory.setDefaultImageResId(R.drawable.transparent_image); imageTagFactory.setErrorImageId(R.drawable.no_image); imageTagFactory.setSaveThumbnail(true); return imageTagFactory; } private void setImageTag(ImageView view, String url) { view.setTag(imageTagFactory.build(url, context)); } private void loadImage(ImageView view) { imageManager.getLoader().load(view); } }
Java
package net.cardgame.orcalecard; import java.util.Random; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.service.ServiceDownload; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; public class TestActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.result_activity_layout); startServiceDownload(); Random random = new Random(); if (random.nextBoolean()) { startServiceDownload(); } else { startServiceDownload2(); } } private void startServiceDownload() { Intent intent = new Intent(this, ServiceDownload.class); intent.putExtra(ServiceDownload.KEY_PATH_SERVER, "http://www.jma-inc.jp/appdata/OracleCard/Card_03.zip"); intent.putExtra(ServiceDownload.KEY_DECK_ID, 3); intent.putExtra(ServiceDownload.KEY_POSITION, 13); intent.putExtra(ServiceDownload.KEY_PATH_SAVE, ConstantValue.getPatchCardData(this) + "Card_03.zip"); startService(intent); } private void startServiceDownload2() { Intent intent = new Intent(this, ServiceDownload.class); intent.putExtra(ServiceDownload.KEY_PATH_SERVER, "http://www.jma-inc.jp/appdata/OracleCard/Card_04.zip"); intent.putExtra(ServiceDownload.KEY_DECK_ID, 4); intent.putExtra(ServiceDownload.KEY_POSITION, 12); intent.putExtra(ServiceDownload.KEY_PATH_SAVE, ConstantValue.getPatchCardData(this) + "Card_04.zip"); startService(intent); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); // Register mMessageReceiver to receive messages. LocalBroadcastManager.getInstance(this).registerReceiver( mBroadcastReceiver, new IntentFilter(ConstantValue.ACTION_DOWNLOAD)); } @Override protected void onPause() { // TODO Auto-generated method stub LocalBroadcastManager.getInstance(this).unregisterReceiver( mBroadcastReceiver); super.onPause(); } private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle bundle = intent.getExtras(); int deckID = bundle.getInt(ServiceDownload.KEY_DECK_ID); int position = bundle.getInt(ServiceDownload.KEY_POSITION); int percent = bundle.getInt(ServiceDownload.KEY_PERCENT); if (bundle.containsKey(ServiceDownload.KEY_STATUS)) { boolean finished = bundle .getBoolean(ServiceDownload.KEY_STATUS); Utils.ELog("Download and Unzip status", finished ? "finished" : "unfinished"); } Utils.ELog("receiver", "deckId:" + deckID + " position:" + position + " percent:" + percent); } }; }
Java
package net.cardgame.orcalecard; import java.io.File; import java.io.IOException; import java.lang.reflect.Type; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import javax.crypto.NoSuchPaddingException; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.BitmapCacheableImageView; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.FileUtils; import uk.co.senab.bitmapcache.BitmapLruCache; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class GalleryActivity extends Activity implements OnItemClickListener, OnItemSelectedListener, OnClickListener { int indexTypeHelp = 7; // List path các ảnh đã mã hóa public List<String> listPaths = new ArrayList<String>(); private int deckID = 10; private String deckName = ""; private String key = ""; // Text mo ta bo bai String strDescriptionDeck = ""; BitmapCacheableImageView iv_bg; TextView tvlabel_gallery; Button btnHelp; Button btnBack; private GalleryFlow gallery; private GalleryAdapter adapter; ArrayList<DeckBean> listSpecial; Handler handler = new Handler(); TextView tv_name; public static String pathCardBackImage = ""; SecurePreferences appPreferences; private SecurePreferences contentPreferences; SettingApp setting; int deckId = 0; int cardId = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_gallery); iv_bg = (BitmapCacheableImageView) findViewById(R.id.iv_bg); gallery = (GalleryFlow) findViewById(R.id.gallery); tv_name = (TextView) findViewById(R.id.tv_name); tvlabel_gallery = (TextView) findViewById(R.id.tvlabel_gallery); // getListSpecial(); // Bundle bundle = this.getIntent().getExtras(); deckID = bundle.getInt("deckId"); // deckName = bundle.getString("deckName"); // tvlabel_gallery.setText(deckName); contentPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); threadLoadTitleGallery loadTitle = new threadLoadTitleGallery(); loadTitle.start(); // Neu khong phai bo Special if (deckID != 999) { String strDECKID = (deckID < 10) ? ("0" + deckID) : ("" + deckID); pathCardBackImage = ConstantValue.APP_PREFERENCES + "/Card_" + strDECKID + "/en_c" + strDECKID + "d.png"; } else { // Neu la bo Special if (!listSpecial.isEmpty()) { iv_bg.setImageResource(R.drawable.bg999); tvlabel_gallery.setText(R.string.name_special_deck); } } new loadPathsAsyncTask().execute(); gallery.setOnItemClickListener(this); gallery.setOnItemSelectedListener(this); btnHelp = (Button) findViewById(R.id.btnHelp); btnBack = (Button) findViewById(R.id.btnBack); btnHelp.setOnClickListener(this); btnBack.setOnClickListener(this); } class threadLoadTitleGallery extends Thread { public void run() { handler.post(new Runnable() { @Override public void run() { key = "content_" + deckID; if (contentPreferences.containsKey(key)) { deckName = contentPreferences.getString(key); String[] arr = deckName.split("---"); deckName = arr[0]; if (deckName.contains("←")) deckName = deckName.substring(0, deckName.indexOf("←")); tvlabel_gallery.setText(deckName); } } }); } } void loadSettingApp() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); setting = gson.fromJson(strSetting, SettingAppType); } } ArrayList<DeckBean> getListSpecial() { appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); loadSettingApp(); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); ArrayList<DeckBean> listDeckBean = gson.fromJson(listSaved, listOfDeckBean); listSpecial = new ArrayList<DeckBean>(); for (DeckBean deckBean : listDeckBean) { if (deckBean.percentDownloaded == -2 && deckBean.deckId != 999 && deckBean.deckId != 998 && setting.listSpecial.contains((Integer) deckBean.deckId)) { listSpecial.add(deckBean); } } return listSpecial; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(this, CardDetailActivity.class); deckId = dId; cardId = cId; i.putExtra("cardId", cardId); i.putExtra("deckId", deckId); startActivityForResult(i, 1); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); clearCacheCardDetail(); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String[] content = getContentCard(position).split("---"); String title = content[0]; for (int i = 0; i < title.length() - 1; i++) { if (title.charAt(i) == '←') { title = title.substring(0, i - 1); break; } } tv_name.setText(title); } @Override public void onNothingSelected(AdapterView<?> arg0) { } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnBack: goBack(); break; case R.id.btnHelp: onClickButtonHelp(); default: break; } } public void onClickButtonHelp() { Intent i = new Intent(this, net.cardgame.orcalecard.HelpActivity.class); i.putExtra(HelpActivity.KEY_HELP_INDEX, indexTypeHelp); startActivity(i); } public String getContentCard(int pos) { String fullPath = listPaths.get(pos); Detect_DeckId_CardId_FromPath(fullPath); int deckId = dId; int cardId = cId; byte[] bytes; String strDECKID = (deckId < 10) ? ("0" + deckId) : ("" + deckId); String strCARDID = (cardId < 10) ? ("0" + cardId) : ("" + cardId); String content = ""; String pathTextFile = ConstantValue.getPatchCardData(this) + "/Card_" + strDECKID + "/en_t" + strDECKID + strCARDID + ".txt"; try { bytes = FileUtils.decryptToByteArray(pathTextFile, ""); content = new String(bytes, "UTF-8"); // Va ma hoa ve utf-8 } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content; } public void loadImageBackground(int _deckID) { String strDECKID = (_deckID < 10) ? ("0" + _deckID) : ("" + _deckID); // Path toi file anh background String pathImageBackground = ConstantValue.getPatchCardData(this) + "Card_" + strDECKID + "/en_bg" + strDECKID + ".jpg"; iv_bg = (BitmapCacheableImageView) findViewById(R.id.iv_bg); iv_bg.loadImage(pathImageBackground, this, 0); } private class loadPathsAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { // Neu khong phai deck Special if (deckID != 999) { listPaths = loadPaths(deckID, "png"); } else { // Neu la deck Special for (DeckBean dec : listSpecial) { List<String> temp = new ArrayList<String>(); temp = loadPaths(dec.deckId, "png"); if (temp.size() > 0) { for (String p : temp) { listPaths.add(p); } } } } return null; } @Override protected void onPostExecute(Void result) { if (deckID != 999) { loadImageBackground(deckID); adapter = new GalleryAdapter(GalleryActivity.this, listPaths, false); } else adapter = new GalleryAdapter(GalleryActivity.this, listPaths, true); gallery.setAdapter(adapter); gallery.setSpacing(-100); super.onPostExecute(result); } } public List<String> loadPaths(int deckId, String strFilter) { String strDECKID = (deckId < 10) ? "0" + deckId : "" + deckId; String _pathDirectory = ConstantValue.getPatchCardData(this) + "Card_" + strDECKID + "/X2/"; String strFilter1 = "c" + strDECKID + "t1-3"; String strFilter2 = "c" + strDECKID + "t"; String strFilter3 = "c" + strDECKID + "s"; String strFilter4 = "c" + strDECKID + "p"; String strFilter5 = "c" + strDECKID + "m"; String strFilter6 = "c" + strDECKID + "n"; String strFilter7 = "c" + strDECKID + "i"; String strFilter8 = "c" + strDECKID + "j"; String strFilter9 = "c" + strDECKID + "d"; String strFilter10 = "copyright"; String strFilter11 = "c" + strDECKID + "00"; List<String> listPaths = new ArrayList<String>(); File targetDirector = new File(_pathDirectory); File[] listFiles = targetDirector.listFiles(); if (listFiles.length > 0) { for (File f : listFiles) { String[] arr = null; String sub = ""; String s = ""; arr = f.getPath().split("\\/"); sub = arr[arr.length - 1]; arr = sub.split("\\."); sub = arr[arr.length - 1]; s = arr[0]; arr = s.split("\\_"); s = arr[arr.length - 1]; if (sub.equalsIgnoreCase(strFilter)) if (!s.equalsIgnoreCase(strFilter1) && !s.equalsIgnoreCase(strFilter2) && !s.equalsIgnoreCase(strFilter3) && !s.equalsIgnoreCase(strFilter4) && !s.equalsIgnoreCase(strFilter5) && !s.equalsIgnoreCase(strFilter6) && !s.equalsIgnoreCase(strFilter7) && !s.equalsIgnoreCase(strFilter8) && !s.equalsIgnoreCase(strFilter9) && !s.equalsIgnoreCase(strFilter10) && !s.equalsIgnoreCase(strFilter11)) listPaths.add(f.getPath()); } java.util.Collections.sort(listPaths); } return listPaths; } private int dId = -1; private int cId = -1; public void Detect_DeckId_CardId_FromPath(String path) { String[] arrPath = null; String subPath1 = ""; String subPath2 = ""; arrPath = path.split("\\/"); subPath1 = arrPath[arrPath.length - 3]; subPath2 = arrPath[arrPath.length - 1]; arrPath = subPath1.split("\\_"); subPath1 = arrPath[arrPath.length - 1]; subPath2 = subPath2.substring(6, 8); dId = Integer.parseInt(subPath1); cId = Integer.parseInt(subPath2); } @Override public void onBackPressed() { // TODO Auto-generated method stub goBack(); } void goBack() { Intent intent = new Intent(this, CardDeckActivity.class); intent.putExtras(getIntent().getExtras()); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } void clearCacheCardDetail() { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, deckId, cardId, ConstantValue.X1)); } void setFontTextView(TextView tv, String patch) { Typeface type = Typeface.createFromAsset(getAssets(), patch); tv.setTypeface(type); } }
Java
package net.cardgame.orcalecard; import java.util.ArrayList; import java.util.Date; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.service.DownloadUnzipObject; import net.cardgame.oraclecard.service.ServiceDownload; import net.cardgame.oraclecard.service.ServiceDownloadListener; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.Sort; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.OnImageLoadedListener; import com.novoda.imageloader.core.model.ImageTagFactory; public class GridViewAdapter extends ArrayAdapter<DeckBean> implements OnImageLoadedListener { private ImageManager imageManager; private ImageTagFactory imageTagFactory; Activity activity; ArrayList<DeckBean> listDeckBean; LinearLayout.LayoutParams paramsHeader, paramsFooter; int size = 0, loaded = 0; Date dateNow; private boolean image_load_finished = false; private ServiceDownloadListener downloadListener; public GridViewAdapter(Activity context, ArrayList<DeckBean> listDeckBean) { super(context, 0); downloadListener = (ServiceDownloadListener) context; activity = context; this.listDeckBean = listDeckBean; this.size = listDeckBean.size(); dateNow = new Date(); initImageLoader(); checkLoadFinished(); } private void checkLoadFinished() { SecurePreferences appPreferences = new SecurePreferences(activity, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE)) image_load_finished = true; } public ArrayList<DeckBean> sortDeckBean(int type) { switch (type) { case SettingApp.SORT_BY_BUY: listDeckBean = Sort.sortByBuy(listDeckBean); break; case SettingApp.SORT_BY_RELEASE: listDeckBean = Sort.sortByRelease(listDeckBean); break; case SettingApp.SORT_BY_USED: listDeckBean = Sort.sortByLastUsed(listDeckBean); break; default: break; } this.notifyDataSetChanged(); return listDeckBean; } /* Function display percent downloading of a DeckBean */ public void setPercentDownloaded(int position, int percentDownloaded) { listDeckBean.get(position).percentDownloaded = percentDownloaded; this.notifyDataSetChanged(); } public void updateStatus(ArrayList<DeckBean> listDeck) { this.listDeckBean = listDeck; this.notifyDataSetChanged(); } public void setPercent(int decId, int percent) { for (DeckBean deckBean : listDeckBean) { if (deckBean.deckId == decId) { deckBean.percentDownloaded = percent; this.notifyDataSetChanged(); downloadListener.onUpdateProgressListener(percent, 0, decId); if (percent == 100) { downloadListener .onFinishedListener(new DownloadUnzipObject( deckBean.deckId, 0, "", "")); } return; } } } /* Function unlock a DeckBean by position */ public void unlockDeckBean(int position) { listDeckBean.get(position).isUnlock = true; this.notifyDataSetChanged(); } public void unlockDeckBeanById(int deckId) { for (DeckBean dec : listDeckBean) { if (dec.deckId == deckId) { dec.isUnlock = true; return; } } } /* get GridView item total */ @Override public int getCount() { // TODO Auto-generated method stub if (size % 3 == 0) return size; else return size + (3 - size % 3); } /* Get item gridview by position */ @Override public DeckBean getItem(int position) { // TODO Auto-generated method stub return listDeckBean.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } private String idToString(int id) { return id < 10 ? "0" + id : "" + id; } /* * (non-Javadoc) * * @see android.widget.ArrayAdapter#getView(int, android.view.View, * android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View row = convertView; ViewHolder holder; /* * inflate layout */ if (row == null) { LayoutInflater inflator = activity.getLayoutInflater(); row = inflator.inflate(R.layout.item_gridview_top_header, null); holder = new ViewHolder(); holder.progressbar = (ProgressBar) row .findViewById(R.id.progressbar); holder.progressbar.setMax(100); holder.imgViewCategory = (ImageView) row .findViewById(R.id.image_category_option_gridview); holder.imgTitle = (ImageView) row .findViewById(R.id.image_title_option_gridview); holder.imgNew = (ImageView) row .findViewById(R.id.image_new_option_gridview); holder.imgLock = (ImageView) row .findViewById(R.id.image_lock_option_gridview); holder.imgBackground = (ImageView) row .findViewById(R.id.image_bg_option_gridview); holder.txtHeader = (TextView) row.findViewById(R.id.txt_header); paramsHeader = (LinearLayout.LayoutParams) holder.txtHeader .getLayoutParams(); holder.txtFooter = (TextView) row.findViewById(R.id.txt_footer); paramsFooter = (LinearLayout.LayoutParams) holder.txtFooter .getLayoutParams(); row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } /* * Set bacground resource */ if (position % 3 == 0) { holder.imgBackground.setImageResource(R.drawable.left_bg); } else if (position % 3 == 1) { holder.imgBackground.setImageResource(R.drawable.center_bg); } else holder.imgBackground.setImageResource(R.drawable.right_bg); /* * set image resource */ if (position < 3) holder.txtHeader.setLayoutParams(paramsHeader); else holder.txtHeader.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0)); if (position > getCount() - 4) holder.txtFooter.setLayoutParams(paramsFooter); else { holder.txtFooter.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0)); } DeckBean deckBean = new DeckBean(); try { deckBean = listDeckBean.get(position); } catch (Exception ex) { holder.imgTitle.setImageDrawable(null); holder.imgViewCategory.setImageDrawable(null); holder.imgLock.setImageDrawable(null); holder.imgNew.setImageDrawable(null); holder.progressbar.setVisibility(View.INVISIBLE); return row; } if (deckBean.isUnlock || deckBean.isFree) holder.imgLock.setImageDrawable(null); else { holder.imgLock.setImageResource(R.drawable.mypage_lock); } if (deckBean.releaseDate != null) holder.imgNew.setImageResource(R.drawable.new_release); else { holder.imgNew.setImageDrawable(null); } String tt = idToString(deckBean.deckId); String title = deckBean.pathServerDownload + "/c" + tt + "n.png"; String strDeck = deckBean.pathServerDownload + "/c" + tt + "i.png"; setImageTag(holder.imgTitle, title); loadImage(holder.imgTitle); setImageTag(holder.imgViewCategory, strDeck); loadImage(holder.imgViewCategory); /* Set percent downloading */ int percent = deckBean.percentDownloaded; if (percent >= 0 && percent < 100) { holder.progressbar.setVisibility(View.VISIBLE); holder.progressbar.setProgress(percent); holder.progressbar.setIndeterminate(false); } else { holder.progressbar.setVisibility(View.INVISIBLE); } long diff = dateNow.getTime() - deckBean.releaseDate.getTime(); int numberOfDay = (int) (diff / 1000 / 60 / 60 / 24); // Set is New if (deckBean.percentDownloaded == -2 || numberOfDay > 30) { holder.imgNew.setVisibility(View.INVISIBLE); } else holder.imgNew.setVisibility(View.VISIBLE); return row; } static class ViewHolder { ImageView imgTitle; ImageView imgBackground; ImageView imgViewCategory; ImageView imgLock; ImageView imgNew; TextView txtHeader, txtFooter; ProgressBar progressbar; } private void initImageLoader() { imageManager = MyApplication.getInstance().getImageLoader(); imageTagFactory = createImageTagFactory(); } private ImageTagFactory createImageTagFactory() { ImageTagFactory imageTagFactory = ImageTagFactory.newInstance(); imageTagFactory.setHeight(248); imageTagFactory.setWidth(188); imageTagFactory.setDefaultImageResId(R.drawable.cardi_tranparent); imageTagFactory.setErrorImageId(R.drawable.cardi_tranparent); imageTagFactory.setSaveThumbnail(true); return imageTagFactory; } private void setImageTag(ImageView view, String url) { view.setTag(imageTagFactory.build(url, activity)); // view.setContentDescription(url); } private void loadImage(ImageView view) { imageManager.getLoader().load(view); if (!image_load_finished) imageManager.setOnImageLoadedListener(this); } @Override public synchronized void onImageLoaded(ImageView imageview) { // TODO Auto-generated method stub // Utils.ELog("loaded", imageview.getContentDescription().toString()); loaded++; if (loaded >= 2 * size - 4) { // Save sharedreference SecurePreferences appPreferences = new SecurePreferences(activity, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); appPreferences.put(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE, "true"); } } private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle bundle = intent.getExtras(); if (bundle.containsKey(ServiceDownload.KEY_MESSAGE_FULL_MEMORY)) { downloadListener.onDownloadFailListener(null, bundle .getString(ServiceDownload.KEY_MESSAGE_FULL_MEMORY)); return; } int deckID = bundle.getInt(ServiceDownload.KEY_DECK_ID); int position = bundle.getInt(ServiceDownload.KEY_POSITION); int percent = bundle.getInt(ServiceDownload.KEY_PERCENT); setPercent(deckID, percent); if (bundle.containsKey(ServiceDownload.KEY_STATUS)) { boolean finished = bundle .getBoolean(ServiceDownload.KEY_STATUS); if (!finished) { downloadListener.onDownloadFailListener( new DownloadUnzipObject(deckID, position, "", ""), null); } } } }; public void registryBroadcast() { LocalBroadcastManager.getInstance(activity).registerReceiver( mBroadcastReceiver, new IntentFilter(ConstantValue.ACTION_DOWNLOAD)); } public void unRegistryBroadcast() { LocalBroadcastManager.getInstance(activity).unregisterReceiver( mBroadcastReceiver); } }
Java
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.animation.FlakeView; import net.cardgame.orcalecard.asynctask.DownloadListener; import net.cardgame.orcalecard.asynctask.GetListDeckTask; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.XmlParser; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * Màn hình Home * */ public class MainActivity extends Activity implements OnClickListener, DownloadListener { String config = ""; ProgressDialog dialog; boolean gotoTopPage = false; boolean load_toppage_finished = false; FlakeView flakeView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout container = (LinearLayout) findViewById(R.id.container); flakeView = new FlakeView(this); container.addView(flakeView); getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK)); findViewById(R.id.btnMyPage).setOnClickListener(this); findViewById(R.id.btnInformation).setOnClickListener(this); getStatus(); } /** * */ void getStatus() { SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE)) { load_toppage_finished = true; } if (appPreferences.containsKey(ConstantValue.CONFIG_DECKBEAN_KEY)) { config = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); } else { if (NetworkUtils.isNetworkConnected(this)) { dialog = ProgressDialog.show(this, "", "Loading..Wait..", true); dialog.show(); GetListDeckTask task = new GetListDeckTask(this); task.setDownloadListener(this); task.execute(""); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE)) { load_toppage_finished = true; } } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btnMyPage: // go to my page activity if (config != null && config != "") { gotoToppage(); } else { if (NetworkUtils.isNetworkConnected(this)) { gotoTopPage = true; dialog = ProgressDialog.show(this, "", "Loading..Wait..", true); dialog.show(); GetListDeckTask task = new GetListDeckTask(this); task.setDownloadListener(this); task.execute(""); } else showDialogSetting(); } break; case R.id.btnInformation:// go to app information activity if (NetworkUtils.isNetworkConnected(this)) { Intent intent = new Intent(this, InfoAppActivity.class); startActivityForResult(intent, 1); } else showDialogSetting(); break; default: break; } } void gotoToppage() { if (!load_toppage_finished && !NetworkUtils.isNetworkConnected(this)) { showDialogSetting(); return; } Intent intent = new Intent(this, TopPageActivity.class); intent.putExtra("continue_download", 1); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); this.finish(); } @Override public void onDownloadSuccessListener(String result) { // TODO Auto-generated method stub new saveXMLtoJson().execute(result); } @Override public void onDownloadFailListener(String result) { // TODO Auto-generated method stub if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } @Override public void onProgressUpdateListener(Integer update) { // TODO Auto-generated method stub } void showDialogSetting() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); String title = getResources().getString( R.string.dialog_errornetwork_title); String message = getResources().getString( R.string.dialog_errornetwork_message); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); } }); AlertDialog dialog = builder.show(); } class saveXMLtoJson extends AsyncTask<String, Void, ArrayList<DeckBean>> { @Override protected ArrayList<DeckBean> doInBackground(String... params) { // TODO Auto-generated method stub return new XmlParser().getDeckBeans(params[0]); } @Override protected void onPostExecute(ArrayList<DeckBean> result) { // TODO Auto-generated method stub super.onPostExecute(result); SecurePreferences appPreferences = new SecurePreferences( MainActivity.this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String save = gson.toJson(result, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); config = save; if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } if (gotoTopPage) { gotoToppage(); } } } @Override protected void onPause() { super.onPause(); if (flakeView != null) flakeView.pause(); } @Override protected void onResume() { super.onResume(); if (flakeView != null) flakeView.resume(); } }
Java
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.SelectedHistoryListener; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.bean.HistoryBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.Sort; import uk.co.senab.bitmapcache.BitmapLruCache; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class HistoryActivity extends Activity implements SelectedHistoryListener, OnClickListener { ArrayList<HistoryBean> listHistory = new ArrayList<HistoryBean>(); HistoryAdapter adapter; ArrayList<CardBean> listCardBean = new ArrayList<CardBean>(); @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.history_activity); ListView listView = (ListView) findViewById(R.id.listView_history); findViewById(R.id.btnhelp_history).setOnClickListener(this); findViewById(R.id.btnBack_history).setOnClickListener(this); getListHistory(); if (!listHistory.isEmpty()) { adapter = new HistoryAdapter(this, listHistory); listView.setAdapter(adapter); } } void getListHistory() { Gson gson = new Gson(); Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() { }.getType(); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.HISTORY_KEY)) { String strHistory = appPreferences .getString(ConstantValue.HISTORY_KEY); listHistory = gson.fromJson(strHistory, listOfHistoryBean); listHistory = Sort.sortHistoryByDate(listHistory); } } @Override public void onSelectedItemListener(int id) { // TODO Auto-generated method stub for (HistoryBean historyBean : listHistory) { if (historyBean.id == id) for (CardBean card : historyBean.cardBeans) { listCardBean.add(card); } } Intent intent = new Intent(this, EditHistoryActivity.class); intent.putExtra("historyId", id); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override public void onDeleteHistory(HistoryBean history) { // TODO Auto-generated method stub listHistory.remove(history); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() { }.getType(); ArrayList<HistoryBean> listSave = listHistory; Collections.reverse(listSave); String save = gson.toJson(listSave, listOfHistoryBean); appPreferences.put(ConstantValue.HISTORY_KEY, save); } @Override public void onClick(View v) { // TODO Auto-generated method stub findViewById(R.id.btnhelp_history).setOnClickListener(this); findViewById(R.id.btnBack_history).setOnClickListener(this); switch (v.getId()) { case R.id.btnhelp_history: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 1); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btnBack_history: this.finish(); break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); if (adapter != null) { adapter.notifyDataSetChanged(); } } private void clearCache() { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); for (CardBean card : listCardBean) { cache.removeFromMemory(ConstantValue.getPathCardDetail(this, card.deckId, card.cardId, ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, card.deckId, card.cardId, ConstantValue.X1)); } } @Override protected void onDestroy() { // TODO Auto-generated method stub clearCache(); super.onDestroy(); } @Override public void onFinished() { // TODO Auto-generated method stub } }
Java
package net.cardgame.orcalecard; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.billingutils.IabHelper; import net.cardgame.oraclecard.billingutils.IabResult; import net.cardgame.oraclecard.billingutils.Inventory; import net.cardgame.oraclecard.billingutils.Purchase; import net.cardgame.oraclecard.service.ServiceDownload; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.model.ImageTagFactory; /* * Màn hình Deck Lock * * */ public class InfoDeckActivity extends Activity implements OnClickListener { TextView tvDeckName; TextView tvPrice; TextView tvContentInfo; private ImageView ivLogo; private ImageView ivBackground; LinearLayout wait_layout; Button btnBack; Button btnHelp; Button btnBuy; Button btnRestore; private ImageManager imageManager; private ImageTagFactory imageTagFactory; private String pathDeckInfo = ""; // Duong dan den file info int indexTypeHelp = 6; DeckBean deckBean; int selectedPosition; Handler handler = new Handler(); private String key = ""; private SecurePreferences contentPreferences; // / BILLING static final String BILLING_TAG = "DECK BILLING"; static final int PURCHASE_REQUEST = 10001; // The helper object IabHelper mHelper; // public key in developer console String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; boolean isBillingSupport = false; // String payload để kiểm tra tính xác thực của việc mua bán. String payload = ""; // static final String SKU_TEST = "android.test.purchased"; boolean flag = true; int mRequestCode; long releaseDate = 0; // / @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_info_deck); initImageLoader(); // / INIT BILLING base64EncodedPublicKey = this.getResources().getString( R.string.app_public_key); // Create the helper, passing it our context and the public key to // verify signatures with Utils.ELog(BILLING_TAG, "Creating IAB helper."); mHelper = new IabHelper(this, base64EncodedPublicKey); // enable debug logging (for a production application, you should set // this to false). mHelper.enableDebugLogging(false); wait_layout = (LinearLayout) findViewById(R.id.layout_wait_billing); btnBuy = (Button) findViewById(R.id.btn_buy); btnRestore = (Button) findViewById(R.id.btn_restore); btnBuy.setOnClickListener(this); btnRestore.setOnClickListener(this); // /----------------------------- // Tạo scrollBar cho TextContent tvContentInfo = (TextView) findViewById(R.id.tvContentInfo); tvDeckName = (TextView) findViewById(R.id.tvDeckName); tvPrice = (TextView) findViewById(R.id.tvPrice); ivLogo = (ImageView) findViewById(R.id.ivLogo); ivBackground = (ImageView) findViewById(R.id.ivBackground); btnBack = (Button) findViewById(R.id.btnBack); btnHelp = (Button) findViewById(R.id.btnHelp); btnBack.setOnClickListener(this); btnHelp.setOnClickListener(this); // Nhận DeckBean từ "TopPageActivity" về deckBean = new DeckBean(); Bundle bundle = this.getIntent().getExtras(); deckBean.deckId = bundle.getInt("deckId"); deckBean.deckName = bundle.getString("deckName"); Utils.ELog("Deck Name", deckBean.deckName); deckBean.deckPrice = bundle.getInt("deckPrice"); deckBean.pathServerDownload = bundle.getString("deckPathServer"); deckBean.isUnlock = bundle.getBoolean("isUnlock"); deckBean.isFree = bundle.getBoolean("isFree"); deckBean.inAppPurchaseId = bundle.getString("inAppPurchaseId"); if (bundle.containsKey("position")) selectedPosition = bundle.getInt("position"); if (bundle.containsKey("releaseDate")) { releaseDate = bundle.getLong("releaseDate"); } if (bundle.containsKey("requestCode")) mRequestCode = bundle.getInt("requestCode"); key = "content_" + deckBean.deckId; contentPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); switch (deckBean.deckId) { case 999: btnBuy.setVisibility(View.INVISIBLE); btnRestore.setVisibility(View.INVISIBLE); ivBackground.setImageResource(R.drawable.bg999); ivLogo.setImageResource(R.drawable.c999i); tvContentInfo.setText(R.string.special_sumary); tvDeckName.setText(R.string.name_special_deck); return; case 998: btnBuy.setVisibility(View.INVISIBLE); btnRestore.setVisibility(View.INVISIBLE); ivBackground.setImageResource(R.drawable.bg998); ivLogo.setImageResource(R.drawable.c998i); tvContentInfo.setText(R.string.random_sumary); tvDeckName.setText(R.string.name_random_deck); return; default: String strDeckId = (deckBean.deckId < 10) ? ("0" + deckBean.deckId) : ("" + deckBean.deckId); pathDeckInfo = deckBean.pathServerDownload + "/t" + strDeckId + ".txt"; loadDataText(pathDeckInfo); break; } /* * 1. Nếu deck isUnlock = true: Deck đã được mua - Button Buy ở trạng * thái unactive. Đồng thời string của button là "購入済" - Button Restore * ở trạng thái active. * * 2. Nếu deck isUnlock = false: Deck chưa được mua - Button Buy ở trạng * thái active. Đồng thời string của button là "購入する" - Button Restore ở * trạng thái unactive. */ if (deckBean.isUnlock) { btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); } else { btnBuy.setEnabled(true); btnBuy.setText(R.string.string_btnBuy_no); btnRestore.setEnabled(false); // Khởi tạo billing nếu deck chưa được mua setWaitScreen(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. Utils.ELog(BILLING_TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Utils.ELog(BILLING_TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. Utils.ELog(BILLING_TAG, "Problem setting up in-app billing: " + result); setWaitScreen(false); return; } // Hooray, IAB is fully set up. Now, let's get an inventory // of // stuff we own. Utils.ELog(BILLING_TAG, "Setup successful. Querying inventory."); isBillingSupport = true; // mHelper.queryInventoryAsync(mGotInventoryListener); List<String> skulist = new ArrayList<String>(); skulist.add(deckBean.inAppPurchaseId); mHelper.queryInventoryAsync(true, skulist, mGotInventoryListener); } }); } loadDataImageThread loadImage = new loadDataImageThread(); loadImage.start(); tvPrice.setText(" ¥ " + deckBean.deckPrice); } private void initImageLoader() { imageManager = MyApplication.getInstance().getImageLoader(); imageTagFactory = createImageTagFactory(); } public void loadDataText(String path) { String content = ""; // Kiem tra da co key nay trong SharedReferences chua // Neu co roi thi lay noi dung content ve if (contentPreferences.containsKey(key)) { content = contentPreferences.getString(key); String[] arr = content.split("---"); String nameDeck = arr[0]; String contentDeck = arr[1]; contentDeck = insertNewLine(contentDeck); for (int i = 0; i < nameDeck.length() - 1; i++) { if (nameDeck.charAt(i) == '←') { nameDeck = nameDeck.substring(0, i - 1); break; } } tvDeckName.setText(nameDeck); tvContentInfo.setText(contentDeck); } // Neu chua co trong SharedReferenced thi load tu internet. // Sau do luu vao SharedReferenced else { // Neu co mang internet if (NetworkUtils.isNetworkConnected(InfoDeckActivity.this)) { new loadDataTextAsyncTask().execute(path); } else { // Nguoc lai khong co internet showDialogSetting(); } } } private class loadDataTextAsyncTask extends AsyncTask<String, Void, String> { String content = ""; @Override protected String doInBackground(String... params) { String path = params[0]; try { URL urlContent = new URL(path); BufferedReader in = new BufferedReader(new InputStreamReader( urlContent.openStream())); String str = ""; while ((str = in.readLine()) != null) { content += str; } in.close(); } catch (MalformedURLException e) { Log.e("Error: ", e.getMessage()); } catch (Exception e) { Log.e("Error: ", e.getMessage()); } return content; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result != "") { String _content = result; String[] arr = _content.split("---"); String nameDeck = arr[0]; String contentDeck = arr[1]; contentDeck = insertNewLine(contentDeck); for (int i = 0; i < nameDeck.length() - 1; i++) { if (nameDeck.charAt(i) == '←') { nameDeck = nameDeck.substring(0, i - 1); break; } } tvDeckName.setText(nameDeck); tvContentInfo.setText(contentDeck); // Nhet content vao trong sharedReferenced contentPreferences.put(key, _content); } } } @Override public void onClick(View v) { if (!flag) return; switch (v.getId()) { case R.id.btnBack: goBack(); break; case R.id.btnHelp: flag = false; onClickButtonHelp(); break; case R.id.btn_buy: { // Date date = new Date(releaseDate); // Utils.ELog("releaseDate", date.toGMTString()); // testReleaseDate(); if (!isRelease()) { String message = getResources().getString( R.string.message_not_release); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); return; } flag = false; onClickButtonBuy(); // onClickButtonRestore(); break; } case R.id.btn_restore: flag = false; onClickButtonRestore(); break; default: break; } } // private void testReleaseDate() { // Date date = new Date(); // date.setDate(19); // date.setMonth(8); // date.setYear(2013 - 1900); // releaseDate = date.getTime(); // } private boolean isRelease() { Date dateNow = new Date(); long diff = dateNow.getTime() - releaseDate; if (diff >= 0) return true; else return false; } public void onClickButtonBuy() { // Neu co mang internet if (NetworkUtils.isNetworkConnected(this)) { // Nếu deck là free if (deckBean.isFree) { flag = true; deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); return; } // Nếu device có hỗ trợ billing hoặc billing khới tạo thành công if (isBillingSupport) { // Test Only deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); onClickButtonRestore(); // // setWaitScreen(true); // Utils.ELog(BILLING_TAG, "Launching purchase flow for deck."); // Utils.ELog(BILLING_TAG, " product id: " // + deckBean.inAppPurchaseId); // // /* // // * TODO: for security, generate your payload here for // // * verification. See the comments on verifyDeveloperPayload() // // * for more info. Since this is a SAMPLE, we just use an empty // // * string, but on a production app you should carefully // // generate // // * this. // // */ // payload = ""; // mHelper.launchPurchaseFlow(this, deckBean.inAppPurchaseId, // PURCHASE_REQUEST, mPurchaseFinishedListener, payload); } else { Toast.makeText(this, "Billing is not initialization", Toast.LENGTH_LONG).show(); flag = true; } } else { // Neu khong co mang thi khong lam gi flag = true; showDialogSetting(); } } private void startDownloadService() { if (NetworkUtils.isNetworkConnected(this)) { Intent intentService = new Intent(this, ServiceDownload.class); String id = deckBean.deckId < 10 ? "0" + deckBean.deckId : "" + deckBean.deckId; intentService .putExtra(ServiceDownload.KEY_DECK_ID, deckBean.deckId); intentService.putExtra(ServiceDownload.KEY_PATH_SERVER, deckBean.pathServerDownload + ".zip"); intentService.putExtra(ServiceDownload.KEY_POSITION, selectedPosition); intentService.putExtra(ServiceDownload.KEY_PATH_SAVE, ConstantValue.getPatchCardData(this) + "Card_" + id + ".zip"); startService(intentService); } } public synchronized void onClickButtonRestore() { // Neu co mang internet if (NetworkUtils.isNetworkConnected(InfoDeckActivity.this)) { // perform download and unzip // contentPreferences.removeValue(key); startDownloadService(); if (mRequestCode == CardDeckActivity.requestcodeInfoDeck) { setResult(RESULT_FIRST_USER); Intent intent1 = new Intent(this, TopPageActivity.class); // intent1.putExtra("deckId", deckBean.deckId); // intent1.putExtra("position", selectedPosition); startActivity(intent1); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } else { Intent intent = new Intent(); intent.putExtra("position", selectedPosition); setResult(RESULT_OK, intent); this.finish(); } } else { showDialogSetting(); } } public void onClickButtonHelp() { Intent i = new Intent(this, net.cardgame.orcalecard.HelpActivity.class); i.putExtra(HelpActivity.KEY_HELP_INDEX, indexTypeHelp); startActivityForResult(i, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } class loadDataImageThread extends Thread { public void run() { handler.post(new Runnable() { @Override public void run() { loadDataImage(); } }); } } private ImageTagFactory createImageTagFactory() { ImageTagFactory imageTagFactory = ImageTagFactory.newInstance(); imageTagFactory.setHeight(1000); imageTagFactory.setWidth(1000); imageTagFactory.setDefaultImageResId(R.drawable.transparent_image); imageTagFactory.setErrorImageId(R.drawable.transparent_image); imageTagFactory.setSaveThumbnail(true); return imageTagFactory; } private void setImageTag(ImageView view, String url) { view.setTag(imageTagFactory.build(url, this)); } private void loadImage(ImageView view) { imageManager.getLoader().load(view); } // Load du lieu anh Image public void loadDataImage() { int deckId = deckBean.deckId; String strDeckId = (deckId < 10) ? ("0" + deckId) : ("" + deckId); String pathImageBackground = deckBean.pathServerDownload + "/bg" + strDeckId + ".jpg"; String pathImageLogoDeck = deckBean.pathServerDownload + "/c" + strDeckId + "i.png"; setImageTag(ivBackground, pathImageBackground); loadImage(ivBackground); setImageTag(ivLogo, pathImageLogoDeck); loadImage(ivLogo); } // Chèn ký tự xuống dòng khi gặp dấu chấm public String insertNewLine(String str) { String tmp = ""; for (int i = 0; i < str.length(); i++) { tmp += str.charAt(i) + ""; if (str.charAt(i) == '。') tmp += "\n"; } return tmp; } void showDialogSetting() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); String title = getResources().getString( R.string.dialog_errornetwork_title); String message = getResources().getString( R.string.dialog_errornetwork_message); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); flag = true; } }); builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { flag = true; dialog.dismiss(); startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); } }); builder.show(); } // // CÁC BILLING FUNCTION. CHỈ DÙNG PURCHASE FUNCTION, CÁC FUNCTION KHÁC ĐỂ // DỰ PHÒNG // Tắt/bật màn hình chờ void setWaitScreen(boolean set) { wait_layout.setVisibility(set ? View.VISIBLE : View.GONE); btnBuy.setClickable(set ? false : true); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Utils.ELog(BILLING_TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data); flag = true; overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); // Pass on the activity result to the helper for handling if (isBillingSupport && !mHelper.handleActivityResult(requestCode, resultCode, data)) { // not handled, so handle it ourselves (here's where you'd // perform any handling of activity results not related to in-app // billing... super.onActivityResult(requestCode, resultCode, data); } else { Utils.ELog(BILLING_TAG, "onActivityResult handled by IABUtil."); } } // Listener that's called when we finish querying the items and // subscriptions we own // Lấy thông tin các item mà user đã mua (sở hữu) IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Utils.ELog(BILLING_TAG, "Query inventory finished."); if (result.isFailure()) { Utils.ELog(BILLING_TAG, "Failed to query inventory: " + result); setWaitScreen(false); return; } Utils.ELog(BILLING_TAG, "Query inventory was successful."); Purchase testPurchase = inventory .getPurchase(deckBean.inAppPurchaseId); if (testPurchase != null && verifyDeveloperPayload(testPurchase)) { deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); Utils.ELog(BILLING_TAG, "Query inventory sku: " + testPurchase.getSku()); // Utils.ELog(BILLING_TAG, " Consuming test item "); // setWaitScreen(true); // mHelper.consumeAsync(testPurchase, mConsumeFinishedListener); } setWaitScreen(false); } }; /** Verifies the developer payload of a purchase. */ // xác thực đoạn payload string trả về boolean verifyDeveloperPayload(Purchase p) { String payloadReturn = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. * It will be the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase * and verifying it here might seem like a good approach, but this will * fail in the case where the user purchases an item on one device and * then uses your app on a different device, because on the other device * you will not have access to the random string you originally * generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different * between them, so that one user's purchase can't be replayed to * another user. * * 2. The payload must be such that you can verify it even when the app * wasn't the one who initiated the purchase flow (so that items * purchased by the user on one device work on other devices owned by * the user). * * Using your own server to store and verify developer payloads across * app installations is recommended. */ return true; } // Callback for when a purchase is finished IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { Utils.ELog(BILLING_TAG, "Purchase finished: " + result + ", purchase: " + purchase); flag = true; if (result.isFailure()) { Utils.ELog(BILLING_TAG, "Error purchasing: " + result); if (result.getResponse() == 7) { // Utils.ELog(BILLING_TAG, "START CONSUME ITEM"); // mHelper.consumeAsync(purchase, mConsumeFinishedListener); deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); setWaitScreen(false); return; } else { setWaitScreen(false); return; } } if (!verifyDeveloperPayload(purchase)) { Utils.ELog(BILLING_TAG, "Error purchasing. Authenticity verification failed."); setWaitScreen(false); return; } Utils.ELog(BILLING_TAG, "Purchase successful."); if (purchase.getSku().equals(deckBean.inAppPurchaseId)) { Utils.ELog(BILLING_TAG, "Purchase test success!"); // dùng luôn để lần sau còn test // mHelper.consumeAsync(purchase, mConsumeFinishedListener); deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); onClickButtonRestore(); } setWaitScreen(false); } }; // Called when consumption is complete // IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new // IabHelper.OnConsumeFinishedListener() { // public void onConsumeFinished(Purchase purchase, IabResult result) { // Utils.ELog(BILLING_TAG, "Consumption finished. Purchase: " // + purchase + ", result: " + result); // // // We know this is the "gas" sku because it's the only one we // // consume, // // so we don't check which sku was consumed. If you have more than // // one // // sku, you probably should check... // if (result.isSuccess()) { // // successfully consumed // Utils.ELog(BILLING_TAG, "Consumption successful. Provisioning."); // // } else { // Utils.ELog(BILLING_TAG, "Error while consuming: " + result); // } // setWaitScreen(false); // } // }; // We're being destroyed. It's important to dispose of the helper here! @Override public void onDestroy() { super.onDestroy(); // very important: Utils.ELog(BILLING_TAG, "Destroying helper."); if (mHelper != null) mHelper.dispose(); mHelper = null; } @Override public void onBackPressed() { // TODO Auto-generated method stub goBack(); super.onBackPressed(); } private void goBack() { Intent intent = new Intent(); intent.putExtra("position", selectedPosition); Utils.ELog("isUnlock", deckBean.isUnlock + ""); intent.putExtra("isUnlock", deckBean.isUnlock); setResult(RESULT_OK, intent); this.finish(); } @Override protected void onResume() { flag = true; super.onResume(); } }
Java
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.SavedListener; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ImageView; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class SettingSpecialActivity extends Activity implements OnClickListener, SavedListener, OnScrollListener { ListSpecialAdapter adapter; SecurePreferences appPreferences; SettingApp setting; boolean save = true; ImageView button_save; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.setting_special_deck_layout); appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); loadSettingApp(); findViewById(R.id.btnBack_setting_special).setOnClickListener(this); findViewById(R.id.btnhelp_setting_special).setOnClickListener(this); button_save = (ImageView) findViewById(R.id.btn_save_setting_special); button_save.setOnClickListener(this); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); ArrayList<DeckBean> listDeckBean = gson.fromJson(listSaved, listOfDeckBean); ListView listView = (ListView) findViewById(R.id.listView_setting_special); adapter = new ListSpecialAdapter(this, R.layout.item_listview_setting_special, getListSpecial(listDeckBean), setting.listSpecial); listView.setFadingEdgeLength(0); listView.setAdapter(adapter); listView.setOnScrollListener(this); } void loadSettingApp() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); // Utils.ELog("str_History", strHistory); setting = gson.fromJson(strSetting, SettingAppType); } } ArrayList<DeckBean> getListSpecial(ArrayList<DeckBean> list) { ArrayList<DeckBean> listtemp = new ArrayList<DeckBean>(); for (DeckBean deckBean : list) { if (deckBean.percentDownloaded == -2 && deckBean.deckId != 999 && deckBean.deckId != 998) { listtemp.add(deckBean); } } return listtemp; } @Override public void onClick(View v) { // TODO Auto-generated method stub findViewById(R.id.btnBack_setting_special).setOnClickListener(this); findViewById(R.id.btnhelp_setting_special).setOnClickListener(this); findViewById(R.id.btn_save_setting_special).setOnClickListener(this); switch (v.getId()) { case R.id.btnBack_setting_special: this.finish(); break; case R.id.btnhelp_setting_special: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 3); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_save_setting_special: if (save) { setting.listSpecial = adapter.getSpecialList(); saveSetting(); this.finish(); } break; default: break; } } void saveSetting() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); String save = gson.toJson(setting, SettingAppType); appPreferences.put(ConstantValue.SETTING_KEY, save); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } @Override public void onSave(boolean save) { // TODO Auto-generated method stub this.save = save; if (!save) { button_save.setSelected(true); } else button_save.setSelected(false); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub if (scrollState != SCROLL_STATE_IDLE) adapter.setFlag(false); else adapter.setFlag(true); // adapter.notifyDataSetChanged(); } }
Java
package net.cardgame.orcalecard; import java.util.Arrays; import java.util.Collection; import java.util.List; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.KeyboardHelper; import net.cardgame.orcalecard.utils.NetworkUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.facebook.LoggingBehavior; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.Session.StatusCallback; import com.facebook.SessionLoginBehavior; import com.facebook.SessionState; import com.facebook.Settings; public class PostFacebookActivity extends Activity implements OnClickListener { ImageView card1; ImageView card2; ImageView card3; ImageView card4; ImageView jumpCard; ImageView btn_share; ImageView bg_layout; LinearLayout wait_layout; ImageView btn_back; ImageView btn_help; EditText edit_status; CardBean cardBean1; CardBean cardBean2; CardBean cardBean3; CardBean cardBean4; Bitmap postBitmap = null; int number_of_card; int deckId; // phiên kết nối facebook private Session session; private static final List<String> PERMISSIONS = Arrays .asList("publish_actions"); private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization"; private boolean pendingPublishReauthorization = false; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.postfacebook_layout); // connect facebook function this.session = createSession(); Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS); Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_RAW_RESPONSES); Settings.addLoggingBehavior(LoggingBehavior.DEVELOPER_ERRORS); // / initView(); getExtra(); loadImage(); } private void initView() { card1 = (ImageView) findViewById(R.id.img_card1_save); card2 = (ImageView) findViewById(R.id.img_card2_save); card3 = (ImageView) findViewById(R.id.img_card3_save); card4 = (ImageView) findViewById(R.id.img_card4_save); card1.setClickable(false); card2.setClickable(false); card3.setClickable(false); card4.setClickable(false); btn_back = (ImageView) findViewById(R.id.btnBack_postfacebook); btn_help = (ImageView) findViewById(R.id.btnhelp_postfacebook); edit_status = (EditText) findViewById(R.id.edit_postfacebook); btn_share = (ImageView) findViewById(R.id.btn_postfacebook); bg_layout = (ImageView) findViewById(R.id.img_bg_postfacebook); wait_layout = (LinearLayout) findViewById(R.id.layout_wait); jumpCard = (ImageView) findViewById(R.id.img_jump_card1_save); btn_share.setOnClickListener(this); btn_back.setOnClickListener(this); btn_help.setOnClickListener(this); } void getExtra() { Intent intent = getIntent(); Bundle bundle = intent.getExtras(); deckId = bundle.getInt("deckId"); number_of_card = bundle.getInt("number_of_card"); cardBean1 = bundle.getParcelable("cardBean1"); cardBean2 = bundle.getParcelable("cardBean2"); cardBean3 = bundle.getParcelable("cardBean3"); cardBean4 = bundle.getParcelable("cardBean4"); } private Handler handlerLoadImage = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: card1.setImageDrawable((Drawable) msg.obj); break; case 2: card2.setImageDrawable((Drawable) msg.obj); break; case 3: card3.setImageDrawable((Drawable) msg.obj); break; case 4: card4.setImageDrawable((Drawable) msg.obj); break; case 5: bg_layout.setBackgroundDrawable((Drawable) msg.obj); break; default: break; } }; }; void loadImage() { if (deckId == 999) { bg_layout.setImageResource(R.drawable.bg999); } else // Load BackGround image new ThreadLoadImage(this, handlerLoadImage, ConstantValue.getPatchCardData(this) + "Card_" + convertIdToStringId(deckId) + "/en_bg" + convertIdToStringId(deckId) + ".jpg", bg_layout, 5).start(); // load card1 loadCard1(); // Load card 2,3,4 switch (number_of_card) { case 3: loadCard2(); loadCard3(); break; case 4: loadCard2(); loadCard3(); loadCard4(); break; default: break; } // Load Jump Card findViewById(R.id.img_jump_card1_save).setVisibility( cardBean1.isJump ? View.VISIBLE : View.INVISIBLE); findViewById(R.id.img_jump_card2_save).setVisibility( cardBean2.isJump ? View.VISIBLE : View.INVISIBLE); findViewById(R.id.img_jump_card3_save).setVisibility( cardBean3.isJump ? View.VISIBLE : View.INVISIBLE); findViewById(R.id.img_jump_card4_save).setVisibility( cardBean4.isJump ? View.VISIBLE : View.INVISIBLE); } // Load card1 void loadCard1() { new ThreadLoadImage(this, handlerLoadImage, getCardPatchByCardId(cardBean1), card1, 1).start(); } void loadCard2() { new ThreadLoadImage(this, handlerLoadImage, getCardPatchByCardId(cardBean2), card2, 2).start(); card2.setVisibility(View.VISIBLE); } void loadCard3() { new ThreadLoadImage(this, handlerLoadImage, getCardPatchByCardId(cardBean3), card3, 3).start(); card3.setVisibility(View.VISIBLE); } void loadCard4() { new ThreadLoadImage(this, handlerLoadImage, getCardPatchByCardId(cardBean4), card4, 4).start(); card4.setVisibility(View.VISIBLE); } String getCardPatchByCardId(CardBean cardBean) { return ConstantValue.getPatchCardData(this) + "Card_" + convertIdToStringId(cardBean.deckId) + "/X3/en_c" + convertIdToStringId(cardBean.deckId) + convertIdToStringId(cardBean.cardId) + ".png"; } String convertIdToStringId(int id) { return id < 10 ? "0" + id : "" + id; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btn_postfacebook: KeyboardHelper.hideSoftKeyboard(this); String status = edit_status.getText().toString(); if (status.matches("")) { showDialogCancelPost(); return; } if (NetworkUtils.isNetworkConnected(this)) { if (this.session.isOpened()) { postToFacebook(); } else { this.session = createSession(); StatusCallback callback = new StatusCallback() { public void call(Session session, SessionState state, Exception exception) { if (state.isOpened()) { postToFacebook(); } else { if (state.isClosed()) { Log.e("StatusCallback", session.toString()); } } } }; this.session .openForPublish(new Session.OpenRequest(this) .setCallback(callback) .setPermissions(PERMISSIONS) .setLoginBehavior( SessionLoginBehavior.SUPPRESS_SSO)); } } else { showDialogSetting(); } break; case R.id.btnBack_postfacebook: if (postBitmap != null) { postBitmap.recycle(); } setResult(RESULT_CANCELED); finish(); break; case R.id.btnhelp_postfacebook: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 11); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; default: break; } } void gotoCardDetail(CardBean cardBean) { Intent intent = new Intent(this, CardDetailActivity.class); intent.putExtra("deckId", cardBean.deckId); intent.putExtra("cardId", cardBean.cardId); startActivityForResult(intent, ConstantValue.SAVE_HISTORY_ACTIVITY); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } /** * Lấy phiên kết nối của facebook * * @return */ private Session createSession() { Session activeSession = Session.getActiveSession(); if (activeSession == null || activeSession.getState().isClosed()) { activeSession = new Session.Builder(this).setApplicationId( this.getResources().getString(R.string.app_id)).build(); Session.setActiveSession(activeSession); } return activeSession; } void showDialogCancelPost() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView txtTitle = new TextView(this); txtTitle.setGravity(Gravity.CENTER); txtTitle.setTextColor(Color.WHITE); txtTitle.setText("Error"); txtTitle.setTextSize(20); builder.setCustomTitle(txtTitle); builder.setMessage("Please input some caption for image"); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.show(); } /** * post history lên facebook */ private void postToFacebook() { if (session != null) { // Check for publish permissions List<String> permissions = session.getPermissions(); if (!isSubsetOf(PERMISSIONS, permissions)) { pendingPublishReauthorization = true; Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest( this, PERMISSIONS); session.requestNewPublishPermissions(newPermissionsRequest); return; } Request.Callback postPhotoCallback = new Request.Callback() { @Override public void onCompleted(Response response) { // TODO Auto-generated method stub Log.e("postToFacebook", response.toString()); if (response.getError() == null) { // Tell the user success! Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); } setWaitScreen(false); } }; setWaitScreen(true); if (postBitmap == null) { postBitmap = createPostImage(); } Request postPhoto = Request.newUploadPhotoRequest(session, postBitmap, postPhotoCallback); Bundle params = postPhoto.getParameters(); params.putString("message", edit_status.getText().toString()); postPhoto.executeAsync(); } } /** * kiểm tra quyền login facebook * * @param subset * @param superset * @return */ private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) { for (String string : subset) { if (!superset.contains(string)) { return false; } } return true; } private static final int IMAGE_SPACE = 15; private Bitmap createPostImage() { if (number_of_card >= 1) { int itemWidth = ((BitmapDrawable) card1.getDrawable()).getBitmap() .getWidth(); int itemHeight = ((BitmapDrawable) card1.getDrawable()).getBitmap() .getHeight(); int bitmapWidth = itemWidth * number_of_card + IMAGE_SPACE * (number_of_card + 1); Bitmap postBitmap = Bitmap.createBitmap(bitmapWidth, itemHeight + IMAGE_SPACE, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(postBitmap); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setDither(true); canvas.drawColor(Color.WHITE); if (number_of_card == 1) { canvas.drawBitmap( ((BitmapDrawable) card1.getDrawable()).getBitmap(), IMAGE_SPACE, 0, paint); } else if (number_of_card == 2) { canvas.drawBitmap( ((BitmapDrawable) card1.getDrawable()).getBitmap(), IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card2.getDrawable()).getBitmap(), itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } else if (number_of_card == 3) { canvas.drawBitmap( ((BitmapDrawable) card1.getDrawable()).getBitmap(), IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card2.getDrawable()).getBitmap(), itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card3.getDrawable()).getBitmap(), itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } else if (number_of_card == 4) { canvas.drawBitmap( ((BitmapDrawable) card1.getDrawable()).getBitmap(), IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card2.getDrawable()).getBitmap(), itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card3.getDrawable()).getBitmap(), itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card4.getDrawable()).getBitmap(), itemWidth + itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } if (cardBean1.isJump) { canvas.drawBitmap( ((BitmapDrawable) jumpCard.getDrawable()).getBitmap(), 0, 0, paint); } if (cardBean2.isJump && number_of_card > 1) { canvas.drawBitmap( ((BitmapDrawable) jumpCard.getDrawable()).getBitmap(), itemWidth + IMAGE_SPACE, 0, paint); } if (cardBean3.isJump && number_of_card > 2) { canvas.drawBitmap( ((BitmapDrawable) jumpCard.getDrawable()).getBitmap(), itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } if (cardBean4.isJump && number_of_card > 3) { canvas.drawBitmap( ((BitmapDrawable) jumpCard.getDrawable()).getBitmap(), itemWidth + itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } return postBitmap; } else { return null; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data); } // Tắt/bật màn hình chờ void setWaitScreen(boolean set) { wait_layout.setVisibility(set ? View.VISIBLE : View.GONE); edit_status.setEnabled(set ? false : true); btn_back.setClickable(set ? false : true); btn_help.setClickable(set ? false : true); btn_share.setClickable(set ? false : true); } void showDialogSetting() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); myMsg.setText("No internet connection"); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage("Please check your setting network"); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); } }); AlertDialog dialog = builder.show(); } @Override public void onBackPressed() { // TODO Auto-generated method stub overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); if (postBitmap != null) { postBitmap.recycle(); } super.onBackPressed(); } }
Java
package net.cardgame.orcalecard; import java.util.List; import android.app.Activity; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class GalleryAdapter extends BaseAdapter { private Activity activity; private List<String> listPaths; public GalleryLoader imageLoader; int index = 0; private int width = 0; public GalleryAdapter(Activity a, List<String> list, boolean isSpecial) { activity = a; listPaths = list; imageLoader = new GalleryLoader(activity.getApplicationContext(), isSpecial); DisplayMetrics displaymetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay() .getMetrics(displaymetrics); width = displaymetrics.widthPixels; } public int getCount() { return listPaths.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } static class ViewHolder { TextView textView; ImageView imageview; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(activity); imageLoader.DisplayImage(listPaths.get(position), imageView); if (width < 500) // Galaxy S2 imageView.setLayoutParams(new GalleryFlow.LayoutParams(280, 440)); else { // Galaxy Nexus imageView.setLayoutParams(new GalleryFlow.LayoutParams(350, 620)); } return imageView; } }
Java
package net.cardgame.orcalecard; import java.io.IOException; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.animation.AnimationFactory; import net.cardgame.oraclecard.animation.AnimationFactory.FlipDirection; import net.cardgame.oraclecard.common.ImageClickable; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.KeyboardHelper; import uk.co.senab.bitmapcache.BitmapLruCache; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.MediaPlayer; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaPlayer.OnSeekCompleteListener; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.ViewFlipper; public class ResultActivity extends Activity implements OnClickListener { int deckId, number_of_card; ImageView img_card1_bg, img_card2_bg, img_card3_bg, img_card4_bg, img_bg, btnSaveHistory; ViewFlipper fliper1, fliper2, fliper3, fliper4; EditText txtQuestion; SettingApp setting; boolean flag = false; CardBean cardBean1, cardBean2, cardBean3, cardBean4; ImageClickable img_card1, img_card2, img_card3, img_card4; boolean performFlipCard = true; String strQuestion; MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); if (savedInstanceState != null) { performFlipCard = false; flag = true; } getData(); if (number_of_card == 1) setContentView(R.layout.result_one_card); else setContentView(R.layout.result_activity_layout); initView(); loadImageResource(); } void getData() { // get bundle setting = ConstantValue.getSettingApp(this); Bundle bundle = getIntent().getExtras(); number_of_card = bundle.getInt("number_of_card"); cardBean1 = bundle.getParcelable("cardBean1"); cardBean2 = bundle.getParcelable("cardBean2"); cardBean3 = bundle.getParcelable("cardBean3"); cardBean4 = bundle.getParcelable("cardBean4"); deckId = bundle.getInt("deckId"); strQuestion = bundle.getString("text_input"); } void initView() { setupUI(findViewById(R.id.parent)); findViewById(R.id.btnreplay_result).setOnClickListener(this); findViewById(R.id.btn_replace_1_3_result).setOnClickListener(this); findViewById(R.id.btn_goto_toppage_result).setOnClickListener(this); btnSaveHistory = (ImageView) findViewById(R.id.btn_share_facebook_result); btnSaveHistory.setOnClickListener(ResultActivity.this); findViewById(R.id.btnsetting_result).setOnClickListener(this); img_card1 = (ImageClickable) findViewById(R.id.img_card1_result); img_card2 = (ImageClickable) findViewById(R.id.img_card2_result); img_card3 = (ImageClickable) findViewById(R.id.img_card3_result); img_card4 = (ImageClickable) findViewById(R.id.img_card4_result); img_card1_bg = (ImageView) findViewById(R.id.img_card100_result); img_card2_bg = (ImageView) findViewById(R.id.img_card200_result); img_card3_bg = (ImageView) findViewById(R.id.img_card300_result); img_card4_bg = (ImageView) findViewById(R.id.img_card400_result); img_bg = (ImageView) findViewById(R.id.bg_result); fliper1 = (ViewFlipper) findViewById(R.id.viewFlipper1); fliper2 = (ViewFlipper) findViewById(R.id.viewFlipper2); fliper3 = (ViewFlipper) findViewById(R.id.viewFlipper3); fliper4 = (ViewFlipper) findViewById(R.id.viewFlipper4); txtQuestion = (EditText) findViewById(R.id.txtquestion_result); if (strQuestion != null) txtQuestion.setText(strQuestion); } /** * Load all image resource */ void loadImageResource() { // Load background image if (deckId == 999) { img_bg.setImageResource(R.drawable.bg999); img_card1_bg.setImageResource(R.drawable.c99900); switch (number_of_card) { case 3: img_card2_bg.setImageResource(R.drawable.c99900); img_card3_bg.setImageResource(R.drawable.c99900); break; case 4: img_card2_bg.setImageResource(R.drawable.c99900); img_card3_bg.setImageResource(R.drawable.c99900); img_card4_bg.setImageResource(R.drawable.c99900); break; default: break; } } else { new ThreadLoadImage(this, handlerLoadImage, ConstantValue.getPathBackgroundByDeckId(this, deckId), img_bg, 5).start(); String path = ConstantValue.getPathDeckImage(this, deckId, "d"); // Load card background (card00) new ThreadLoadImage(this, handlerLoadImage, ConstantValue.getPathDeckImage(this, deckId, "d"), img_card1_bg, 6).start(); } // Load card1,2,3,4 switch (number_of_card) { case 1: loadCard1(); break; case 3: loadCard1(); loadCard2(); loadCard3(); break; case 4: loadCard1(); loadCard2(); loadCard3(); loadCard4(); break; default: break; } } private Handler handlerLoadImage = new Handler() { private boolean finished1 = false, finished2 = false, finished3 = false, finished4 = false, finished5 = false, finished6 = false; public void handleMessage(Message msg) { if (msg.obj == null) return; if (deckId == 999) { finished5 = true; finished6 = true; } switch (msg.what) { case 1: finished1 = true; Drawable result1 = ((Drawable) msg.obj); Bitmap bitmap1 = ((BitmapDrawable) result1).getBitmap(); if (!bitmap1.isRecycled()) img_card1.setImageBitmap(bitmap1); fliper1.setDisplayedChild(0); break; case 2: finished2 = true; Drawable result2 = ((Drawable) msg.obj); Bitmap bitmap2 = ((BitmapDrawable) result2).getBitmap(); if (!bitmap2.isRecycled()) img_card2.setImageBitmap(bitmap2); fliper2.setDisplayedChild(0); break; case 3: finished3 = true; Drawable result3 = ((Drawable) msg.obj); Bitmap bitmap3 = ((BitmapDrawable) result3).getBitmap(); if (!bitmap3.isRecycled()) img_card3.setImageBitmap(bitmap3); fliper3.setDisplayedChild(0); break; case 4: finished4 = true; Drawable result4 = ((Drawable) msg.obj); Bitmap bitmap4 = ((BitmapDrawable) result4).getBitmap(); if (!bitmap4.isRecycled()) img_card4.setImageBitmap(bitmap4); fliper4.setDisplayedChild(0); break; case 5: finished5 = true; Drawable result5 = ((Drawable) msg.obj); Bitmap bitmap5 = ((BitmapDrawable) result5).getBitmap(); if (!bitmap5.isRecycled()) img_bg.setImageBitmap(bitmap5); break; case 6: finished6 = true; Drawable result6 = ((Drawable) msg.obj); Bitmap bitmap6 = ((BitmapDrawable) result6).getBitmap(); if (!bitmap6.isRecycled()) { if (number_of_card == 4) { img_card2_bg.setImageBitmap(bitmap6); img_card3_bg.setImageBitmap(bitmap6); img_card4_bg.setImageBitmap(bitmap6); } else if (number_of_card == 3) { img_card2_bg.setImageBitmap(bitmap6); img_card3_bg.setImageBitmap(bitmap6); } img_card1_bg.setImageBitmap(bitmap6); } break; default: break; } boolean loadFinished = false; if (number_of_card == 1) loadFinished = finished1 && finished5 && finished6; else if (number_of_card == 3) loadFinished = finished1 && finished2 && finished3 && finished5 && finished6; else if (number_of_card == 4) loadFinished = finished1 && finished2 && finished3 && finished4 && finished5 && finished6; if (loadFinished) { // perform Flip card if (performFlipCard) { if (setting.sound) playMusic(); AnimationFactory.flipTransition(fliper1, FlipDirection.RIGHT_LEFT); new ThreadFlipCard(1).start(); } else { fliper1.setDisplayedChild(1); fliper2.setDisplayedChild(1); fliper3.setDisplayedChild(1); fliper4.setDisplayedChild(1); img_card1.setOnClickListener(ResultActivity.this); img_card2.setOnClickListener(ResultActivity.this); img_card3.setOnClickListener(ResultActivity.this); img_card4.setOnClickListener(ResultActivity.this); } } }; }; class ThreadFlipCard extends Thread { int what; ThreadFlipCard(int what) { this.what = what; } @Override public void run() { // TODO Auto-generated method stub super.run(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handlerFlipCard.sendEmptyMessage(what); } } Handler handlerFlipCard = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: img_card1.setOnClickListener(ResultActivity.this); img_card1.setBackgroundResource(R.drawable.shadow_card); if (number_of_card > 1) { if (setting.sound) playMusic(); AnimationFactory.flipTransition(fliper2, FlipDirection.RIGHT_LEFT); new ThreadFlipCard(2).start(); } else { flag = true; if (mediaPlayer != null) mediaPlayer.release(); } break; case 2: img_card2.setOnClickListener(ResultActivity.this); img_card2.setBackgroundResource(R.drawable.shadow_card); if (setting.sound) playMusic(); AnimationFactory.flipTransition(fliper3, FlipDirection.RIGHT_LEFT); new ThreadFlipCard(3).start(); break; case 3: img_card3.setOnClickListener(ResultActivity.this); img_card3.setBackgroundResource(R.drawable.shadow_card); if (number_of_card > 3) { if (setting.sound) playMusic(); AnimationFactory.flipTransition(fliper4, FlipDirection.RIGHT_LEFT); new ThreadFlipCard(4).start(); } else { flag = true; if (mediaPlayer != null) mediaPlayer.release(); } break; case 4: img_card4.setOnClickListener(ResultActivity.this); img_card4.setBackgroundResource(R.drawable.shadow_card); flag = true; if (mediaPlayer != null) mediaPlayer.release(); break; default: break; } }; }; void loadCard1() { String path = ConstantValue.getPathCardDetail(this, cardBean1.deckId, cardBean1.cardId, number_of_card == 1 ? ConstantValue.X2 : ConstantValue.X3); img_card1.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, img_card1, 1).start(); img_card1_bg.setVisibility(View.VISIBLE); img_card1.setVisibility(View.VISIBLE); if (cardBean1.isJump) findViewById(R.id.img_jump_card1_result) .setVisibility(View.VISIBLE); if (number_of_card != 1) findViewById(R.id.img_title_card1_result).setVisibility( View.VISIBLE); } void loadCard2() { String path = ConstantValue.getPathCardDetail(this, cardBean2.deckId, cardBean2.cardId, ConstantValue.X3); img_card2.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, img_card2, 2).start(); img_card2_bg.setVisibility(View.VISIBLE); img_card2.setVisibility(View.VISIBLE); findViewById(R.id.img_title_card2_result).setVisibility(View.VISIBLE); if (cardBean2.isJump) { findViewById(R.id.img_jump_card2_result) .setVisibility(View.VISIBLE); } } void loadCard3() { String path = ConstantValue.getPathCardDetail(this, cardBean3.deckId, cardBean3.cardId, ConstantValue.X3); img_card3.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, img_card3, 3).start(); img_card3_bg.setVisibility(View.VISIBLE); img_card3.setVisibility(View.VISIBLE); findViewById(R.id.img_title_card3_result).setVisibility(View.VISIBLE); if (cardBean3.isJump) findViewById(R.id.img_jump_card3_result) .setVisibility(View.VISIBLE); } void loadCard4() { String path = ConstantValue.getPathCardDetail(this, cardBean4.deckId, cardBean4.cardId, ConstantValue.X3); img_card4.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, img_card4, 4).start(); img_card4_bg.setVisibility(View.VISIBLE); img_card4.setVisibility(View.VISIBLE); findViewById(R.id.img_title_card4_result).setVisibility(View.VISIBLE); if (cardBean4.isJump) findViewById(R.id.img_jump_card4_result) .setVisibility(View.VISIBLE); } @Override public void onClick(View v) { // TODO Auto-generated method stub if (!flag) return; switch (v.getId()) { case R.id.img_card1_result: flag = false; gotoCardDetail(cardBean1); break; case R.id.img_card2_result: flag = false; gotoCardDetail(cardBean2); break; case R.id.img_card3_result: flag = false; gotoCardDetail(cardBean3); break; case R.id.img_card4_result: flag = false; gotoCardDetail(cardBean4); break; case R.id.btnreplay_result: goBack(); break; case R.id.btn_replace_1_3_result: // go to card deck activity goCardDeck(); break; case R.id.btn_goto_toppage_result: clearCacheBefore(); goToppage(); break; case R.id.btnsetting_result: flag = false; Intent intent2 = new Intent(this, SettingActiviy.class); startActivityForResult(intent2, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_share_facebook_result: flag = false; gotoSaveHistory(); break; default: break; } } void gotoSaveHistory() { Intent intent = new Intent(this, SaveHistoryActivity.class); intent.putExtra("number_of_card", number_of_card); intent.putExtra("deckId", deckId); intent.putExtra("cardBean1", cardBean1); intent.putExtra("cardBean2", cardBean2); intent.putExtra("cardBean3", cardBean3); intent.putExtra("cardBean4", cardBean4); intent.putExtra("question", txtQuestion.getText().toString()); startActivityForResult(intent, ConstantValue.RESULT_ACTIVITY); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } void gotoCardDetail(CardBean cardBean) { Intent intentGotoCardDetail = new Intent(this, CardDetailActivity.class); intentGotoCardDetail.putExtra("deckId", cardBean.deckId); intentGotoCardDetail.putExtra("cardId", cardBean.cardId); startActivityForResult(intentGotoCardDetail, ConstantValue.RESULT_ACTIVITY); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); flag = true; setting = ConstantValue.getSettingApp(this); } public void setupUI(View view) { // Set up touch listener for non-text box views to hide keyboard. if (!(view instanceof EditText)) { view.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { v.requestFocus(); KeyboardHelper.hideSoftKeyboard(ResultActivity.this); return false; } }); } // If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView); } } } private void playMusic() { if (mediaPlayer == null) { mediaPlayer = MediaPlayer.create(this, R.raw.se_card_flip); mediaPlayer.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub mp.start(); } }); } else { mediaPlayer.seekTo(0); mediaPlayer.start(); } } @Override protected void onDestroy() { // TODO Auto-generated method stub if (mediaPlayer != null) { mediaPlayer.release(); } ClearCache(); super.onDestroy(); } private void ClearCache() { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean1.deckId, cardBean1.cardId, number_of_card == 1 ? ConstantValue.X2 : ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean2.deckId, cardBean2.cardId, ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean3.deckId, cardBean3.cardId, ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean4.deckId, cardBean4.cardId, ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean1.deckId, cardBean1.cardId, ConstantValue.X1)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean2.deckId, cardBean2.cardId, ConstantValue.X1)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean3.deckId, cardBean3.cardId, ConstantValue.X1)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean4.deckId, cardBean4.cardId, ConstantValue.X1)); if (deckId == 999) { String backgoundCard1 = ConstantValue.getPathBackgroundByDeckId( this, cardBean1.deckId); String backgoundCard2 = ConstantValue.getPathBackgroundByDeckId( this, cardBean1.deckId); String backgoundCard3 = ConstantValue.getPathBackgroundByDeckId( this, cardBean1.deckId); String backgoundCard4 = ConstantValue.getPathBackgroundByDeckId( this, cardBean1.deckId); cache.removeFromMemory(backgoundCard1); cache.removeFromMemory(backgoundCard2); cache.removeFromMemory(backgoundCard3); cache.removeFromMemory(backgoundCard4); } } @Override public void onBackPressed() { // TODO Auto-generated method stub goBack(); } void goBack() { Intent intent = new Intent(this, GetCardActivity.class); Bundle bundle = getIntent().getExtras(); if (number_of_card != 1) { number_of_card = setting.adviseCard ? 4 : 3; bundle.putInt("number_of_card", number_of_card); } bundle.remove("cardBean1"); bundle.remove("cardBean2"); bundle.remove("cardBean3"); bundle.remove("cardBean4"); bundle.remove("text_input"); intent.putExtras(bundle); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } void goToppage() { Intent intent = new Intent(this, TopPageActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } void goCardDeck() { Intent intent = new Intent(this, CardDeckActivity.class); Bundle bundle = getIntent().getExtras(); bundle.remove("cardBean1"); bundle.remove("cardBean2"); bundle.remove("cardBean3"); bundle.remove("cardBean4"); bundle.remove("text_input"); intent.putExtras(bundle); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } private void clearCacheBefore() { if (deckId != 999) { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "s")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "p")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "m")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "d")); cache.removeFromMemory(ConstantValue.getPathBackgroundByDeckId( this, deckId)); } } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * 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 net.cardgame.oraclecard.animation; import java.util.HashMap; import java.util.Random; import android.graphics.Bitmap; /** * This class represents a single Droidflake, with properties representing its * size, rotation, location, and speed. */ public class Flake { // These are the unique properties of any flake: its size, rotation, speed, // location, and its underlying Bitmap object float x, y; float rotation; float speed; float rotationSpeed; int width, height; Bitmap bitmap; int move; boolean moveLeft; // This map stores pre-scaled bitmaps according to the width. No reason to // create // new bitmaps for sizes we've already seen. static HashMap<Integer, Bitmap> bitmapMap = new HashMap<Integer, Bitmap>(); /** * Creates a new droidflake in the given xRange and with the given bitmap. * Parameters of location, size, rotation, and speed are randomly * determined. */ static Flake createFlake(float xRange, Bitmap originalBitmap, int width, int x) { Flake flake = new Flake(); // Size each flake with a width between 5 and 55 and a proportional // height flake.width = width; flake.height = width; // Position the flake horizontally between the left and right of the // range Random random = new Random(); flake.x = random.nextInt((int) xRange - flake.width); if (flake.x > xRange / 2) flake.moveLeft = true; else flake.moveLeft = false; // Position the flake vertically slightly off the top of the display flake.y = 0 - (flake.height); // Each flake travels at 50-200 pixels per second flake.speed = 50; // Flakes start at -90 to 90 degrees rotation, and rotate between -45 // and 45 // degrees per second flake.rotation = (float) Math.random() * 180 - 90; flake.rotationSpeed = (float) Math.random() * 90 - 45; // Get the cached bitmap for this size if it exists, otherwise create // and cache one flake.bitmap = bitmapMap.get(x); if (flake.bitmap == null) { flake.bitmap = Bitmap.createScaledBitmap(originalBitmap, (int) flake.width, (int) flake.height, true); bitmapMap.put(x, flake.bitmap); } return flake; } }
Java
/** * Copyright (c) 2012 Ephraim Tekle genzeb@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @author Ephraim A. Tekle * */ package net.cardgame.oraclecard.animation; import android.graphics.Camera; import android.graphics.Matrix; import android.view.animation.Animation; import android.view.animation.Transformation; /** * This class extends Animation to support a 3D flip view transition animation. Two instances of this class is * required: one for the "from" view and another for the "to" view. * * NOTE: use {@link AnimationFactory} to use this class. * * @author Ephraim A. Tekle * */ public class FlipAnimation extends Animation { private final float mFromDegrees; private final float mToDegrees; private final float mCenterX; private final float mCenterY; private Camera mCamera; private final ScaleUpDownEnum scaleType; /** * How much to scale up/down. The default scale of 75% of full size seems optimal based on testing. Feel free to experiment away, however. */ public static final float SCALE_DEFAULT = 0.75f; private float scale; /** * Constructs a new {@code FlipAnimation} object.Two {@code FlipAnimation} objects are needed for a complete transition b/n two views. * * @param fromDegrees the start angle in degrees for a rotation along the y-axis, i.e. in-and-out of the screen, i.e. 3D flip. This should really be multiple of 90 degrees. * @param toDegrees the end angle in degrees for a rotation along the y-axis, i.e. in-and-out of the screen, i.e. 3D flip. This should really be multiple of 90 degrees. * @param centerX the x-axis value of the center of rotation * @param centerY the y-axis value of the center of rotation * @param scale to get a 3D effect, the transition views need to be zoomed (scaled). This value must be b/n (0,1) or else the default scale {@link #SCALE_DEFAULT} is used. * @param scaleType flip view transition is broken down into two: the zoom-out of the "from" view and the zoom-in of the "to" view. This parameter is used to determine which is being done. See {@link ScaleUpDownEnum}. */ public FlipAnimation(float fromDegrees, float toDegrees, float centerX, float centerY, float scale, ScaleUpDownEnum scaleType) { mFromDegrees = fromDegrees; mToDegrees = toDegrees; mCenterX = centerX; mCenterY = centerY; this.scale = (scale<=0||scale>=1)?SCALE_DEFAULT:scale; this.scaleType = scaleType==null?ScaleUpDownEnum.SCALE_CYCLE:scaleType; } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); mCamera = new Camera(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { final float fromDegrees = mFromDegrees; float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime); final float centerX = mCenterX; final float centerY = mCenterY; final Camera camera = mCamera; final Matrix matrix = t.getMatrix(); camera.save(); camera.rotateY(degrees); camera.getMatrix(matrix); camera.restore(); matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY); matrix.preScale(scaleType.getScale(scale, interpolatedTime), scaleType.getScale(scale, interpolatedTime), centerX, centerY); } /** * This enumeration is used to determine the zoom (or scale) behavior of a {@link FlipAnimation}. * * @author Ephraim A. Tekle * */ public static enum ScaleUpDownEnum { /** * The view will be scaled up from the scale value until it's at 100% zoom level (i.e. no zoom). */ SCALE_UP, /** * The view will be scaled down starting at no zoom (100% zoom level) until it's at a specified zoom level. */ SCALE_DOWN, /** * The view will cycle through a zoom down and then zoom up. */ SCALE_CYCLE, /** * No zoom effect is applied. */ SCALE_NONE; /** * The intermittent zoom level given the current or desired maximum zoom level for the specified iteration * * @param max the maximum desired or current zoom level * @param iter the iteration (from 0..1). * @return the current zoom level */ public float getScale(float max, float iter) { switch(this) { case SCALE_UP: return max + (1-max)*iter; case SCALE_DOWN: return 1 - (1-max)*iter; case SCALE_CYCLE: { final boolean halfWay = (iter > 0.5); if (halfWay) { return max + (1-max)*(iter-0.5f)*2; } else { return 1 - (1-max)*(iter*2); } } default: return 1; } } } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * 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 net.cardgame.oraclecard.animation; import java.util.ArrayList; import java.util.Random; import jp.jma.oraclecard.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.view.View; import com.nineoldandroids.animation.ValueAnimator; import com.nineoldandroids.animation.ValueAnimator.AnimatorUpdateListener; /** * This class is the custom view where all of the Droidflakes are drawn. This * class has all of the logic for adding, subtracting, and rendering * Droidflakes. */ public class FlakeView extends View { Bitmap droid; // The bitmap that all flakes use Bitmap droid2; int numFlakes = 0; // Current number of flakes ArrayList<Flake> flakes = new ArrayList<Flake>(); // List of current flakes // Animator used to drive all separate flake animations. Rather than have // potentially // hundreds of separate animators, we just use one and then update all // flakes for each // frame of that single animation. ValueAnimator animator = ValueAnimator.ofFloat(0, 1); long startTime, prevTime; // Used to track elapsed time for animations and // fps int frames = 0; // Used to track frames per second Matrix m = new Matrix(); // Matrix used to translate/rotate each flake // during rendering /** * Constructor. Create objects used throughout the life of the View: the * Paint and the animator */ public FlakeView(Context context) { super(context); // This listener is where the action is for the flak animations. Every // frame of the // animation, we calculate the elapsed time and update every flake's // position and rotation // according to its speed. animator.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator arg0) { long nowTime = System.currentTimeMillis(); float secs = (float) (nowTime - prevTime) / 1000f; prevTime = nowTime; for (Flake flake : flakes) { if (flake.move == 1000) { flake.moveLeft = !flake.moveLeft; flake.move = 0; } else { flake.move++; } if (flake.moveLeft) { flake.x -= (flake.speed * secs); } else { flake.x += (flake.speed * secs); } if (flake.x < 0 - flake.width / 2) { // If a flake falls off the bottom, send it back to the // top flake.move = 0; flake.moveLeft = false; } else if (flake.x > getWidth() - flake.width / 2) { flake.move = 0; flake.moveLeft = true; } flake.y += Math.random() * (flake.speed * secs); if (flake.y > getHeight()) { // If a flake falls off the bottom, send it back to the // top flake.y = 0 - flake.height; Random random = new Random(); flake.x = random .nextInt((int) getWidth() - flake.width); } flake.rotation = flake.rotation + (flake.rotationSpeed * secs); } // Force a redraw to see the flakes in their new positions and // orientations invalidate(); } }); animator.setRepeatCount(ValueAnimator.INFINITE); animator.setDuration(2000); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Reset list of droidflakes, then restart it with 8 flakes flakes.clear(); numFlakes = 2; final int widthFeather = getResources().getInteger( R.integer.width_feather); droid = BitmapFactory.decodeResource(getResources(), R.drawable.feather01); flakes.add(Flake.createFlake(getWidth(), droid, widthFeather, getWidth() + widthFeather)); Thread thread = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } droid2 = BitmapFactory.decodeResource(getResources(), R.drawable.feather02); flakes.add(Flake.createFlake(getWidth(), droid2, widthFeather, -widthFeather)); } }); thread.start(); // Cancel animator in case it was already running animator.cancel(); // Set up fps tracking and start the animation startTime = System.currentTimeMillis(); prevTime = startTime; frames = 0; animator.start(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // For each flake: back-translate by half its size (this allows it to // rotate around its center), // rotate by its current rotation, translate by its location, then draw // its bitmap for (Flake flake : flakes) { m.setTranslate(-flake.width / 2, -flake.height / 2); m.postRotate(flake.rotation); m.postTranslate(flake.width / 2 + flake.x, flake.height / 2 + flake.y); canvas.drawBitmap(flake.bitmap, m, null); } } public void pause() { // Make sure the animator's not spinning in the background when the // activity is paused. animator.cancel(); } public void resume() { animator.start(); } }
Java
/** * Copyright (c) 2012 Ephraim Tekle genzeb@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @author Ephraim A. Tekle * */ package net.cardgame.oraclecard.animation; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.TranslateAnimation; import android.widget.ViewAnimator; /** * This class contains methods for creating {@link Animation} objects for some of the most common animation, including a 3D flip animation, {@link FlipAnimation}. * Furthermore, utility methods are provided for initiating fade-in-then-out and flip animations. * * @author Ephraim A. Tekle * */ public class AnimationFactory { /** * The {@code FlipDirection} enumeration defines the most typical flip view transitions: left-to-right and right-to-left. {@code FlipDirection} is used during the creation of {@link FlipAnimation} animations. * * @author Ephraim A. Tekle * */ public static enum FlipDirection { LEFT_RIGHT, RIGHT_LEFT; public float getStartDegreeForFirstView() { return 0; } public float getStartDegreeForSecondView() { switch(this) { case LEFT_RIGHT: return -90; case RIGHT_LEFT: return 90; default: return 0; } } public float getEndDegreeForFirstView() { switch(this) { case LEFT_RIGHT: return 90; case RIGHT_LEFT: return -90; default: return 0; } } public float getEndDegreeForSecondView() { return 0; } public FlipDirection theOtherDirection() { switch(this) { case LEFT_RIGHT: return RIGHT_LEFT; case RIGHT_LEFT: return LEFT_RIGHT; default: return null; } } }; /** * Create a pair of {@link FlipAnimation} that can be used to flip 3D transition from {@code fromView} to {@code toView}. A typical use case is with {@link ViewAnimator} as an out and in transition. * * NOTE: Avoid using this method. Instead, use {@link #flipTransition}. * * @param fromView the view transition away from * @param toView the view transition to * @param dir the flip direction * @param duration the transition duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return */ public static Animation[] flipAnimation(final View fromView, final View toView, FlipDirection dir, long duration, Interpolator interpolator) { Animation[] result = new Animation[2]; float centerX; float centerY; centerX = fromView.getWidth() / 2.0f; centerY = fromView.getHeight() / 2.0f; Animation outFlip= new FlipAnimation(dir.getStartDegreeForFirstView(), dir.getEndDegreeForFirstView(), centerX, centerY, FlipAnimation.SCALE_DEFAULT, FlipAnimation.ScaleUpDownEnum.SCALE_DOWN); outFlip.setDuration(duration); outFlip.setFillAfter(true); outFlip.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); AnimationSet outAnimation = new AnimationSet(true); outAnimation.addAnimation(outFlip); result[0] = outAnimation; // Uncomment the following if toView has its layout established (not the case if using ViewFlipper and on first show) //centerX = toView.getWidth() / 2.0f; //centerY = toView.getHeight() / 2.0f; Animation inFlip = new FlipAnimation(dir.getStartDegreeForSecondView(), dir.getEndDegreeForSecondView(), centerX, centerY, FlipAnimation.SCALE_DEFAULT, FlipAnimation.ScaleUpDownEnum.SCALE_UP); inFlip.setDuration(duration); inFlip.setFillAfter(true); inFlip.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); inFlip.setStartOffset(duration); AnimationSet inAnimation = new AnimationSet(true); inAnimation.addAnimation(inFlip); result[1] = inAnimation; return result; } /** * Flip to the next view of the {@code ViewAnimator}'s subviews. A call to this method will initiate a {@link FlipAnimation} to show the next View. * If the currently visible view is the last view, flip direction will be reversed for this transition. * * @param viewAnimator the {@code ViewAnimator} * @param dir the direction of flip */ public static void flipTransition(final ViewAnimator viewAnimator, FlipDirection dir) { final View fromView = viewAnimator.getCurrentView(); final int currentIndex = viewAnimator.getDisplayedChild(); final int nextIndex = (currentIndex + 1)%viewAnimator.getChildCount(); final View toView = viewAnimator.getChildAt(nextIndex); Animation[] animc = AnimationFactory.flipAnimation(fromView, toView, (nextIndex < currentIndex?dir.theOtherDirection():dir), 500, null); viewAnimator.setOutAnimation(animc[0]); viewAnimator.setInAnimation(animc[1]); viewAnimator.showNext(); } ////////////// /** * Slide animations to enter a view from left. * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation inFromLeftAnimation(long duration, Interpolator interpolator) { Animation inFromLeft = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); inFromLeft.setDuration(duration); inFromLeft.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); //AccelerateInterpolator return inFromLeft; } /** * Slide animations to hide a view by sliding it to the right * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation outToRightAnimation(long duration, Interpolator interpolator) { Animation outtoRight = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); outtoRight.setDuration(duration); outtoRight.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return outtoRight; } /** * Slide animations to enter a view from right. * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation inFromRightAnimation(long duration, Interpolator interpolator) { Animation inFromRight = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); inFromRight.setDuration(duration); inFromRight.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return inFromRight; } /** * Slide animations to hide a view by sliding it to the left. * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation outToLeftAnimation(long duration, Interpolator interpolator) { Animation outtoLeft = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); outtoLeft.setDuration(duration); outtoLeft.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return outtoLeft; } /** * Slide animations to enter a view from top. * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation inFromTopAnimation(long duration, Interpolator interpolator) { Animation infromtop = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); infromtop.setDuration(duration); infromtop.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return infromtop; } /** * Slide animations to hide a view by sliding it to the top * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation outToTopAnimation(long duration, Interpolator interpolator) { Animation outtotop = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f ); outtotop.setDuration(duration); outtotop.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return outtotop; } /** * A fade animation that will fade the subject in by changing alpha from 0 to 1. * * @param duration the animation duration in milliseconds * @param delay how long to wait before starting the animation, in milliseconds * @return a fade animation * @see #fadeInAnimation(View, long) */ public static Animation fadeInAnimation(long duration, long delay) { Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new DecelerateInterpolator()); fadeIn.setDuration(duration); fadeIn.setStartOffset(delay); return fadeIn; } /** * A fade animation that will fade the subject out by changing alpha from 1 to 0. * * @param duration the animation duration in milliseconds * @param delay how long to wait before starting the animation, in milliseconds * @return a fade animation * @see #fadeOutAnimation(View, long) */ public static Animation fadeOutAnimation(long duration, long delay) { Animation fadeOut = new AlphaAnimation(1, 0); fadeOut.setInterpolator(new AccelerateInterpolator()); fadeOut.setStartOffset(delay); fadeOut.setDuration(duration); return fadeOut; } /** * A fade animation that will ensure the View starts and ends with the correct visibility * @param view the View to be faded in * @param duration the animation duration in milliseconds * @return a fade animation that will set the visibility of the view at the start and end of animation */ public static Animation fadeInAnimation(long duration, final View view) { Animation animation = fadeInAnimation(500, 0); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.VISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { view.setVisibility(View.GONE); } }); return animation; } /** * A fade animation that will ensure the View starts and ends with the correct visibility * @param view the View to be faded out * @param duration the animation duration in milliseconds * @return a fade animation that will set the visibility of the view at the start and end of animation */ public static Animation fadeOutAnimation(long duration, final View view) { Animation animation = fadeOutAnimation(500, 0); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.GONE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { view.setVisibility(View.VISIBLE); } }); return animation; } /** * Creates a pair of animation that will fade in, delay, then fade out * @param duration the animation duration in milliseconds * @param delay how long to wait after fading in the subject and before starting the fade out * @return a fade in then out animations */ public static Animation[] fadeInThenOutAnimation(long duration, long delay) { return new Animation[] {fadeInAnimation(duration,0), fadeOutAnimation(duration, duration+delay)}; } /** * Fades the view in. Animation starts right away. * @param v the view to be faded in */ public static void fadeOut(View v) { if (v==null) return; v.startAnimation(fadeOutAnimation(500, v)); } /** * Fades the view out. Animation starts right away. * @param v the view to be faded out */ public static void fadeIn(View v) { if (v==null) return; v.startAnimation(fadeInAnimation(500, v)); } /** * Fades the view in, delays the specified amount of time, then fades the view out * @param v the view to be faded in then out * @param delay how long the view will be visible for */ public static void fadeInThenOut(final View v, long delay) { if (v==null) return; v.setVisibility(View.VISIBLE); AnimationSet animation = new AnimationSet(true); Animation[] fadeInOut = fadeInThenOutAnimation(500,delay); animation.addAnimation(fadeInOut[0]); animation.addAnimation(fadeInOut[1]); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { v.setVisibility(View.GONE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { v.setVisibility(View.VISIBLE); } }); v.startAnimation(animation); } }
Java
// Copyright 2002, 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 net.cardgame.oraclecard.billingutils; /** * Exception thrown when encountering an invalid Base64 input character. * * @author nelson */ public class Base64DecoderException extends Exception { public Base64DecoderException() { super(); } public Base64DecoderException(String s) { super(s); } private static final long serialVersionUID = 1L; }
Java
/* Copyright (c) 2012 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 net.cardgame.oraclecard.billingutils; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import android.text.TextUtils; import android.util.Log; /** * Security-related methods. For a secure implementation, all of this code * should be implemented on a server that communicates with the * application on the device. For the sake of simplicity and clarity of this * example, this code is included here and is executed on the device. If you * must verify the purchases on the phone, you should obfuscate this code to * make it harder for an attacker to replace the code with stubs that treat all * purchases as verified. */ public class Security { private static final String TAG = "IABUtil/Security"; private static final String KEY_FACTORY_ALGORITHM = "RSA"; private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; /** * Verifies that the data was signed with the given signature, and returns * the verified purchase. The data is in JSON format and signed * with a private key. The data also contains the {@link PurchaseState} * and product ID of the purchase. * @param base64PublicKey the base64-encoded public key to use for verifying. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return false; } boolean verified = false; if (!TextUtils.isEmpty(signature)) { PublicKey key = Security.generatePublicKey(base64PublicKey); verified = Security.verify(key, signedData, signature); if (!verified) { Log.w(TAG, "signature does not match data."); return false; } } return true; } /** * Generates a PublicKey instance from a string containing the * Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IllegalArgumentException if encodedPublicKey is invalid */ public static PublicKey generatePublicKey(String encodedPublicKey) { try { byte[] decodedKey = Base64.decode(encodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { Log.e(TAG, "Invalid key specification."); throw new IllegalArgumentException(e); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); throw new IllegalArgumentException(e); } } /** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature * @return true if the data and signature match */ public static boolean verify(PublicKey publicKey, String signedData, String signature) { Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { Log.e(TAG, "Signature verification failed."); return false; } return true; } catch (NoSuchAlgorithmException e) { Log.e(TAG, "NoSuchAlgorithmException."); } catch (InvalidKeyException e) { Log.e(TAG, "Invalid key specification."); } catch (SignatureException e) { Log.e(TAG, "Signature exception."); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); } return false; } }
Java
package net.cardgame.oraclecard.billingutils; // Portions copyright 2002, 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. // This code was converted from code at http://iharder.sourceforge.net/base64/ // Lots of extraneous features were removed. /* The original code said: * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit * <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rharder@usa.net * @version 1.3 */ /** * Base64 converter class. This code is not a complete MIME encoder; * it simply converts binary data to base64 data and back. * * <p>Note {@link CharBase64} is a GWT-compatible implementation of this * class. */ public class Base64 { /** Specify encoding (value is {@code true}). */ public final static boolean ENCODE = true; /** Specify decoding (value is {@code false}). */ public final static boolean DECODE = false; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte) '\n'; /** * The 64 valid Base64 values. */ private final static byte[] ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; /** * The 64 valid web safe Base64 values. */ private final static byte[] WEBSAFE_ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'}; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; /** The web safe decodabet */ private final static byte[] WEBSAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44 62, // Dash '-' sign at decimal 45 -9, -9, // Decimal 46-47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, // Decimal 91-94 63, // Underscore '_' at decimal 95 -9, // Decimal 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // Indicates white space in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates equals sign in encoding private final static byte EQUALS_SIGN_ENC = -1; /** Defeats instantiation. */ private Base64() { } /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param alphabet is the encoding alphabet * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index alphabet // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = alphabet[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Encodes a byte array into Base64 notation. * Equivalent to calling * {@code encodeBytes(source, 0, source.length)} * * @param source The data to convert * @since 1.4 */ public static String encode(byte[] source) { return encode(source, 0, source.length, ALPHABET, true); } /** * Encodes a byte array into web safe Base64 notation. * * @param source The data to convert * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries */ public static String encodeWebSafe(byte[] source, boolean doPadding) { return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet the encoding alphabet * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries * @since 1.4 */ public static String encode(byte[] source, int off, int len, byte[] alphabet, boolean doPadding) { byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE); int outLen = outBuff.length; // If doPadding is false, set length to truncate '=' // padding characters while (doPadding == false && outLen > 0) { if (outBuff[outLen - 1] != '=') { break; } outLen -= 1; } return new String(outBuff, 0, outLen); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet is the encoding alphabet * @param maxLineLength maximum length of one line. * @return the BASE64-encoded byte array */ public static byte[] encode(byte[] source, int off, int len, byte[] alphabet, int maxLineLength) { int lenDiv3 = (len + 2) / 3; // ceil(len / 3) int len43 = lenDiv3 * 4; byte[] outBuff = new byte[len43 // Main 4:3 + (len43 / maxLineLength)]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { // The following block of code is the same as // encode3to4( source, d + off, 3, outBuff, e, alphabet ); // but inlined for faster encoding (~20% improvement) int inBuff = ((source[d + off] << 24) >>> 8) | ((source[d + 1 + off] << 24) >>> 16) | ((source[d + 2 + off] << 24) >>> 24); outBuff[e] = alphabet[(inBuff >>> 18)]; outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f]; outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f]; outBuff[e + 3] = alphabet[(inBuff) & 0x3f]; lineLength += 4; if (lineLength == maxLineLength) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // end for: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e, alphabet); lineLength += 4; if (lineLength == maxLineLength) { // Add a last newline outBuff[e + 4] = NEW_LINE; e++; } e += 4; } assert (e == outBuff.length); return outBuff; } /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param decodabet the decodabet for decoding Base64 content * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, byte[] decodabet) { // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } else if (source[srcOffset + 3] == EQUALS_SIGN) { // Example: DkL= int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } else { // Example: DkLE int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18) | ((decodabet[source[srcOffset + 3]] << 24) >>> 24); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } } // end decodeToBytes /** * Decodes data from Base64 notation. * * @param s the string to decode (decoded in default encoding) * @return the decoded data * @since 1.4 */ public static byte[] decode(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decode(bytes, 0, bytes.length); } /** * Decodes data from web safe Base64 notation. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param s the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decodeWebSafe(bytes, 0, bytes.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source The Base64 encoded data * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source) throws Base64DecoderException { return decode(source, 0, source.length); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded data. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(byte[] source) throws Base64DecoderException { return decodeWebSafe(source, 0, source.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, DECODABET); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded byte array. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data */ public static byte[] decodeWebSafe(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, WEBSAFE_DECODABET); } /** * Decodes Base64 content using the supplied decodabet and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @param decodabet the decodabet for decoding Base64 content * @return decoded data */ public static byte[] decode(byte[] source, int off, int len, byte[] decodabet) throws Base64DecoderException { int len34 = len * 3 / 4; byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = 0; i < len; i++) { sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits sbiDecode = decodabet[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better if (sbiDecode >= EQUALS_SIGN_ENC) { // An equals sign (for padding) must not occur at position 0 or 1 // and must be the last byte[s] in the encoded value if (sbiCrop == EQUALS_SIGN) { int bytesLeft = len - i; byte lastByte = (byte) (source[len - 1 + off] & 0x7f); if (b4Posn == 0 || b4Posn == 1) { throw new Base64DecoderException( "invalid padding byte '=' at byte offset " + i); } else if ((b4Posn == 3 && bytesLeft > 2) || (b4Posn == 4 && bytesLeft > 1)) { throw new Base64DecoderException( "padding byte '=' falsely signals end of encoded value " + "at offset " + i); } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) { throw new Base64DecoderException( "encoded value has invalid trailing byte"); } break; } b4[b4Posn++] = sbiCrop; if (b4Posn == 4) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); b4Posn = 0; } } } else { throw new Base64DecoderException("Bad Base64 input character at " + i + ": " + source[i + off] + "(decimal)"); } } // Because web safe encoding allows non padding base64 encodes, we // need to pad the rest of the b4 buffer with equal signs when // b4Posn != 0. There can be at most 2 equal signs at the end of // four characters, so the b4 buffer must have two or three // characters. This also catches the case where the input is // padded with EQUALS_SIGN if (b4Posn != 0) { if (b4Posn == 1) { throw new Base64DecoderException("single trailing character at offset " + (len - 1)); } b4[b4Posn++] = EQUALS_SIGN; outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); } byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } }
Java
/* Copyright (c) 2012 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 net.cardgame.oraclecard.billingutils; /** * Exception thrown when something went wrong with in-app billing. * An IabException has an associated IabResult (an error). * To get the IAB result that caused this exception to be thrown, * call {@link #getResult()}. */ public class IabException extends Exception { IabResult mResult; public IabException(IabResult r) { this(r, null); } public IabException(int response, String message) { this(new IabResult(response, message)); } public IabException(IabResult r, Exception cause) { super(r.getMessage(), cause); mResult = r; } public IabException(int response, String message, Exception cause) { this(new IabResult(response, message), cause); } /** Returns the IAB result (error) that this exception signals. */ public IabResult getResult() { return mResult; } }
Java
/* Copyright (c) 2012 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 net.cardgame.oraclecard.billingutils; import org.json.JSONException; import org.json.JSONObject; /** * Represents an in-app billing purchase. */ public class Purchase { String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS String mOrderId; String mPackageName; String mSku; long mPurchaseTime; int mPurchaseState; String mDeveloperPayload; String mToken; String mOriginalJson; String mSignature; public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException { mItemType = itemType; mOriginalJson = jsonPurchaseInfo; JSONObject o = new JSONObject(mOriginalJson); mOrderId = o.optString("orderId"); mPackageName = o.optString("packageName"); mSku = o.optString("productId"); mPurchaseTime = o.optLong("purchaseTime"); mPurchaseState = o.optInt("purchaseState"); mDeveloperPayload = o.optString("developerPayload"); mToken = o.optString("token", o.optString("purchaseToken")); mSignature = signature; } public String getItemType() { return mItemType; } public String getOrderId() { return mOrderId; } public String getPackageName() { return mPackageName; } public String getSku() { return mSku; } public long getPurchaseTime() { return mPurchaseTime; } public int getPurchaseState() { return mPurchaseState; } public String getDeveloperPayload() { return mDeveloperPayload; } public String getToken() { return mToken; } public String getOriginalJson() { return mOriginalJson; } public String getSignature() { return mSignature; } @Override public String toString() { return "PurchaseInfo(type:" + mItemType + "):" + mOriginalJson; } }
Java
/* Copyright (c) 2012 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 net.cardgame.oraclecard.billingutils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents a block of information about in-app items. * An Inventory is returned by such methods as {@link IabHelper#queryInventory}. */ public class Inventory { Map<String,SkuDetails> mSkuMap = new HashMap<String,SkuDetails>(); Map<String,Purchase> mPurchaseMap = new HashMap<String,Purchase>(); Inventory() { } /** Returns the listing details for an in-app product. */ public SkuDetails getSkuDetails(String sku) { return mSkuMap.get(sku); } /** Returns purchase information for a given product, or null if there is no purchase. */ public Purchase getPurchase(String sku) { return mPurchaseMap.get(sku); } /** Returns whether or not there exists a purchase of the given product. */ public boolean hasPurchase(String sku) { return mPurchaseMap.containsKey(sku); } /** Return whether or not details about the given product are available. */ public boolean hasDetails(String sku) { return mSkuMap.containsKey(sku); } /** * Erase a purchase (locally) from the inventory, given its product ID. This just * modifies the Inventory object locally and has no effect on the server! This is * useful when you have an existing Inventory object which you know to be up to date, * and you have just consumed an item successfully, which means that erasing its * purchase data from the Inventory you already have is quicker than querying for * a new Inventory. */ public void erasePurchase(String sku) { if (mPurchaseMap.containsKey(sku)) mPurchaseMap.remove(sku); } /** Returns a list of all owned product IDs. */ List<String> getAllOwnedSkus() { return new ArrayList<String>(mPurchaseMap.keySet()); } /** Returns a list of all owned product IDs of a given type */ List<String> getAllOwnedSkus(String itemType) { List<String> result = new ArrayList<String>(); for (Purchase p : mPurchaseMap.values()) { if (p.getItemType().equals(itemType)) result.add(p.getSku()); } return result; } /** Returns a list of all purchases. */ List<Purchase> getAllPurchases() { return new ArrayList<Purchase>(mPurchaseMap.values()); } void addSkuDetails(SkuDetails d) { mSkuMap.put(d.getSku(), d); } void addPurchase(Purchase p) { mPurchaseMap.put(p.getSku(), p); } }
Java
/* Copyright (c) 2012 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 net.cardgame.oraclecard.billingutils; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; import com.android.vending.billing.IInAppBillingService; /** * Provides convenience methods for in-app billing. You can create one instance of this * class for your application and use it to process in-app billing operations. * It provides synchronous (blocking) and asynchronous (non-blocking) methods for * many common in-app billing operations, as well as automatic signature * verification. * * After instantiating, you must perform setup in order to start using the object. * To perform setup, call the {@link #startSetup} method and provide a listener; * that listener will be notified when setup is complete, after which (and not before) * you may call other methods. * * After setup is complete, you will typically want to request an inventory of owned * items and subscriptions. See {@link #queryInventory}, {@link #queryInventoryAsync} * and related methods. * * When you are done with this object, don't forget to call {@link #dispose} * to ensure proper cleanup. This object holds a binding to the in-app billing * service, which will leak unless you dispose of it correctly. If you created * the object on an Activity's onCreate method, then the recommended * place to dispose of it is the Activity's onDestroy method. * * A note about threading: When using this object from a background thread, you may * call the blocking versions of methods; when using from a UI thread, call * only the asynchronous versions and handle the results via callbacks. * Also, notice that you can only call one asynchronous operation at a time; * attempting to start a second asynchronous operation while the first one * has not yet completed will result in an exception being thrown. * * @author Bruno Oliveira (Google) * */ public class IabHelper { // Is debug logging enabled? boolean mDebugLog = false; String mDebugTag = "IabHelper"; // Is setup done? boolean mSetupDone = false; // Has this object been disposed of? (If so, we should ignore callbacks, etc) boolean mDisposed = false; // Are subscriptions supported? boolean mSubscriptionsSupported = false; // Is an asynchronous operation in progress? // (only one at a time can be in progress) boolean mAsyncInProgress = false; // (for logging/debugging) // if mAsyncInProgress == true, what asynchronous operation is in progress? String mAsyncOperation = ""; // Context we were passed during initialization Context mContext; // Connection to the service IInAppBillingService mService; ServiceConnection mServiceConn; // The request code used to launch purchase flow int mRequestCode; // The item type of the current purchase flow String mPurchasingItemType; // Public key for verifying signature, in base64 encoding String mSignatureBase64 = null; // Billing response codes public static final int BILLING_RESPONSE_RESULT_OK = 0; public static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1; public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3; public static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4; public static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5; public static final int BILLING_RESPONSE_RESULT_ERROR = 6; public static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7; public static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8; // IAB Helper error codes public static final int IABHELPER_ERROR_BASE = -1000; public static final int IABHELPER_REMOTE_EXCEPTION = -1001; public static final int IABHELPER_BAD_RESPONSE = -1002; public static final int IABHELPER_VERIFICATION_FAILED = -1003; public static final int IABHELPER_SEND_INTENT_FAILED = -1004; public static final int IABHELPER_USER_CANCELLED = -1005; public static final int IABHELPER_UNKNOWN_PURCHASE_RESPONSE = -1006; public static final int IABHELPER_MISSING_TOKEN = -1007; public static final int IABHELPER_UNKNOWN_ERROR = -1008; public static final int IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE = -1009; public static final int IABHELPER_INVALID_CONSUMPTION = -1010; // Keys for the responses from InAppBillingService public static final String RESPONSE_CODE = "RESPONSE_CODE"; public static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST"; public static final String RESPONSE_BUY_INTENT = "BUY_INTENT"; public static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; public static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE"; public static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST"; public static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST"; public static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST"; public static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN"; // Item types public static final String ITEM_TYPE_INAPP = "inapp"; public static final String ITEM_TYPE_SUBS = "subs"; // some fields on the getSkuDetails response bundle public static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST"; public static final String GET_SKU_DETAILS_ITEM_TYPE_LIST = "ITEM_TYPE_LIST"; /** * Creates an instance. After creation, it will not yet be ready to use. You must perform * setup by calling {@link #startSetup} and wait for setup to complete. This constructor does not * block and is safe to call from a UI thread. * * @param ctx Your application or Activity context. Needed to bind to the in-app billing service. * @param base64PublicKey Your application's public key, encoded in base64. * This is used for verification of purchase signatures. You can find your app's base64-encoded * public key in your application's page on Google Play Developer Console. Note that this * is NOT your "developer public key". */ public IabHelper(Context ctx, String base64PublicKey) { mContext = ctx.getApplicationContext(); mSignatureBase64 = base64PublicKey; logDebug("IAB helper created."); } /** * Enables or disable debug logging through LogCat. */ public void enableDebugLogging(boolean enable, String tag) { checkNotDisposed(); mDebugLog = enable; mDebugTag = tag; } public void enableDebugLogging(boolean enable) { checkNotDisposed(); mDebugLog = enable; } /** * Callback for setup process. This listener's {@link #onIabSetupFinished} method is called * when the setup process is complete. */ public interface OnIabSetupFinishedListener { /** * Called to notify that setup is complete. * * @param result The result of the setup process. */ public void onIabSetupFinished(IabResult result); } /** * Starts the setup process. This will start up the setup process asynchronously. * You will be notified through the listener when the setup process is complete. * This method is safe to call from a UI thread. * * @param listener The listener to notify when the setup process is complete. */ public void startSetup(final OnIabSetupFinishedListener listener) { // If already set up, can't do it again. checkNotDisposed(); if (mSetupDone) throw new IllegalStateException("IAB helper is already set up."); // Connection to IAB service logDebug("Starting in-app billing setup."); mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { logDebug("Billing service disconnected."); mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { if (mDisposed) return; logDebug("Billing service connected."); mService = IInAppBillingService.Stub.asInterface(service); String packageName = mContext.getPackageName(); try { logDebug("Checking for in-app billing 3 support."); // check for in-app billing v3 support int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP); if (response != BILLING_RESPONSE_RESULT_OK) { if (listener != null) listener.onIabSetupFinished(new IabResult(response, "Error checking for billing v3 support.")); // if in-app purchases aren't supported, neither are subscriptions. mSubscriptionsSupported = false; return; } logDebug("In-app billing version 3 supported for " + packageName); // check for v3 subscriptions support response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS); if (response == BILLING_RESPONSE_RESULT_OK) { logDebug("Subscriptions AVAILABLE."); mSubscriptionsSupported = true; } else { logDebug("Subscriptions NOT AVAILABLE. Response: " + response); } mSetupDone = true; } catch (RemoteException e) { if (listener != null) { listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION, "RemoteException while setting up in-app billing.")); } e.printStackTrace(); return; } if (listener != null) { listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful.")); } } }; Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) { // service available to handle that Intent mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); } else { // no service available to handle that Intent if (listener != null) { listener.onIabSetupFinished( new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing service unavailable on device.")); } } } /** * Dispose of object, releasing resources. It's very important to call this * method when you are done with this object. It will release any resources * used by it such as service connections. Naturally, once the object is * disposed of, it can't be used again. */ public void dispose() { logDebug("Disposing."); mSetupDone = false; if (mServiceConn != null) { logDebug("Unbinding from service."); if (mContext != null) mContext.unbindService(mServiceConn); } mDisposed = true; mContext = null; mServiceConn = null; mService = null; mPurchaseListener = null; } private void checkNotDisposed() { if (mDisposed) throw new IllegalStateException("IabHelper was disposed of, so it cannot be used."); } /** Returns whether subscriptions are supported. */ public boolean subscriptionsSupported() { checkNotDisposed(); return mSubscriptionsSupported; } /** * Callback that notifies when a purchase is finished. */ public interface OnIabPurchaseFinishedListener { /** * Called to notify that an in-app purchase finished. If the purchase was successful, * then the sku parameter specifies which item was purchased. If the purchase failed, * the sku and extraData parameters may or may not be null, depending on how far the purchase * process went. * * @param result The result of the purchase. * @param info The purchase information (null if purchase failed) */ public void onIabPurchaseFinished(IabResult result, Purchase info); } // The listener registered on launchPurchaseFlow, which we have to call back when // the purchase finishes OnIabPurchaseFinishedListener mPurchaseListener; public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchPurchaseFlow(act, sku, requestCode, listener, ""); } public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, requestCode, listener, extraData); } public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchSubscriptionPurchaseFlow(act, sku, requestCode, listener, ""); } public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, requestCode, listener, extraData); } /** * Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase, * which will involve bringing up the Google Play screen. The calling activity will be paused while * the user interacts with Google Play, and the result will be delivered via the activity's * {@link android.app.Activity#onActivityResult} method, at which point you must call * this object's {@link #handleActivityResult} method to continue the purchase flow. This method * MUST be called from the UI thread of the Activity. * * @param act The calling activity. * @param sku The sku of the item to purchase. * @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS) * @param requestCode A request code (to differentiate from other responses -- * as in {@link android.app.Activity#startActivityForResult}). * @param listener The listener to notify when the purchase process finishes * @param extraData Extra data (developer payload), which will be returned with the purchase data * when the purchase completes. This extra data will be permanently bound to that purchase * and will always be returned when the purchase is queried. */ public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { checkNotDisposed(); checkSetupDone("launchPurchaseFlow"); flagStartAsync("launchPurchaseFlow"); IabResult result; if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) { IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available."); flagEndAsync(); if (listener != null) listener.onIabPurchaseFinished(r, null); return; } try { logDebug("Constructing buy intent for " + sku + ", item type: " + itemType); Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData); int response = getResponseCodeFromBundle(buyIntentBundle); if (response != BILLING_RESPONSE_RESULT_OK) { logError("Unable to buy item, Error response: " + getResponseDesc(response)); flagEndAsync(); result = new IabResult(response, "Unable to buy item"); if (listener != null) listener.onIabPurchaseFinished(result, null); return; } PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT); logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode); mRequestCode = requestCode; mPurchaseListener = listener; mPurchasingItemType = itemType; act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); } catch (SendIntentException e) { logError("SendIntentException while launching purchase flow for sku " + sku); e.printStackTrace(); flagEndAsync(); result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent."); if (listener != null) listener.onIabPurchaseFinished(result, null); } catch (RemoteException e) { logError("RemoteException while launching purchase flow for sku " + sku); e.printStackTrace(); flagEndAsync(); result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow"); if (listener != null) listener.onIabPurchaseFinished(result, null); } } /** * Handles an activity result that's part of the purchase flow in in-app billing. If you * are calling {@link #launchPurchaseFlow}, then you must call this method from your * Activity's {@link android.app.Activity@onActivityResult} method. This method * MUST be called from the UI thread of the Activity. * * @param requestCode The requestCode as you received it. * @param resultCode The resultCode as you received it. * @param data The data (Intent) as you received it. * @return Returns true if the result was related to a purchase flow and was handled; * false if the result was not related to a purchase, in which case you should * handle it normally. */ public boolean handleActivityResult(int requestCode, int resultCode, Intent data) { IabResult result; if (requestCode != mRequestCode) return false; checkNotDisposed(); checkSetupDone("handleActivityResult"); // end of async purchase operation that started on launchPurchaseFlow flagEndAsync(); if (data == null) { logError("Null data in IAB activity result."); result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result"); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } int responseCode = getResponseCodeFromIntent(data); String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA); String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE); if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) { logDebug("Successful resultcode from purchase activity."); logDebug("Purchase data: " + purchaseData); logDebug("Data signature: " + dataSignature); logDebug("Extras: " + data.getExtras()); logDebug("Expected item type: " + mPurchasingItemType); if (purchaseData == null || dataSignature == null) { logError("BUG: either purchaseData or dataSignature is null."); logDebug("Extras: " + data.getExtras().toString()); result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature"); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } Purchase purchase = null; try { purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature); String sku = purchase.getSku(); // Verify signature if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) { logError("Purchase signature verification FAILED for sku " + sku); result = new IabResult(IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, purchase); return true; } logDebug("Purchase signature successfully verified."); } catch (JSONException e) { logError("Failed to parse purchase data."); e.printStackTrace(); result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } if (mPurchaseListener != null) { mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase); } } else if (resultCode == Activity.RESULT_OK) { // result code was OK, but in-app billing response was not OK. logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode)); if (mPurchaseListener != null) { result = new IabResult(responseCode, "Problem purchashing item."); mPurchaseListener.onIabPurchaseFinished(result, null); } } else if (resultCode == Activity.RESULT_CANCELED) { logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode)); result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); } else { logError("Purchase failed. Result code: " + Integer.toString(resultCode) + ". Response: " + getResponseDesc(responseCode)); result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); } return true; } public Inventory queryInventory(boolean querySkuDetails, List<String> moreSkus) throws IabException { return queryInventory(querySkuDetails, moreSkus, null); } /** * Queries the inventory. This will query all owned items from the server, as well as * information on additional skus, if specified. This method may block or take long to execute. * Do not call from a UI thread. For that, use the non-blocking version {@link #refreshInventoryAsync}. * * @param querySkuDetails if true, SKU details (price, description, etc) will be queried as well * as purchase information. * @param moreItemSkus additional PRODUCT skus to query information on, regardless of ownership. * Ignored if null or if querySkuDetails is false. * @param moreSubsSkus additional SUBSCRIPTIONS skus to query information on, regardless of ownership. * Ignored if null or if querySkuDetails is false. * @throws IabException if a problem occurs while refreshing the inventory. */ public Inventory queryInventory(boolean querySkuDetails, List<String> moreItemSkus, List<String> moreSubsSkus) throws IabException { checkNotDisposed(); checkSetupDone("queryInventory"); try { Inventory inv = new Inventory(); int r = queryPurchases(inv, ITEM_TYPE_INAPP); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying owned items)."); } if (querySkuDetails) { r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying prices of items)."); } } // if subscriptions are supported, then also query for subscriptions if (mSubscriptionsSupported) { r = queryPurchases(inv, ITEM_TYPE_SUBS); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying owned subscriptions)."); } if (querySkuDetails) { r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreItemSkus); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions)."); } } } return inv; } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e); } catch (JSONException e) { throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e); } } /** * Listener that notifies when an inventory query operation completes. */ public interface QueryInventoryFinishedListener { /** * Called to notify that an inventory query operation completed. * * @param result The result of the operation. * @param inv The inventory. */ public void onQueryInventoryFinished(IabResult result, Inventory inv); } /** * Asynchronous wrapper for inventory query. This will perform an inventory * query as described in {@link #queryInventory}, but will do so asynchronously * and call back the specified listener upon completion. This method is safe to * call from a UI thread. * * @param querySkuDetails as in {@link #queryInventory} * @param moreSkus as in {@link #queryInventory} * @param listener The listener to notify when the refresh operation completes. */ public void queryInventoryAsync(final boolean querySkuDetails, final List<String> moreSkus, final QueryInventoryFinishedListener listener) { final Handler handler = new Handler(); checkNotDisposed(); checkSetupDone("queryInventory"); flagStartAsync("refresh inventory"); (new Thread(new Runnable() { public void run() { IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful."); Inventory inv = null; try { inv = queryInventory(querySkuDetails, moreSkus); } catch (IabException ex) { result = ex.getResult(); } flagEndAsync(); final IabResult result_f = result; final Inventory inv_f = inv; if (!mDisposed && listener != null) { handler.post(new Runnable() { public void run() { listener.onQueryInventoryFinished(result_f, inv_f); } }); } } })).start(); } public void queryInventoryAsync(QueryInventoryFinishedListener listener) { queryInventoryAsync(true, null, listener); } public void queryInventoryAsync(boolean querySkuDetails, QueryInventoryFinishedListener listener) { queryInventoryAsync(querySkuDetails, null, listener); } /** * Consumes a given in-app product. Consuming can only be done on an item * that's owned, and as a result of consumption, the user will no longer own it. * This method may block or take long to return. Do not call from the UI thread. * For that, see {@link #consumeAsync}. * * @param itemInfo The PurchaseInfo that represents the item to consume. * @throws IabException if there is a problem during consumption. */ void consume(Purchase itemInfo) throws IabException { checkNotDisposed(); checkSetupDone("consume"); if (!itemInfo.mItemType.equals(ITEM_TYPE_INAPP)) { throw new IabException(IABHELPER_INVALID_CONSUMPTION, "Items of type '" + itemInfo.mItemType + "' can't be consumed."); } try { String token = itemInfo.getToken(); String sku = itemInfo.getSku(); if (token == null || token.equals("")) { logError("Can't consume "+ sku + ". No token."); throw new IabException(IABHELPER_MISSING_TOKEN, "PurchaseInfo is missing token for sku: " + sku + " " + itemInfo); } logDebug("Consuming sku: " + sku + ", token: " + token); int response = mService.consumePurchase(3, mContext.getPackageName(), token); if (response == BILLING_RESPONSE_RESULT_OK) { logDebug("Successfully consumed sku: " + sku); } else { logDebug("Error consuming consuming sku " + sku + ". " + getResponseDesc(response)); throw new IabException(response, "Error consuming sku " + sku); } } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while consuming. PurchaseInfo: " + itemInfo, e); } } /** * Callback that notifies when a consumption operation finishes. */ public interface OnConsumeFinishedListener { /** * Called to notify that a consumption has finished. * * @param purchase The purchase that was (or was to be) consumed. * @param result The result of the consumption operation. */ public void onConsumeFinished(Purchase purchase, IabResult result); } /** * Callback that notifies when a multi-item consumption operation finishes. */ public interface OnConsumeMultiFinishedListener { /** * Called to notify that a consumption of multiple items has finished. * * @param purchases The purchases that were (or were to be) consumed. * @param results The results of each consumption operation, corresponding to each * sku. */ public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results); } /** * Asynchronous wrapper to item consumption. Works like {@link #consume}, but * performs the consumption in the background and notifies completion through * the provided listener. This method is safe to call from a UI thread. * * @param purchase The purchase to be consumed. * @param listener The listener to notify when the consumption operation finishes. */ public void consumeAsync(Purchase purchase, OnConsumeFinishedListener listener) { checkNotDisposed(); checkSetupDone("consume"); List<Purchase> purchases = new ArrayList<Purchase>(); purchases.add(purchase); consumeAsyncInternal(purchases, listener, null); } /** * Same as {@link consumeAsync}, but for multiple items at once. * @param purchases The list of PurchaseInfo objects representing the purchases to consume. * @param listener The listener to notify when the consumption operation finishes. */ public void consumeAsync(List<Purchase> purchases, OnConsumeMultiFinishedListener listener) { checkNotDisposed(); checkSetupDone("consume"); consumeAsyncInternal(purchases, null, listener); } /** * Returns a human-readable description for the given response code. * * @param code The response code * @return A human-readable string explaining the result code. * It also includes the result code numerically. */ public static String getResponseDesc(int code) { String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" + "3:Billing Unavailable/4:Item unavailable/" + "5:Developer Error/6:Error/7:Item Already Owned/" + "8:Item not owned").split("/"); String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" + "-1002:Bad response received/" + "-1003:Purchase signature verification failed/" + "-1004:Send intent failed/" + "-1005:User cancelled/" + "-1006:Unknown purchase response/" + "-1007:Missing token/" + "-1008:Unknown error/" + "-1009:Subscriptions not available/" + "-1010:Invalid consumption attempt").split("/"); if (code <= IABHELPER_ERROR_BASE) { int index = IABHELPER_ERROR_BASE - code; if (index >= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index]; else return String.valueOf(code) + ":Unknown IAB Helper Error"; } else if (code < 0 || code >= iab_msgs.length) return String.valueOf(code) + ":Unknown"; else return iab_msgs[code]; } // Checks that setup was done; if not, throws an exception. void checkSetupDone(String operation) { if (!mSetupDone) { logError("Illegal state for operation (" + operation + "): IAB helper is not set up."); throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + operation); } } // Workaround to bug where sometimes response codes come as Long instead of Integer int getResponseCodeFromBundle(Bundle b) { Object o = b.get(RESPONSE_CODE); if (o == null) { logDebug("Bundle with null response code, assuming OK (known issue)"); return BILLING_RESPONSE_RESULT_OK; } else if (o instanceof Integer) return ((Integer)o).intValue(); else if (o instanceof Long) return (int)((Long)o).longValue(); else { logError("Unexpected type for bundle response code."); logError(o.getClass().getName()); throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName()); } } // Workaround to bug where sometimes response codes come as Long instead of Integer int getResponseCodeFromIntent(Intent i) { Object o = i.getExtras().get(RESPONSE_CODE); if (o == null) { logError("Intent with no response code, assuming OK (known issue)"); return BILLING_RESPONSE_RESULT_OK; } else if (o instanceof Integer) return ((Integer)o).intValue(); else if (o instanceof Long) return (int)((Long)o).longValue(); else { logError("Unexpected type for intent response code."); logError(o.getClass().getName()); throw new RuntimeException("Unexpected type for intent response code: " + o.getClass().getName()); } } void flagStartAsync(String operation) { if (mAsyncInProgress) throw new IllegalStateException("Can't start async operation (" + operation + ") because another async operation(" + mAsyncOperation + ") is in progress."); mAsyncOperation = operation; mAsyncInProgress = true; logDebug("Starting async operation: " + operation); } void flagEndAsync() { logDebug("Ending async operation: " + mAsyncOperation); mAsyncOperation = ""; mAsyncInProgress = false; } int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException { // Query purchases logDebug("Querying owned items, item type: " + itemType); logDebug("Package name: " + mContext.getPackageName()); boolean verificationFailed = false; String continueToken = null; do { logDebug("Calling getPurchases with continuation token: " + continueToken); Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken); int response = getResponseCodeFromBundle(ownedItems); logDebug("Owned items response: " + String.valueOf(response)); if (response != BILLING_RESPONSE_RESULT_OK) { logDebug("getPurchases() failed: " + getResponseDesc(response)); return response; } if (!ownedItems.containsKey(RESPONSE_INAPP_ITEM_LIST) || !ownedItems.containsKey(RESPONSE_INAPP_PURCHASE_DATA_LIST) || !ownedItems.containsKey(RESPONSE_INAPP_SIGNATURE_LIST)) { logError("Bundle returned from getPurchases() doesn't contain required fields."); return IABHELPER_BAD_RESPONSE; } ArrayList<String> ownedSkus = ownedItems.getStringArrayList( RESPONSE_INAPP_ITEM_LIST); ArrayList<String> purchaseDataList = ownedItems.getStringArrayList( RESPONSE_INAPP_PURCHASE_DATA_LIST); ArrayList<String> signatureList = ownedItems.getStringArrayList( RESPONSE_INAPP_SIGNATURE_LIST); for (int i = 0; i < purchaseDataList.size(); ++i) { String purchaseData = purchaseDataList.get(i); String signature = signatureList.get(i); String sku = ownedSkus.get(i); if (Security.verifyPurchase(mSignatureBase64, purchaseData, signature)) { logDebug("Sku is owned: " + sku); Purchase purchase = new Purchase(itemType, purchaseData, signature); if (TextUtils.isEmpty(purchase.getToken())) { logWarn("BUG: empty/null token!"); logDebug("Purchase data: " + purchaseData); } // Record ownership and token inv.addPurchase(purchase); } else { logWarn("Purchase signature verification **FAILED**. Not adding item."); logDebug(" Purchase data: " + purchaseData); logDebug(" Signature: " + signature); verificationFailed = true; } } continueToken = ownedItems.getString(INAPP_CONTINUATION_TOKEN); logDebug("Continuation token: " + continueToken); } while (!TextUtils.isEmpty(continueToken)); return verificationFailed ? IABHELPER_VERIFICATION_FAILED : BILLING_RESPONSE_RESULT_OK; } int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus) throws RemoteException, JSONException { logDebug("Querying SKU details."); ArrayList<String> skuList = new ArrayList<String>(); skuList.addAll(inv.getAllOwnedSkus(itemType)); if (moreSkus != null) { for (String sku : moreSkus) { if (!skuList.contains(sku)) { skuList.add(sku); } } } if (skuList.size() == 0) { logDebug("queryPrices: nothing to do because there are no SKUs."); return BILLING_RESPONSE_RESULT_OK; } Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList); Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), itemType, querySkus); if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) { int response = getResponseCodeFromBundle(skuDetails); if (response != BILLING_RESPONSE_RESULT_OK) { logDebug("getSkuDetails() failed: " + getResponseDesc(response)); return response; } else { logError("getSkuDetails() returned a bundle with neither an error nor a detail list."); return IABHELPER_BAD_RESPONSE; } } ArrayList<String> responseList = skuDetails.getStringArrayList( RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { SkuDetails d = new SkuDetails(itemType, thisResponse); logDebug("Got sku details: " + d); inv.addSkuDetails(d); } return BILLING_RESPONSE_RESULT_OK; } void consumeAsyncInternal(final List<Purchase> purchases, final OnConsumeFinishedListener singleListener, final OnConsumeMultiFinishedListener multiListener) { final Handler handler = new Handler(); flagStartAsync("consume"); (new Thread(new Runnable() { public void run() { final List<IabResult> results = new ArrayList<IabResult>(); for (Purchase purchase : purchases) { try { consume(purchase); results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku())); } catch (IabException ex) { results.add(ex.getResult()); } } flagEndAsync(); if (!mDisposed && singleListener != null) { handler.post(new Runnable() { public void run() { singleListener.onConsumeFinished(purchases.get(0), results.get(0)); } }); } if (!mDisposed && multiListener != null) { handler.post(new Runnable() { public void run() { multiListener.onConsumeMultiFinished(purchases, results); } }); } } })).start(); } void logDebug(String msg) { if (mDebugLog) Log.d(mDebugTag, msg); } void logError(String msg) { Log.e(mDebugTag, "In-app billing error: " + msg); } void logWarn(String msg) { Log.w(mDebugTag, "In-app billing warning: " + msg); } }
Java
/* Copyright (c) 2012 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 net.cardgame.oraclecard.billingutils; /** * Represents the result of an in-app billing operation. * A result is composed of a response code (an integer) and possibly a * message (String). You can get those by calling * {@link #getResponse} and {@link #getMessage()}, respectively. You * can also inquire whether a result is a success or a failure by * calling {@link #isSuccess()} and {@link #isFailure()}. */ public class IabResult { int mResponse; String mMessage; public IabResult(int response, String message) { mResponse = response; if (message == null || message.trim().length() == 0) { mMessage = IabHelper.getResponseDesc(response); } else { mMessage = message + " (response: " + IabHelper.getResponseDesc(response) + ")"; } } public int getResponse() { return mResponse; } public String getMessage() { return mMessage; } public boolean isSuccess() { return mResponse == IabHelper.BILLING_RESPONSE_RESULT_OK; } public boolean isFailure() { return !isSuccess(); } public String toString() { return "IabResult: " + getMessage(); } }
Java
/* Copyright (c) 2012 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 net.cardgame.oraclecard.billingutils; import org.json.JSONException; import org.json.JSONObject; /** * Represents an in-app product's listing details. */ public class SkuDetails { String mItemType; String mSku; String mType; String mPrice; String mTitle; String mDescription; String mJson; public SkuDetails(String jsonSkuDetails) throws JSONException { this(IabHelper.ITEM_TYPE_INAPP, jsonSkuDetails); } public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException { mItemType = itemType; mJson = jsonSkuDetails; JSONObject o = new JSONObject(mJson); mSku = o.optString("productId"); mType = o.optString("type"); mPrice = o.optString("price"); mTitle = o.optString("title"); mDescription = o.optString("description"); } public String getSku() { return mSku; } public String getType() { return mType; } public String getPrice() { return mPrice; } public String getTitle() { return mTitle; } public String getDescription() { return mDescription; } @Override public String toString() { return "SkuDetails:" + mJson; } }
Java
package net.cardgame.oraclecard.service; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import jp.jma.oraclecard.R; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.FileUtils; import net.cardgame.orcalecard.utils.Utils; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class ServiceDownload extends IntentService implements ServiceDownloadListener { public final static String KEY_PATH_SERVER = "path_server"; public final static String KEY_DECK_ID = "deckBeanId"; public final static String KEY_POSITION = "Position"; public final static String KEY_PERCENT = "percent download"; public final static String KEY_PATH_SAVE = "path save"; public final static String KEY_STATUS = "status download"; public final static String KEY_MESSAGE_FULL_MEMORY = "full_memory"; private static DownloadUnzipObject downloadObject1; private static DownloadUnzipObject downloadObject2; private static boolean cancel = false; public ServiceDownload(String name) { super(name); // TODO Auto-generated constructor stub } public ServiceDownload() { super("ServiceDownload"); } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub // Get data Bundle bundle = intent.getExtras(); cancel = false; if (bundle.containsKey("cancel")) { cancel = true; return; } String patch = bundle.getString(KEY_PATH_SERVER); int deckId = bundle.getInt(KEY_DECK_ID); int position = bundle.getInt(KEY_POSITION); String patchSave = bundle.getString(KEY_PATH_SAVE); DownloadUnzipObject object = new DownloadUnzipObject(deckId, position, patch, patchSave); boolean excute = false; if (downloadObject1 == null) { if (downloadObject2 == null || (downloadObject2 != null && object.getDeckId() != downloadObject2 .getDeckId())) { downloadObject1 = object; excute = true; } } else if (downloadObject2 == null && downloadObject1.getDeckId() != object.getDeckId()) { downloadObject2 = object; excute = true; } if (excute) { // excute download and unzip file DownloadFileAndUnzip ayncTask = new DownloadFileAndUnzip(this); ayncTask.execute(object); } } /* This task implement Download Deck bean from server */ class DownloadFileAndUnzip extends AsyncTask<DownloadUnzipObject, Void, DownloadUnzipObject> { /** * Downloading file in background thread * */ private final static int CONNECT_TIMEOUT = 15 * 1000; private final static int READ_TIMEOUT = 30 * 1000; private Context mContext; FileUtils fileUtils; DownloadFileAndUnzip(Context context) { mContext = context; } @Override protected DownloadUnzipObject doInBackground( DownloadUnzipObject... progress) { DownloadUnzipObject downloadObject = progress[0]; long downloaded = 0; try { File folder = new File( ConstantValue.getPatchCardData(ServiceDownload.this)); if (!folder.exists()) { folder.mkdirs(); } File file = new File(downloadObject.getPathSaveFile()); URL url = new URL(downloadObject.getUrlDownload()); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setReadTimeout(READ_TIMEOUT); connection.setConnectTimeout(CONNECT_TIMEOUT); if (file.exists()) { downloaded = (int) file.length(); } long fileLength = 0; if (downloaded > 0) { fileLength = connection.getContentLength(); if (downloaded >= fileLength) { downloadObject.setPercent(50); // perform unzip file FileUtils fileUtils = new FileUtils(); fileUtils.registryUnzipListener(ServiceDownload.this); if (fileUtils.unzipFile(downloadObject)) downloadObject.setFinished(); return downloadObject; } else { connection.disconnect(); url = new URL(downloadObject.getUrlDownload()); connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(READ_TIMEOUT); connection.setConnectTimeout(CONNECT_TIMEOUT); } } connection.setRequestProperty("Range", "bytes=" + downloaded + "-"); connection.setDoOutput(true); BufferedInputStream in = new BufferedInputStream( connection.getInputStream()); FileOutputStream fos = downloaded == 0 ? new FileOutputStream( file) : new FileOutputStream( downloadObject.getPathSaveFile(), true); BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); byte[] data = new byte[1024]; long lenghtOfFile = connection.getContentLength() + downloaded; if (!FileUtils.availableDownload(lenghtOfFile)) { // Bộ nhớ không đủ, không cho phép download String message1 = getResources().getString( R.string.freespace_unvailable1); String message2 = getResources().getString( R.string.freespace_unvailable2); String message = message1 + 3 * lenghtOfFile / (1024 * 1024) + message2; // send broadcast receiver Intent intent = new Intent(ConstantValue.ACTION_DOWNLOAD); intent.putExtra(KEY_MESSAGE_FULL_MEMORY, message); LocalBroadcastManager.getInstance(ServiceDownload.this) .sendBroadcast(intent); return downloadObject; } int count; int percent = 0; while ((count = in.read(data, 0, 1024)) != -1) { if (cancel) return downloadObject; downloaded += count; float result = (float) downloaded / (float) lenghtOfFile * 100; result = result / 2; if (result - percent >= 1) { downloadObject.setPercent((int) result); // send progress percentage to broadcast Intent intent = new Intent( ConstantValue.ACTION_DOWNLOAD); intent.putExtra(KEY_DECK_ID, downloadObject.getDeckId()); intent.putExtra(KEY_POSITION, downloadObject.getPosition()); intent.putExtra(KEY_PERCENT, downloadObject.getPercent()); LocalBroadcastManager.getInstance(ServiceDownload.this) .sendBroadcast(intent); // publishProgress(downloadObject); percent = (int) result; } bout.write(data, 0, count); } bout.flush(); bout.close(); in.close(); connection.disconnect(); } catch (Exception e) { Log.e("Error: ", e.toString()); return downloadObject; } downloadObject.setPercent(50); // perform unzip file fileUtils = new FileUtils(); fileUtils.registryUnzipListener(ServiceDownload.this); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub if (cancel) fileUtils.stopUnzip(); } }, 1000, 1000); if (fileUtils.unzipFile(downloadObject)) downloadObject.setFinished(); timer.cancel(); return downloadObject; } @Override protected void onPostExecute(DownloadUnzipObject result) { // TODO Auto-generated method stub super.onPostExecute(result); if (downloadObject1 != null && result.getDeckId() == downloadObject1.getDeckId()) { downloadObject1 = null; } else { downloadObject2 = null; } // send to broadcast receiver Intent intent = new Intent(ConstantValue.ACTION_DOWNLOAD); intent.putExtra(KEY_DECK_ID, result.getDeckId()); intent.putExtra(KEY_POSITION, result.getPosition()); intent.putExtra(KEY_PERCENT, result.getPercent()); intent.putExtra(KEY_STATUS, result.isFinished()); LocalBroadcastManager.getInstance(ServiceDownload.this) .sendBroadcast(intent); saveStatus(result); } void saveStatus(DownloadUnzipObject object) { SecurePreferences appPreferences = new SecurePreferences(mContext, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); ArrayList<DeckBean> listDeckBean = gson.fromJson(listSaved, listOfDeckBean); for (DeckBean deckBean : listDeckBean) { if (deckBean.deckId == object.getDeckId()) { deckBean.percentDownloaded = object.isFinished() ? -2 : object.getPercent(); if (!deckBean.isFree) { deckBean.isUnlock = true; } ArrayList<DeckBean> listSave = checkUnlockSpecial(listDeckBean); String save = gson.toJson(listSave, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); return; } } } ArrayList<DeckBean> checkUnlockSpecial(ArrayList<DeckBean> listDeckBean) { int total = 0; for (DeckBean deckbean : listDeckBean) { if (deckbean.percentDownloaded == -2) total++; if (total >= 2) return unlockSpecialAndRandom(listDeckBean); } return listDeckBean; } ArrayList<DeckBean> unlockSpecialAndRandom( ArrayList<DeckBean> listDeckBean) { for (DeckBean deckbean : listDeckBean) { if (deckbean.deckId == 999 || deckbean.deckId == 998) { deckbean.isUnlock = true; } } return listDeckBean; } } @Override public void onUpdateProgressListener(int percent, int position, int deckId) { // TODO Auto-generated method stub Intent intent = new Intent(ConstantValue.ACTION_DOWNLOAD); // Add data intent.putExtra(KEY_DECK_ID, deckId); intent.putExtra(KEY_POSITION, position); intent.putExtra(KEY_PERCENT, percent); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } @Override public void onDownloadFailListener(DownloadUnzipObject object, String message) { // TODO Auto-generated method stub } @Override public void onFinishedListener(DownloadUnzipObject object) { // TODO Auto-generated method stub } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } }
Java
package net.cardgame.oraclecard.service; public class DownloadUnzipObject { @Override public String toString() { return "DownloadUnzipObject [deckId=" + deckId + ", position=" + position + ", percent=" + percent + ", urlDownload=" + urlDownload + ", finished=" + finished + ", pathSaveFile=" + pathSaveFile + ", strId=" + strId + "]"; } private int deckId; private int position; private int percent; private String urlDownload; private boolean finished = false; private String pathSaveFile; private String strId; public String getStringId() { return strId; } public String getPathSaveFile() { return pathSaveFile; } public void setPathSaveFile(String pathSaveFile) { this.pathSaveFile = pathSaveFile; } public int getDeckId() { return deckId; } public void setDeckId(int deckId) { this.deckId = deckId; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public int getPercent() { return percent; } public void setPercent(int percent) { this.percent = percent; } public String getUrlDownload() { return urlDownload; } public void setUrlDownload(String urlDownload) { this.urlDownload = urlDownload; } public void setFinished() { this.finished = true; } public boolean isFinished() { return finished; } public DownloadUnzipObject(int deckId, int position, String url, String pathSave) { this.deckId = deckId; this.position = position; this.urlDownload = url; this.pathSaveFile = pathSave; this.percent = 0; strId = deckId < 10 ? "0" + deckId : "" + deckId; } }
Java
package net.cardgame.oraclecard.service; public interface ServiceDownloadListener { void onUpdateProgressListener(int percent, int position, int deckId); void onDownloadFailListener(DownloadUnzipObject object, String message); void onFinishedListener(DownloadUnzipObject object); }
Java
package net.cardgame.oraclecard.service; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.XmlParser; import android.app.IntentService; import android.content.Intent; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class ServiceUpdateFileConfig extends IntentService { public ServiceUpdateFileConfig(String name) { super(name); // TODO Auto-generated constructor stub } public ServiceUpdateFileConfig() { super("ServiceUpdateFileConfig"); } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub ArrayList<DeckBean> listDeckBean = new ArrayList<DeckBean>(); ArrayList<DeckBean> listDeckBeanSaved = new ArrayList<DeckBean>(); String deckXml = "null"; NetworkUtils networkUtils = new NetworkUtils(); if (NetworkUtils.isNetworkConnected(this)) { deckXml = networkUtils.getStringFromUrl(ConstantValue.BASE_URL + ConstantValue.LIST_DECK_SUB_URL); } else return; listDeckBean = new XmlParser().getDeckBeans(deckXml); // get sharedreference Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); String config = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); listDeckBeanSaved = gson.fromJson(config, listOfDeckBean); if (listDeckBean == null || listDeckBean.isEmpty() || listDeckBeanSaved == null || listDeckBeanSaved.isEmpty()) return; // test // DeckBean deck = listDeckBean.get(16); // DeckBean deck1 = new DeckBean(); // deck1.deckId = 19; // deck1.deckName = "test"; // deck1.isFree = true; // deck1.releaseDate = deck.releaseDate; // deck1.inAppPurchaseId = "12131121"; // deck1.deckPrice = 132; // deck1.cardNumber = 44; // deck1.pathServerDownload = deck.pathServerDownload; // DeckBean deck2 = new DeckBean(); // deck2.deckId = 20; // deck2.deckName = "test2"; // deck2.isFree = true; // deck2.releaseDate = deck.releaseDate; // deck2.inAppPurchaseId = "12131121"; // deck2.deckPrice = 132; // deck2.cardNumber = 44; // deck2.pathServerDownload = deck.pathServerDownload; // listDeckBean.add(deck1); // listDeckBean.add(deck2); // listDeckBean.remove(10); // listDeckBean.add(deck1); // // update list deck bean for (DeckBean deckBean : listDeckBean) { boolean add = true; for (DeckBean dec : listDeckBeanSaved) { if (dec.deckId == deckBean.deckId) { add = false; dec.deckName = deckBean.deckName; if (deckBean.isFree == false && dec.isFree == true) { dec.isUnlock = false; } dec.isFree = deckBean.isFree; dec.releaseDate = deckBean.releaseDate; dec.inAppPurchaseId = deckBean.inAppPurchaseId; dec.deckPrice = deckBean.deckPrice; dec.cardNumber = deckBean.cardNumber; dec.pathServerDownload = deckBean.pathServerDownload; break; } } if (add) { listDeckBeanSaved.add(deckBean); } } // remove deck bean if server has removed int size = listDeckBeanSaved.size(); for (int i = 0; i < size; i++) { DeckBean deckBean = listDeckBeanSaved.get(i); boolean remove = true; for (DeckBean deckBean2 : listDeckBean) { if (deckBean.deckId == deckBean2.deckId) { remove = false; break; } } if (remove) { listDeckBeanSaved.remove(i); size--; } } // put shared reference String save = gson.toJson(listDeckBeanSaved, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); } }
Java
package net.cardgame.oraclecard.common; public interface SavedListener { public void onSave(boolean save); }
Java
package net.cardgame.oraclecard.common; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; public class Helper { public static void getListViewSize(ListView myListView) { ListAdapter myListAdapter = myListView.getAdapter(); if (myListAdapter == null) { // do nothing return null return; } // set listAdapter in loop for getting final size int totalHeight = 0; for (int size = 0; size < myListAdapter.getCount(); size++) { View listItem = myListAdapter.getView(size, null, myListView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } // setting listview item in adapter ViewGroup.LayoutParams params = myListView.getLayoutParams(); params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1)); myListView.setLayoutParams(params); // print height of adapter on log Log.i("height of listItem:", String.valueOf(totalHeight)); } }
Java
package net.cardgame.oraclecard.common; import net.cardgame.orcalecard.bean.HistoryBean; public interface SelectedHistoryListener { public void onSelectedItemListener(int id); public void onFinished(); public void onDeleteHistory(HistoryBean history); }
Java
package net.cardgame.oraclecard.common; import jp.jma.oraclecard.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageView; public class ImageClickable extends ImageView { private String path; boolean loadding = false; public ImageClickable(Context context) { super(context); } public ImageClickable(Context context, AttributeSet attrs) { super(context, attrs); } public ImageClickable(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.obj == null) { ImageClickable.this .setImageResource(R.drawable.image_not_found); return; } ImageClickable.this.setImageDrawable((Drawable) msg.obj); loadding = false; }; }; public void loadImage(String path) { this.path = path; if (path != null) { new ThreadLoadImage(mHandler, path, this, 1, true).start(); } } public void setPath(String path) { this.path = path; } private void reLoadImage() { if (path != null) { new ThreadLoadImage(mHandler, path, this, 1, true).start(); } } @Override public boolean onTouchEvent(MotionEvent event) { if (isEnabled() && isClickable()) switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: setColorFilter(Color.parseColor("#ee0467FB"), PorterDuff.Mode.MULTIPLY); break; case MotionEvent.ACTION_UP: setColorFilter(null); break; case MotionEvent.ACTION_CANCEL: setColorFilter(null); break; default: break; } return super.onTouchEvent(event); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub BitmapDrawable drawable = (BitmapDrawable) getDrawable(); if (drawable != null) { Bitmap bitmap = drawable.getBitmap(); if (!bitmap.isRecycled()) { super.onDraw(canvas); } else { if (!loadding) { loadding = true; reLoadImage(); } } } } }
Java
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 net.cardgame.oraclecard.common; import java.io.InputStream; import java.lang.ref.WeakReference; import jp.jma.oraclecard.MyApplication; import net.cardgame.orcalecard.utils.FileUtils; import uk.co.senab.bitmapcache.BitmapLruCache; import uk.co.senab.bitmapcache.CacheableBitmapDrawable; import uk.co.senab.bitmapcache.CacheableImageView; import android.content.Context; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.util.AttributeSet; import android.widget.ImageView; /** * Simple extension of CacheableImageView which allows downloading of Images of * the Internet. * * This code isn't production quality, but works well enough for this sample.s * * @author Chris Banes */ public class BitmapCacheableImageView extends CacheableImageView { /** * This task simply fetches an Bitmap from the specified URL and wraps it in * a wrapper. This implementation is NOT 'best practice' or production ready * code. */ private static class ImageUrlAsyncTask extends AsyncTask<String, Void, CacheableBitmapDrawable> { private final BitmapLruCache mCache; private final WeakReference<ImageView> mImageViewRef; private final BitmapFactory.Options mDecodeOpts; ImageUrlAsyncTask(ImageView imageView, BitmapLruCache cache, BitmapFactory.Options decodeOpts) { mCache = cache; mImageViewRef = new WeakReference<ImageView>(imageView); mDecodeOpts = decodeOpts; } @Override protected CacheableBitmapDrawable doInBackground(String... params) { // Return early if the ImageView has disappeared. if (null == mImageViewRef.get()) { return null; } final String sourcePath = params[0]; // Now we're not on the main thread we can check all caches CacheableBitmapDrawable result = mCache.getFromDiskCache(params[0], mDecodeOpts); try { if (null == result) { InputStream is = FileUtils.decrytToInputStream(sourcePath); // Add to cache result = mCache.put(sourcePath, is, mDecodeOpts, true); } } catch (Exception e) { // TODO: handle exception } return result; } @Override protected void onPostExecute(CacheableBitmapDrawable result) { super.onPostExecute(result); ImageView iv = mImageViewRef.get(); if (null != iv) { iv.setImageDrawable(result); } } } private BitmapLruCache mCache; private ImageUrlAsyncTask mCurrentTask; float rotate = 0; Context context; public BitmapCacheableImageView(Context context, AttributeSet attrs) { super(context, attrs); mCache = MyApplication.getInstance().getBitmapCache(); this.context = context; } public boolean loadImage(String sourcePath, Context context, float rotate) { this.rotate = rotate; // First check whether there's already a task running, if so cancel it if (null != mCurrentTask) { mCurrentTask.cancel(true); } // Check to see if the memory cache already has the bitmap. We can // safely do // this on the main thread. BitmapDrawable wrapper = mCache.getFromMemoryCache(sourcePath); BitmapFactory.Options option = new BitmapFactory.Options(); option.outHeight = this.getHeight(); option.outWidth = this.getWidth(); if (null != wrapper) { // The cache has it, so just display it setImageDrawable(wrapper); return true; } else { // Memory Cache doesn't have the URL, do threaded request... setImageDrawable(null); mCurrentTask = new ImageUrlAsyncTask(this, mCache, option); mCurrentTask.execute(sourcePath); // ThreadLoadImage thread = new ThreadLoadImage(sourcePath, option, // mCache); // thread.start(); return false; } } }
Java
package net.cardgame.oraclecard.common; import java.io.InputStream; import jp.jma.oraclecard.MyApplication; import net.cardgame.orcalecard.utils.FileUtils; import uk.co.senab.bitmapcache.BitmapLruCache; import uk.co.senab.bitmapcache.CacheableBitmapDrawable; import android.content.Context; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.graphics.drawable.BitmapDrawable; import android.os.Handler; import android.os.Message; import android.widget.ImageView; public class ThreadLoadImage extends Thread { String patch; BitmapFactory.Options option; int what; Handler handler; private BitmapLruCache mCache; Boolean cacheOnMemory; public ThreadLoadImage(Handler handler, String patch, ImageView imageview, int what, boolean cacheOnMemory) { // TODO Auto-generated constructor stubt this.cacheOnMemory = cacheOnMemory; mCache = MyApplication.getInstance().getBitmapCache(); this.handler = handler; this.what = what; this.patch = patch; this.option = new Options(); if (imageview != null) { option.outHeight = imageview.getHeight(); option.outWidth = imageview.getWidth(); } } public ThreadLoadImage(Context context, Handler handler, String patch, ImageView imageview, int what) { // TODO Auto-generated constructor stubt this.cacheOnMemory = true; mCache = MyApplication.getInstance().getBitmapCache(); this.handler = handler; this.what = what; this.patch = patch; this.option = new Options(); if (imageview != null) { option.outHeight = imageview.getHeight(); option.outWidth = imageview.getWidth(); } imageview = null; } @Override public void run() { // TODO Auto-generated method stub super.run(); BitmapDrawable wrapper = mCache.getFromMemoryCache(patch); if (wrapper != null && !wrapper.getBitmap().isRecycled()) { Message msg = handler.obtainMessage(what); msg.obj = wrapper; wrapper = null; msg.what = what; handler.sendMessage(msg); return; } CacheableBitmapDrawable result = mCache.getFromDiskCache(patch, option); if (null == result || result.getBitmap().isRecycled()) { try { InputStream is = FileUtils.decrytToInputStream(patch); // Add to mCache result = mCache.put(patch, is, option, cacheOnMemory); } catch (Exception e) { } } Message msg = handler.obtainMessage(what); msg.obj = result; result = null; msg.what = what; handler.sendMessage(msg); } }
Java
package net.cardgame.oraclecard.common; import net.cardgame.orcalecard.bean.NewsBean; public interface onDeleteNewsBeanListener { public void onDeleted(NewsBean newsBean); }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * 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 net.cardgame.oraclecard.common; import jp.jma.oraclecard.R; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.ViewConfiguration; import android.widget.CompoundButton; /** * A MySwitch is a two-state toggle switch widget that can select between two * options. The user may drag the "thumb" back and forth to choose the selected * option, or simply tap to toggle as if it were a checkbox. The * {@link #setText(CharSequence) text} property controls the text displayed in * the label for the switch, whereas the {@link #setTextOff(CharSequence) off} * and {@link #setTextOn(CharSequence) on} text controls the text on the thumb. * Similarly, the {@link #setTextAppearance(android.content.Context, int) * textAppearance} and the related setTypeface() methods control the typeface * and style of label text, whereas the * {@link #setSwitchTextAppearance(android.content.Context, int) * switchTextAppearance} and the related seSwitchTypeface() methods control that * of the thumb. * */ public class MySwitch extends CompoundButton { private static final int TOUCH_MODE_IDLE = 0; private static final int TOUCH_MODE_DOWN = 1; private static final int TOUCH_MODE_DRAGGING = 2; private static final String TAG = "MySwitch"; // Enum for the "typeface" XML parameter. private static final int SANS = 1; private static final int SERIF = 2; private static final int MONOSPACE = 3; private static final int VERTICAL = 0; private static final int HORIZONTAL = 1; private int mOrientation = HORIZONTAL; private OnChangeAttemptListener mOnChangeAttemptListener; private boolean mPushStyle; private boolean mTextOnThumb; private int mThumbExtraMovement; private Drawable mLeftBackground; private Drawable mRightBackground; private Drawable mMaskDrawable; private Drawable mThumbDrawable; private Drawable mTrackDrawable; private int mThumbTextPadding; private int mTrackTextPadding; private int mSwitchMinWidth; private int mSwitchMinHeight; private int mSwitchPadding; private CharSequence mTextOn; private CharSequence mTextOff; private Drawable mDrawableOn; private Drawable mDrawableOff; private boolean fixed = false; private boolean clickDisabled = false; private boolean onOrOff = true; private Bitmap pushBitmap; private Bitmap maskBitmap; private Bitmap tempBitmap; private Canvas backingLayer; private int mTouchMode; private int mTouchSlop; private float mTouchX; private float mTouchY; private VelocityTracker mVelocityTracker = VelocityTracker.obtain(); private int mMinFlingVelocity; private float mThumbPosition = 0; private int mSwitchWidth; private int mSwitchHeight; private int mThumbWidth; private int mThumbHeight; private int mSwitchLeft; private int mSwitchTop; private int mSwitchRight; private int mSwitchBottom; private TextPaint mTextPaint; private ColorStateList mTextColors; private Layout mOnLayout; private Layout mOffLayout; private Paint xferPaint; private Bitmap leftBitmap, rightBitmap; private final Rect mTrackPaddingRect = new Rect(); private final Rect mThPad = new Rect(); private final Rect canvasClipBounds = new Rect(); private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked }; /** * Construct a new MySwitch with default styling. * * @param context * The Context that will determine this widget's theming. */ public MySwitch(Context context) { this(context, null); } /** * Construct a new MySwitch with default styling, overriding specific style * attributes as requested. * * @param context * The Context that will determine this widget's theming. * @param attrs * Specification of attributes that should deviate from default * styling. */ public MySwitch(Context context, AttributeSet attrs) { this(context, attrs, R.attr.mySwitchStyleAttr); } /** * Construct a new MySwitch with a default style determined by the given * theme attribute, overriding specific style attributes as requested. * * @param context * The Context that will determine this widget's theming. * @param attrs * Specification of attributes that should deviate from the * default styling. * @param defStyle * An attribute ID within the active theme containing a reference * to the default style for this widget. e.g. * android.R.attr.switchStyle. */ public MySwitch(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); Resources res = getResources(); mTextPaint.density = res.getDisplayMetrics().density; mTextPaint.setShadowLayer(0.5f, 1.0f, 1.0f, Color.BLACK); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MySwitch, defStyle, 0); mLeftBackground = a.getDrawable(R.styleable.MySwitch_leftBackground); // if (mLeftBackground == null) { // mLeftBackground = new ColorDrawable(0xFF11BB33); // } mRightBackground = a.getDrawable(R.styleable.MySwitch_rightBackground); // if (mRightBackground == null) { // mRightBackground = new ColorDrawable(0x993322BB); // } mOrientation = a.getInteger(R.styleable.MySwitch_orientation, HORIZONTAL); // Log.d(TAG, "mLeftBackground="+mLeftBackground); // Log.d(TAG, "mRightBackground="+mRightBackground); mThumbDrawable = a.getDrawable(R.styleable.MySwitch_thumb); mTrackDrawable = a.getDrawable(R.styleable.MySwitch_track); mTextOn = a.getText(R.styleable.MySwitch_textOn); mTextOff = a.getText(R.styleable.MySwitch_textOff); mDrawableOn = a.getDrawable(R.styleable.MySwitch_drawableOn); mDrawableOff = a.getDrawable(R.styleable.MySwitch_drawableOff); mPushStyle = a.getBoolean(R.styleable.MySwitch_pushStyle, false); mTextOnThumb = a.getBoolean(R.styleable.MySwitch_textOnThumb, false); mThumbExtraMovement = a.getDimensionPixelSize( R.styleable.MySwitch_thumbExtraMovement, 0); mThumbTextPadding = a.getDimensionPixelSize( R.styleable.MySwitch_thumbTextPadding, 0); mTrackTextPadding = a.getDimensionPixelSize( R.styleable.MySwitch_trackTextPadding, 0); mSwitchMinWidth = a.getDimensionPixelSize( R.styleable.MySwitch_switchMinWidth, 0); mSwitchMinHeight = a.getDimensionPixelSize( R.styleable.MySwitch_switchMinHeight, 0); mSwitchPadding = a.getDimensionPixelSize( R.styleable.MySwitch_switchPadding, 0); mTrackDrawable.getPadding(mTrackPaddingRect); mThumbDrawable.getPadding(mThPad); mMaskDrawable = a.getDrawable(R.styleable.MySwitch_backgroundMask); RuntimeException e = null; if ((mLeftBackground != null) || (mRightBackground != null)) { // if ((mMaskDrawable == null) && (mLeftBackground == null) && // (mRightBackground == null)) { if (mMaskDrawable == null) { e = new IllegalArgumentException( a.getPositionDescription() + " if left/right background is given, then a mask has to be there"); } } if ((mLeftBackground != null) ^ (mRightBackground != null)) { if (mMaskDrawable == null) { e = new IllegalArgumentException( a.getPositionDescription() + " left and right background both should be there. only one is not allowed "); } } if ((mTextOnThumb) && (mPushStyle)) { e = new IllegalArgumentException( a.getPositionDescription() + " Text On Thumb and Push Stype are mutually exclusive. Only one can be present "); } xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // xferPaint.setColor(Color.TRANSPARENT); xferPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); int appearance = a.getResourceId( R.styleable.MySwitch_switchTextAppearanceAttrib, 0); if (appearance != 0) { setSwitchTextAppearance(context, appearance); } a.recycle(); if (e != null) { throw e; } ViewConfiguration config = ViewConfiguration.get(context); mTouchSlop = config.getScaledTouchSlop(); // Log.d(TAG, "mTouchSlop="+mTouchSlop); mMinFlingVelocity = config.getScaledMinimumFlingVelocity(); // Log.d(TAG, "mMinFlingVelocity="+mMinFlingVelocity); // Refresh display with current params refreshDrawableState(); setChecked(isChecked()); this.setClickable(true); // this.setOnClickListener(clickListener); } /** * Sets the switch text color, size, style, hint color, and highlight color * from the specified TextAppearance resource. */ public void setSwitchTextAppearance(Context context, int resid) { TypedArray appearance = context.obtainStyledAttributes(resid, R.styleable.mySwitchTextAppearanceAttrib); ColorStateList colors; int ts; colors = appearance .getColorStateList(R.styleable.mySwitchTextAppearanceAttrib_textColor); if (colors != null) { mTextColors = colors; } else { // If no color set in TextAppearance, default to the view's // textColor mTextColors = getTextColors(); } ts = appearance.getDimensionPixelSize( R.styleable.mySwitchTextAppearanceAttrib_textSize, 0); if (ts != 0) { if (ts != mTextPaint.getTextSize()) { mTextPaint.setTextSize(ts); requestLayout(); } } int typefaceIndex, styleIndex; typefaceIndex = appearance.getInt( R.styleable.mySwitchTextAppearanceAttrib_typeface, -1); styleIndex = appearance.getInt( R.styleable.mySwitchTextAppearanceAttrib_textStyle, -1); setSwitchTypefaceByIndex(typefaceIndex, styleIndex); appearance.recycle(); } private void setSwitchTypefaceByIndex(int typefaceIndex, int styleIndex) { Typeface tf = null; switch (typefaceIndex) { case SANS: tf = Typeface.SANS_SERIF; break; case SERIF: tf = Typeface.SERIF; break; case MONOSPACE: tf = Typeface.MONOSPACE; break; } setSwitchTypeface(tf, styleIndex); } /** * Sets the typeface and style in which the text should be displayed on the * switch, and turns on the fake bold and italic bits in the Paint if the * Typeface that you provided does not have all the bits in the style that * you specified. */ public void setSwitchTypeface(Typeface tf, int style) { if (style > 0) { if (tf == null) { tf = Typeface.defaultFromStyle(style); } else { tf = Typeface.create(tf, style); } setSwitchTypeface(tf); // now compute what (if any) algorithmic styling is needed int typefaceStyle = tf != null ? tf.getStyle() : 0; int need = style & ~typefaceStyle; mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0); mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); } else { mTextPaint.setFakeBoldText(false); mTextPaint.setTextSkewX(0); setSwitchTypeface(tf); } } /** * Sets the typeface in which the text should be displayed on the switch. * Note that not all Typeface families actually have bold and italic * variants, so you may need to use * {@link #setSwitchTypeface(Typeface, int)} to get the appearance that you * actually want. * * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle */ public void setSwitchTypeface(Typeface tf) { if (mTextPaint.getTypeface() != tf) { mTextPaint.setTypeface(tf); requestLayout(); invalidate(); } } /** * Returns the text displayed when the button is in the checked state. */ public CharSequence getTextOn() { return mTextOn; } /** * Sets the text displayed when the button is in the checked state. */ public void setTextOn(CharSequence textOn) { mTextOn = textOn; this.mOnLayout = null; requestLayout(); } /** * Returns the text displayed when the button is not in the checked state. */ public CharSequence getTextOff() { return mTextOff; } /** * Sets the text displayed when the button is not in the checked state. */ public void setTextOff(CharSequence textOff) { mTextOff = textOff; this.mOffLayout = null; requestLayout(); } /** * Interface definition for a callback to be invoked when the switch is in a * fixed state and there was an attempt to change its state either via a * click or drag */ public static interface OnChangeAttemptListener { /** * Called when an attempt was made to change the checked state of the * switch while the switch was in a fixed state. * * @param isChecked * The current state of switch. */ void onChangeAttempted(boolean isChecked); } /** * Register a callback to be invoked when there is an attempt to change the * state of the switch when its in fixated * * @param listener * the callback to call on checked state change */ public void setOnChangeAttemptListener(OnChangeAttemptListener listener) { mOnChangeAttemptListener = listener; } /** * fixates the switch on one of the positions ON or OFF. if the switch is * fixated, then it cannot be switched to the other position * * @param fixed * If true, sets the switch to fixed mode. If false, sets the * switch to switched mode. * @param onOrOff * The switch position to which it will be fixed. If it is true * then the switch is fixed on ON. If it is false then the switch * is fixed on OFF * @Note The position is only fixed from the user interface. It can still be * changed through program by using {@link #setChecked(boolean) * setChecked} */ public void fixate(boolean fixed, boolean onOrOff) { fixate(fixed); this.onOrOff = onOrOff; if (onOrOff) this.setChecked(true); } /** * fixates the switch on one of the positions ON or OFF. if the switch is * fixated, then it cannot be switched to the other position * * @param fixed * if true, sets the switch to fixed mode. if false, sets the * switch to switched mode. */ public void fixate(boolean fixed) { this.fixed = fixed; } /** * returns if the switch is fixed to one of its positions */ public boolean isFixed() { return fixed; } private Layout makeLayout(CharSequence text) { return new StaticLayout(text, mTextPaint, (int) android.util.FloatMath.ceil(Layout.getDesiredWidth(text, mTextPaint)), Layout.Alignment.ALIGN_NORMAL, 1.f, 0, true); } /** * @return true if (x, y) is within the target area of the switch thumb */ private boolean hitThumb(float x, float y) { if (mOrientation == HORIZONTAL) { final int thumbTop = mSwitchTop - mTouchSlop; final int thumbLeft = mSwitchLeft + (int) (mThumbPosition + 0.5f) - mTouchSlop; final int thumbRight = thumbLeft + mThumbWidth + mTouchSlop;// + // mThPad.left // + // mThPad.right final int thumbBottom = mSwitchBottom + mTouchSlop; return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom; } // if (mOrientation == VERTICAL) if (mSwitchHeight > 150) { final int thumbLeft = mSwitchLeft - mTouchSlop; final int thumbTop = mSwitchTop + (int) (mThumbPosition + 0.5f) - mTouchSlop; final int thumbBottom = thumbTop + mThumbHeight + mTouchSlop;// + // mThPad.top // + // mThPad.bottom final int thumbRight = mSwitchRight + mTouchSlop; return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom; } else { return x > mSwitchLeft && x < mSwitchRight && y > mSwitchTop && y < mSwitchBottom; } } @Override public boolean onTouchEvent(MotionEvent ev) { // if (fixed) { // Log.d(TAG, "the switch position is fixed to " + (onOrOff ? // "On":"Off") + "position."); // return true; // } mVelocityTracker.addMovement(ev); // Log.d(TAG, "onTouchEvent(ev="+ev.toString()+")"); // Log.d(TAG, "mTouchMode="+mTouchMode); final int action = ev.getActionMasked(); switch (action) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); if (isEnabled() && hitThumb(x, y)) { mTouchMode = TOUCH_MODE_DOWN; mTouchX = x; mTouchY = y; } break; } case MotionEvent.ACTION_MOVE: { switch (mTouchMode) { case TOUCH_MODE_IDLE: // Didn't target the thumb, treat normally. break; case TOUCH_MODE_DOWN: { final float x = ev.getX(); final float y = ev.getY(); if (Math.abs(x - mTouchX) > mTouchSlop / 2 || Math.abs(y - mTouchY) > mTouchSlop / 2) { mTouchMode = TOUCH_MODE_DRAGGING; if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(true); } mTouchX = x; mTouchY = y; return true; } break; } case TOUCH_MODE_DRAGGING: { final float x = ev.getX(); final float dx = x - mTouchX; final float y = ev.getY(); final float dy = y - mTouchY; if (mOrientation == HORIZONTAL) { float newPos = Math.max(0, Math.min(mThumbPosition + dx, getThumbScrollRange())); if (newPos != mThumbPosition) { mThumbPosition = newPos; mTouchX = x; invalidate(); } return true; } if (mOrientation == VERTICAL) { float newPos = Math.max(0, Math.min(mThumbPosition + dy, getThumbScrollRange())); if (newPos != mThumbPosition) { mThumbPosition = newPos; mTouchY = y; invalidate(); } return true; } } } break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { if (mTouchMode == TOUCH_MODE_DRAGGING) { stopDrag(ev); return true; } mTouchMode = TOUCH_MODE_IDLE; mVelocityTracker.clear(); break; } } boolean flag = super.onTouchEvent(ev); // Log.d(TAG, "super.onTouchEvent(ev) returned="+flag); return flag; } /* * OnClickListener clickListener = new OnClickListener() { public void * onClick(View v) { Log.d(TAG, "onClick()"); * animateThumbToCheckedState(isChecked()); } } */ @Override public boolean performClick() { if (!clickDisabled) { // Log.d(TAG, "performClick(). current Value="+isChecked()); if (!fixed) { boolean flag = super.performClick(); // Log.d(TAG, // "after super.performClick(). Value="+isChecked()); return flag; } else { if (this.mOnChangeAttemptListener != null) this.mOnChangeAttemptListener .onChangeAttempted(isChecked()); return false; } } else { return false; } } public void disableClick() { clickDisabled = true; } public void enableClick() { clickDisabled = false; } /* * public void toggleWithAnimation(boolean animate) { toggle(); if (animate) * { animateThumbToCheckedState(isChecked()); } } * * //@Override public boolean isChecked1() { Log.d(TAG, * "isChecked()-mTextOnThumb="+mTextOnThumb); if (mTextOnThumb) { Log.d(TAG, * "returning = "+super.isChecked()); return super.isChecked(); } Log.d(TAG, * "returning="+(!(super.isChecked()))); return !(super.isChecked()); } */ public CharSequence getCurrentText() { if (isChecked()) return mTextOn; return mTextOff; } public CharSequence getText(boolean checkedState) { if (checkedState) return mTextOn; else return mTextOff; } private void cancelSuperTouch(MotionEvent ev) { MotionEvent cancel = MotionEvent.obtain(ev); cancel.setAction(MotionEvent.ACTION_CANCEL); super.onTouchEvent(cancel); cancel.recycle(); } /** * Called from onTouchEvent to end a drag operation. * * @param ev * Event that triggered the end of drag mode - ACTION_UP or * ACTION_CANCEL */ private void stopDrag(MotionEvent ev) { mTouchMode = TOUCH_MODE_IDLE; // Up and not canceled, also checks the switch has not been disabled // during the drag boolean commitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled(); // check if the swtich is fixed to a position commitChange = commitChange && (!fixed); // Log.d(TAG,"commitChange="+commitChange); cancelSuperTouch(ev); if (commitChange) { boolean newState; mVelocityTracker.computeCurrentVelocity(1000); if (mOrientation == HORIZONTAL) { float xvel = mVelocityTracker.getXVelocity(); if (Math.abs(xvel) > mMinFlingVelocity) { newState = xvel > 0; } else { newState = getTargetCheckedState(); } } else { float yvel = mVelocityTracker.getYVelocity(); if (Math.abs(yvel) > mMinFlingVelocity) { newState = yvel > 0; } else { newState = getTargetCheckedState(); } } if (mTextOnThumb) animateThumbToCheckedState(newState); else animateThumbToCheckedState(!newState); } else { animateThumbToCheckedState(isChecked()); if (fixed) if (this.mOnChangeAttemptListener != null) this.mOnChangeAttemptListener .onChangeAttempted(isChecked()); } } private void animateThumbToCheckedState(boolean newCheckedState) { // TODO animate! // float targetPos = newCheckedState ? 0 : getThumbScrollRange(); // mThumbPosition = targetPos; setChecked(newCheckedState); } private boolean getTargetCheckedState() { return mThumbPosition >= getThumbScrollRange() / 2; } @Override public void setChecked(boolean checked) { // Log.d(TAG, "setChecked("+checked+")"); boolean lc = checked; if (!mTextOnThumb) { lc = !checked; } super.setChecked(checked); mThumbPosition = lc ? getThumbScrollRange() : 0; invalidate(); } @SuppressLint("WrongCall") protected void onLayout_orig(boolean changed, int left, int top, int right, int bottom) { // Log.d(TAG, "left=" + left + // ",top="+top+",right="+right+",bottom="+bottom); super.onLayout(changed, left, top, right, bottom); mThumbPosition = isChecked() ? getThumbScrollRange() : 0; int switchRight = getWidth() - getPaddingRight(); int switchLeft = switchRight - mSwitchWidth; int switchTop = 0; int switchBottom = 0; switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) { default: case Gravity.TOP: switchTop = getPaddingTop(); switchBottom = switchTop + mSwitchHeight; break; case Gravity.CENTER_VERTICAL: switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 - mSwitchHeight / 2; switchBottom = switchTop + mSwitchHeight; break; case Gravity.BOTTOM: switchBottom = getHeight() - getPaddingBottom(); switchTop = switchBottom - mSwitchHeight; break; } mSwitchLeft = switchLeft; mSwitchTop = switchTop; mSwitchBottom = switchBottom; mSwitchRight = switchRight; // Log.d(TAG, "mSwitchLeft="+mSwitchLeft+" mSwitchRight="+mSwitchRight); // Log.d(TAG, "mSwitchTop="+mSwitchTop+" mSwitchBottom="+mSwitchBottom); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (mOnLayout == null) { mOnLayout = makeLayout(mTextOn); } if (mOffLayout == null) { mOffLayout = makeLayout(mTextOff); } final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth()); final int maxTextHeight = Math.max(mOnLayout.getHeight(), mOffLayout.getHeight()); mThumbWidth = maxTextWidth + mThumbTextPadding * 2 + mThPad.left + mThPad.right; mThumbWidth = Math.max(mThumbWidth, mThumbDrawable.getIntrinsicWidth()); if (mTextOnThumb == false) { mThumbWidth = mThumbDrawable.getIntrinsicWidth(); if (mThumbWidth < 15) { // TODO: change this to something guessed based on the other // parameters. mThumbWidth = 15; } } mThumbHeight = maxTextHeight + mThumbTextPadding * 2 + mThPad.bottom + mThPad.top; mThumbHeight = Math.max(mThumbHeight, mThumbDrawable.getIntrinsicHeight()); if (mTextOnThumb == false) { mThumbHeight = mThumbDrawable.getIntrinsicHeight(); if (mThumbHeight < 15) { // TODO: change this to something guessed based on the other // parameters. mThumbHeight = 15; } } // Log.d(TAG, "mThumbWidth=" + mThumbWidth); // Log.d(TAG, "mThumbHeight=" + mThumbHeight); int switchWidth; if (mOrientation == HORIZONTAL) { switchWidth = Math.max(mSwitchMinWidth, maxTextWidth * 2 + mThumbTextPadding * 2 + mTrackTextPadding * 2 + mTrackPaddingRect.left + mTrackPaddingRect.right); if (mTextOnThumb == false) { switchWidth = Math.max(maxTextWidth + mThumbWidth + mTrackTextPadding * 2 + (mTrackPaddingRect.right + mTrackPaddingRect.left) / 2, mSwitchMinWidth); } if (this.mPushStyle) { switchWidth = Math.max(mSwitchMinWidth, maxTextWidth + mThumbWidth + mTrackTextPadding + (mTrackPaddingRect.left + mTrackPaddingRect.right) / 2); } } else { switchWidth = Math.max(maxTextWidth + mThumbTextPadding * 2 + mThPad.left + mThPad.right, mThumbWidth); if ((this.mPushStyle) || (mTextOnThumb == false)) { switchWidth = Math.max(maxTextWidth + mTrackTextPadding * 2 + mTrackPaddingRect.left + mTrackPaddingRect.right, mThumbWidth); } } switchWidth = Math.max(mSwitchMinWidth, switchWidth); final int trackHeight = mTrackDrawable.getIntrinsicHeight(); final int thumbHeight = mThumbDrawable.getIntrinsicHeight(); int switchHeight = Math.max(mSwitchMinHeight, maxTextHeight); switchHeight = Math.max(trackHeight, switchHeight); switchHeight = Math.max(switchHeight, thumbHeight); if (mOrientation == VERTICAL) { switchHeight = mOnLayout.getHeight() + mOffLayout.getHeight() + mThumbTextPadding * 2 + mThPad.top + mThPad.bottom + mTrackPaddingRect.bottom + mTrackPaddingRect.top + mTrackTextPadding * 2; if (mTextOnThumb == false) { switchHeight = Math.max(mThumbHeight + maxTextHeight + (mTrackPaddingRect.bottom + mTrackPaddingRect.top) / 2 + mTrackTextPadding * 2, mSwitchMinHeight); } if (this.mPushStyle) { switchHeight = Math.max(mSwitchMinHeight, maxTextHeight + mThumbHeight + mTrackTextPadding + (mTrackPaddingRect.top + mTrackPaddingRect.bottom) / 2); } } switch (widthMode) { case MeasureSpec.AT_MOST: widthSize = Math.min(widthSize, switchWidth); break; case MeasureSpec.UNSPECIFIED: widthSize = switchWidth; break; case MeasureSpec.EXACTLY: // Just use what we were given break; } switch (heightMode) { case MeasureSpec.AT_MOST: heightSize = Math.min(heightSize, switchHeight); break; case MeasureSpec.UNSPECIFIED: heightSize = switchHeight; break; case MeasureSpec.EXACTLY: // Just use what we were given break; } mSwitchWidth = switchWidth; mSwitchHeight = switchHeight; // Log.d(TAG, "onMeasure():mSwitchWidth=" + mSwitchWidth // + " mSwitchHeight=" + mSwitchHeight); super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int measuredHeight = getMeasuredHeight(); final int measuredWidth = getMeasuredWidth(); if (measuredHeight < switchHeight) { setMeasuredDimension(getMeasuredWidth(), switchHeight); } if (measuredWidth < switchWidth) { setMeasuredDimension(switchWidth, getMeasuredHeight()); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { // Log.d(TAG, "onLayout()-left=" + left + ",top=" + top + ",right=" // + right + ",bottom=" + bottom); super.onLayout(changed, left, top, right, bottom); int switchTop = 0; int switchBottom = 0; switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) { default: case Gravity.TOP: switchTop = getPaddingTop(); switchBottom = switchTop + mSwitchHeight; break; case Gravity.CENTER_VERTICAL: switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 - mSwitchHeight / 2; switchBottom = switchTop + mSwitchHeight; break; case Gravity.BOTTOM: switchBottom = getHeight() - getPaddingBottom(); switchTop = switchBottom - mSwitchHeight; break; } // mSwitchWidth = right - left; // mSwitchHeight = bottom - top; mSwitchBottom = mSwitchHeight - getPaddingBottom(); mSwitchTop = mSwitchBottom - mSwitchHeight; mSwitchRight = mSwitchWidth - getPaddingRight(); mSwitchLeft = mSwitchRight - mSwitchWidth; if (this.mTextOnThumb) { mThumbPosition = isChecked() ? getThumbScrollRange() : 0; } else { mThumbPosition = isChecked() ? 0 : getThumbScrollRange(); } // Log.d(TAG, "getWidth()=" + getWidth() + " getHeight()=" + // getHeight()); // Log.d(TAG, "getPaddingLeft()=" + getPaddingLeft() // + " getPaddingRight()=" + getPaddingRight()); // Log.d(TAG, "getPaddingTop()=" + getPaddingTop() // + " getPaddingBottom()=" + getPaddingBottom()); // // Log.d(TAG, "mSwitchWidth=" + mSwitchWidth + " mSwitchHeight=" // + mSwitchHeight); // Log.d(TAG, "mSwitchLeft=" + mSwitchLeft + " mSwitchRight=" // + mSwitchRight); // Log.d(TAG, "mSwitchTop=" + mSwitchTop + " mSwitchBottom=" // + mSwitchBottom); // now that the layout is known, prepare the drawables mTrackDrawable.setBounds(mSwitchLeft, mSwitchTop, mSwitchRight, mSwitchBottom); if (mDrawableOn != null) mDrawableOn.setBounds(0, 0, mDrawableOn.getIntrinsicWidth(), mDrawableOn.getIntrinsicHeight()); if (mDrawableOff != null) mDrawableOff.setBounds(0, 0, mDrawableOff.getIntrinsicWidth(), mDrawableOff.getIntrinsicHeight()); if (mLeftBackground != null) mLeftBackground.setBounds(mSwitchLeft, mSwitchTop, mSwitchRight, mSwitchBottom); if (mRightBackground != null) mRightBackground.setBounds(mSwitchLeft, mSwitchTop, mSwitchRight, mSwitchBottom); if (mMaskDrawable != null) { tempBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, mSwitchBottom - mSwitchTop, Config.ARGB_8888); backingLayer = new Canvas(tempBitmap); mMaskDrawable.setBounds(mSwitchLeft, mSwitchTop, mSwitchRight, mSwitchBottom); // Log.d(TAG,"bitmap width="+tempBitmap.getWidth()+" bitmap.height="+tempBitmap.getHeight()); // Log.d(TAG,"bitmap 0,0="+String.format("%x", // (tempBitmap.getPixel(0,0)))+" bitmap 40,40="+String.format("%x", // (tempBitmap.getPixel(40,40)))); // Bitmap maskBitmap = Bitmap.createBitmap(mSwitchRight - // mSwitchLeft, mSwitchBottom - mSwitchTop, Config.ARGB_8888); // Canvas maskLayer = new Canvas(maskBitmap); mMaskDrawable.draw(backingLayer); // Log.d(TAG,"mask width="+maskBitmap.getWidth()+" mask.height="+maskBitmap.getHeight()); // Log.d(TAG,"mask 0,0="+String.format("%x", // (maskBitmap.getPixel(0,0)))+" mask 40,40="+String.format("%x", // (maskBitmap.getPixel(40,40)))); maskBitmap = tempBitmap.extractAlpha(); // Log.d(TAG,"mask 0,0="+String.format("%x", // (maskBitmap.getPixel(0,0)))+" mask 40,40="+String.format("%x", // (maskBitmap.getPixel(40,40)))); if (mLeftBackground != null) { mLeftBackground.draw(backingLayer); // leftBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, // mSwitchBottom - mSwitchTop, Config.ARGB_8888); // Canvas backingLayer2 = new Canvas(leftBitmap); // backingLayer2.drawBitmap(tempBitmap, 0, 0, null); // backingLayer2.drawBitmap(maskBitmap, 0, 0, xferPaint); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); leftBitmap = tempBitmap.copy(tempBitmap.getConfig(), true); } if (mRightBackground != null) { mRightBackground.draw(backingLayer); // rightBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, // mSwitchBottom - mSwitchTop, Config.ARGB_8888); // Canvas backingLayer3 = new Canvas(rightBitmap); // backingLayer3.drawBitmap(tempBitmap, 0, 0, null); // backingLayer3.drawBitmap(maskBitmap, 0, 0, xferPaint); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); rightBitmap = tempBitmap.copy(tempBitmap.getConfig(), true); } } if (mPushStyle) { // final int switchInnerLeft = mSwitchLeft + mTrackPaddingRect.left; final int switchInnerTop = mSwitchTop + mTrackPaddingRect.top; // final int switchInnerRight = mSwitchRight - // mTrackPaddingRect.right; final int switchInnerBottom = mSwitchBottom - mTrackPaddingRect.bottom; final int switchVerticalMid = (switchInnerTop + switchInnerBottom) / 2; final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth()); final int maxTextHeight = Math.max(mOnLayout.getHeight(), mOffLayout.getHeight()); int width = maxTextWidth * 2 + mTrackPaddingRect.left + mTrackPaddingRect.right + mThumbWidth + mTrackTextPadding * 4; int height = mSwitchBottom - mSwitchTop; if (mOrientation == VERTICAL) { height = mTrackPaddingRect.top + mTrackTextPadding + maxTextHeight + mTrackTextPadding + mThumbHeight + mTrackTextPadding + maxTextHeight + mTrackTextPadding + mTrackPaddingRect.bottom; width = mSwitchRight - mSwitchLeft; } Log.d(TAG, "pushBitmap width=" + width + " height=" + height); pushBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas backingLayer = new Canvas(pushBitmap); mTextPaint.drawableState = getDrawableState(); // mTextColors should not be null, but just in case if (mTextColors != null) { mTextPaint.setColor(mTextColors.getColorForState( getDrawableState(), mTextColors.getDefaultColor())); } // for vertical orientation leftBitmap is used as top bitmap if (leftBitmap != null) { backingLayer.save(); if (backingLayer.getClipBounds(canvasClipBounds)) { if (mOrientation == HORIZONTAL) { canvasClipBounds.right -= width / 2; } if (mOrientation == VERTICAL) { canvasClipBounds.bottom -= height / 2; } backingLayer.clipRect(canvasClipBounds); } backingLayer.drawBitmap(leftBitmap, 0, 0, null); backingLayer.restore(); } if (rightBitmap != null) { backingLayer.save(); if (backingLayer.getClipBounds(canvasClipBounds)) { if (mOrientation == HORIZONTAL) { canvasClipBounds.left += (width) / 2; } if (mOrientation == VERTICAL) { canvasClipBounds.top += (height) / 2; } backingLayer.clipRect(canvasClipBounds); } if (mOrientation == HORIZONTAL) { backingLayer.translate(width / 2 - mTrackPaddingRect.right, 0); } if (mOrientation == VERTICAL) { backingLayer.translate(0, height / 2 - mTrackPaddingRect.bottom); } backingLayer.drawBitmap(rightBitmap, 0, 0, null); backingLayer.restore(); } /* * if (mOrientation == HORIZONTAL) { * backingLayer.translate(mTrackPaddingRect.left, 0); * backingLayer.save(Canvas.MATRIX_SAVE_FLAG); * backingLayer.translate((maxTextWidth - mOffLayout.getWidth())/2, * switchVerticalMid - mOffLayout.getHeight() / 2); * mOffLayout.draw(backingLayer); backingLayer.restore(); * backingLayer.translate(maxTextWidth+ mTrackTextPadding * 2+ * (maxTextWidth - mOnLayout.getWidth())/2 + mThumbWidth+ * mThPad.left + mThPad.right, switchVerticalMid - * mOnLayout.getHeight() / 2); mOnLayout.draw(backingLayer); } * * if (mOrientation == VERTICAL) { * backingLayer.translate(0,mTrackPaddingRect.top); * backingLayer.save(Canvas.MATRIX_SAVE_FLAG); * backingLayer.translate((maxTextWidth - mOffLayout.getWidth())/2, * switchVerticalMid - mOffLayout.getHeight() / 2); * mOffLayout.draw(backingLayer); backingLayer.restore(); * backingLayer.translate((maxTextWidth - mOnLayout.getWidth())/2, * maxTextHeight+ mTrackTextPadding * 2+ (maxTextHeight - * mOnLayout.getHeight())/2 + mThumbWidth+ mThPad.left + * mThPad.top); mOnLayout.draw(backingLayer); } */ } } // Draw the switch @Override protected void onDraw(Canvas canvas) { // Log.d(TAG, // "onDraw()canvas:height="+canvas.getHeight()+" width="+canvas.getWidth()); // Rect canvasClipBounds = canvas.getClipBounds(); // Log.d(TAG, "onDraw()canvas:clipbounds="+canvasClipBounds); // super.onDraw(canvas); int switchInnerLeft = mSwitchLeft + mTrackPaddingRect.left; int switchInnerTop = mSwitchTop + mTrackPaddingRect.top; int switchInnerRight = mSwitchRight - mTrackPaddingRect.right; int switchInnerBottom = mSwitchBottom - mTrackPaddingRect.bottom; int thumbRange = getThumbScrollRange(); int thumbPos = (int) (mThumbPosition + 0.5f); int alpha = mTextPaint.getAlpha(); mTextPaint.drawableState = getDrawableState(); // Log.d(TAG, // "switchInnerLeft="+switchInnerLeft+" switchInnerRight="+switchInnerRight); // Log.d(TAG, // "switchInnerTop="+switchInnerTop+" switchInnerBottom="+switchInnerBottom); // Log.d(TAG, "thumbRange="+thumbRange+" thumbPos="+thumbPos); if (mOrientation == VERTICAL) { int switchHorizontalMid = (switchInnerLeft + switchInnerRight) / 2; int thumbBoundR = mSwitchRight; int thumbBoundT = switchInnerTop + 1 * this.getThumbScrollRange() - mThumbExtraMovement; int thumbBoundB = thumbBoundT + mThumbHeight; if (mPushStyle) { final int maxTextHeight = Math.max(mOnLayout.getHeight(), mOffLayout.getHeight()); // tempBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, // mSwitchBottom - mSwitchTop, Config.ARGB_8888); // backingLayer = new Canvas(tempBitmap); backingLayer.save(); backingLayer.translate(0, -thumbRange + thumbPos); backingLayer.drawBitmap(pushBitmap, 0, 0, null); backingLayer.restore(); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); canvas.drawBitmap(tempBitmap, 0, 0, null); mTrackDrawable.draw(canvas); backingLayer.drawColor(0xff000000, Mode.DST_IN); backingLayer.save(); backingLayer.translate(0, -thumbRange + thumbPos); backingLayer.translate(0, mTrackPaddingRect.top); backingLayer.save(); backingLayer.translate(0, (maxTextHeight - mOffLayout.getHeight()) / 2); if (mDrawableOff != null) mDrawableOff.draw(backingLayer); backingLayer.translate( switchHorizontalMid - mOffLayout.getWidth() / 2, 0); mOffLayout.draw(backingLayer); backingLayer.restore(); backingLayer.translate(0, maxTextHeight + mTrackTextPadding * 2 + (maxTextHeight - mOnLayout.getHeight()) / 2 + mThumbHeight);// + mThPad.left + mThPad.right,) if (mDrawableOn != null) mDrawableOn.draw(backingLayer); backingLayer.translate( switchHorizontalMid - mOnLayout.getWidth() / 2, 0);// + // mThPad.left // + // mThPad.right,) mOnLayout.draw(backingLayer); backingLayer.restore(); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); canvas.drawBitmap(tempBitmap, 0, 0, null); } else { if (rightBitmap != null) { canvas.save(); if (canvas.getClipBounds(canvasClipBounds)) { if (this.mOrientation == HORIZONTAL) { canvasClipBounds.left += (thumbPos + mThumbWidth / 2); } if (this.mOrientation == VERTICAL) { canvasClipBounds.top += (thumbPos + mThumbHeight / 2); } canvas.clipRect(canvasClipBounds); } canvas.drawBitmap(rightBitmap, 0, 0, null); canvas.restore(); } if (leftBitmap != null) { canvas.save(); if (canvas.getClipBounds(canvasClipBounds)) { if (this.mOrientation == HORIZONTAL) { canvasClipBounds.right -= (thumbRange - thumbPos + mThumbWidth / 2); } if (this.mOrientation == VERTICAL) { canvasClipBounds.bottom = (canvasClipBounds.top + thumbPos + mThumbHeight / 2); } canvas.clipRect(canvasClipBounds); } canvas.drawBitmap(leftBitmap, 0, 0, null); canvas.restore(); } // draw the track mTrackDrawable.draw(canvas); canvas.save(); // evaluate the coordinates for drawing the Thumb and Text canvas.clipRect(switchInnerLeft, mSwitchTop, switchInnerRight, mSwitchBottom); // mTextColors should not be null, but just in case if (mTextColors != null) { mTextPaint.setColor(mTextColors.getColorForState( getDrawableState(), mTextColors.getDefaultColor())); } // draw the texts for On/Off in reduced alpha mode. if (this.getTargetCheckedState() ^ (mTextOnThumb)) mTextPaint.setAlpha(alpha / 4); else mTextPaint.setAlpha(alpha); thumbBoundT = switchInnerTop + 1 * this.getThumbScrollRange() - mThumbExtraMovement; thumbBoundB = thumbBoundT + mThumbHeight; canvas.save(); canvas.translate(0, (thumbBoundT + thumbBoundB) / 2 - mOnLayout.getHeight() / 2); if ((mDrawableOn != null) && (mTextPaint.getAlpha() == alpha)) mDrawableOn.draw(canvas); canvas.translate( (mSwitchLeft + mSwitchRight) / 2 - mOnLayout.getWidth() / 2, 0); mOnLayout.draw(canvas); canvas.restore(); // mTextColors should not be null, but just in case if (mTextColors != null) { mTextPaint.setColor(mTextColors.getColorForState( getDrawableState(), mTextColors.getDefaultColor())); } if (this.getTargetCheckedState() ^ (mTextOnThumb)) mTextPaint.setAlpha(alpha); else mTextPaint.setAlpha(alpha / 4); thumbBoundT = switchInnerTop + 0 * this.getThumbScrollRange() - mThumbExtraMovement; thumbBoundB = thumbBoundT + mThumbHeight; canvas.save(); canvas.translate(0, (thumbBoundT + thumbBoundB) / 2 - mOffLayout.getHeight() / 2); if ((mDrawableOff != null) && (mTextPaint.getAlpha() == alpha)) mDrawableOff.draw(canvas); canvas.translate( (mSwitchLeft + mSwitchRight) / 2 - mOffLayout.getWidth() / 2, 0); mOffLayout.draw(canvas); canvas.restore(); canvas.restore(); } thumbBoundT = switchInnerTop + thumbPos - mThumbExtraMovement; thumbBoundB = switchInnerTop + thumbPos - mThumbExtraMovement + mThumbHeight; // Draw the Thumb // Log.d(TAG, "thumbBoundT, thumbBoundB=(" + thumbBoundT + "," // + thumbBoundB + ")"); // Log.d(TAG, "mSwitchLeft, mSwitchRight=(" + mSwitchLeft + "," // + mSwitchRight + ")"); mThumbDrawable.setBounds(mSwitchLeft, thumbBoundT, mSwitchRight, thumbBoundB); mThumbDrawable.draw(canvas); mTextPaint.setAlpha(alpha); // Draw the text on the Thumb if (mTextOnThumb) { Layout offSwitchText = getTargetCheckedState() ? mOnLayout : mOffLayout; canvas.save(); canvas.translate( (mSwitchLeft + mSwitchRight) / 2 - offSwitchText.getWidth() / 2, (thumbBoundT + thumbBoundB) / 2 - offSwitchText.getHeight() / 2); // (switchInnerTop + switchInnerBottom) / 2 - // onSwitchText.getHeight() - this.mThumbTextPadding); offSwitchText.draw(canvas); canvas.restore(); } } if (mOrientation == HORIZONTAL) { int thumbL = switchInnerLeft;// + mThPad.left; int thumbR = switchInnerLeft + mThumbWidth;// - mThPad.right; int dxOffText = mTextOnThumb ? (thumbL + thumbR) / 2 - mOffLayout.getWidth() / 2 + mTrackTextPadding - mThumbTextPadding // (thumbL+thumbR)/2 already has // 2*mThumbTextPadding // so we have to subtract it : switchInnerLeft + mTrackTextPadding; thumbL = thumbL + thumbRange; thumbR = thumbR + thumbRange; int dxOnText = mTextOnThumb ? (thumbL + thumbR) / 2 - mOnLayout.getWidth() / 2 // (thumbL + thumbR)/2 already has the ThumbTextPadding // so we dont have to add it : switchInnerRight - mOnLayout.getWidth() - mTrackTextPadding; int switchVerticalMid = (switchInnerTop + switchInnerBottom) / 2; int thumbBoundL = switchInnerLeft + thumbPos - mThumbExtraMovement;// + // mThPad.left int thumbBoundR = switchInnerLeft + thumbPos + mThumbWidth - mThumbExtraMovement;// - mThPad.right if (mPushStyle) { final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth()); // tempBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, // mSwitchBottom - mSwitchTop, Config.ARGB_8888); // backingLayer = new Canvas(tempBitmap); backingLayer.save(); backingLayer.translate(-thumbRange + thumbPos, 0); backingLayer.drawBitmap(pushBitmap, 0, 0, null); backingLayer.restore(); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); canvas.drawBitmap(tempBitmap, 0, 0, null); mTrackDrawable.draw(canvas); backingLayer.drawColor(0xff000000, Mode.DST_IN); backingLayer.save(); backingLayer.translate(-thumbRange + thumbPos, 0); backingLayer.translate(mTrackPaddingRect.left, 0); backingLayer.save(); backingLayer.translate( (maxTextWidth - mOffLayout.getWidth()) / 2, switchVerticalMid - mOffLayout.getHeight() / 2); mOffLayout.draw(backingLayer); if (mDrawableOff != null) mDrawableOff.draw(backingLayer); backingLayer.restore(); backingLayer.translate(maxTextWidth + mTrackTextPadding * 2 + (maxTextWidth - mOnLayout.getWidth()) / 2 + mThumbWidth,// + mThPad.left + mThPad.right, switchVerticalMid - mOnLayout.getHeight() / 2); mOnLayout.draw(backingLayer); if (mDrawableOn != null) mDrawableOn.draw(backingLayer); backingLayer.restore(); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); canvas.drawBitmap(tempBitmap, 0, 0, null); } else { if (rightBitmap != null) { canvas.save(); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.left += (mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } canvas.drawBitmap(rightBitmap, 0, 0, null); canvas.restore(); } if (leftBitmap != null) { canvas.save(); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.right -= (thumbRange - mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } canvas.drawBitmap(leftBitmap, 0, 0, null); canvas.restore(); } // draw the track mTrackDrawable.draw(canvas); // evaluate the coordinates for drawing the Thumb and Text canvas.save(); canvas.clipRect(switchInnerLeft, mSwitchTop, switchInnerRight, mSwitchBottom); // mTextColors should not be null, but just in case if (mTextColors != null) { mTextPaint.setColor(mTextColors.getColorForState( getDrawableState(), mTextColors.getDefaultColor())); } // draw the texts for On/Off in reduced alpha mode. mTextPaint.setAlpha(alpha / 4); if (getTargetCheckedState()) { canvas.save(); canvas.translate(dxOnText, switchVerticalMid - mOnLayout.getHeight() / 2); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.left += (mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } mOnLayout.draw(canvas); if (mDrawableOn != null) mDrawableOn.draw(canvas); canvas.restore(); if (mTextOnThumb == false) mTextPaint.setAlpha(alpha); canvas.save(); canvas.translate(dxOffText, switchVerticalMid - mOffLayout.getHeight() / 2); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.right -= (thumbRange - mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } mOffLayout.draw(canvas); if (mDrawableOff != null) mDrawableOff.draw(canvas); canvas.restore(); } else { canvas.save(); canvas.translate(dxOffText, switchVerticalMid - mOffLayout.getHeight() / 2); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.right -= (thumbRange - mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } mOffLayout.draw(canvas); if (mDrawableOff != null) mDrawableOff.draw(canvas); canvas.restore(); if (mTextOnThumb == false) mTextPaint.setAlpha(alpha); canvas.save(); canvas.translate(dxOnText, switchVerticalMid - mOnLayout.getHeight() / 2); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.left += (mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } mOnLayout.draw(canvas); if (mDrawableOn != null) mDrawableOn.draw(canvas); canvas.restore(); } canvas.restore(); } // Draw the Thumb // Log.d(TAG, // "thumbBoundL, thumbBoundR=("+thumbBoundL+","+thumbBoundR+")"); mThumbDrawable.setBounds(thumbBoundL, mSwitchTop, thumbBoundR, mSwitchBottom); mThumbDrawable.draw(canvas); // Draw the text on the Thumb if (mTextOnThumb) { mTextPaint.setAlpha(alpha); Layout onSwitchText = getTargetCheckedState() ? mOnLayout : mOffLayout; canvas.save(); canvas.translate( (thumbBoundL + thumbBoundR) / 2 - onSwitchText.getWidth() / 2, (switchInnerTop + switchInnerBottom) / 2 - onSwitchText.getHeight() / 2); onSwitchText.draw(canvas); canvas.restore(); } } } @Override public int getCompoundPaddingRight() { int padding = super.getCompoundPaddingRight() + mSwitchWidth; if (!TextUtils.isEmpty(getText())) { padding += mSwitchPadding; } return padding; } @Override public int getCompoundPaddingTop() { int padding = super.getCompoundPaddingTop() + mSwitchHeight; if (!TextUtils.isEmpty(getText())) { padding += mSwitchPadding; } return padding; } private int getThumbScrollRange() { if (mTrackDrawable == null) { return 0; } int range = 0; if (mOrientation == VERTICAL) range = mSwitchHeight - mThumbHeight - mTrackPaddingRect.top - mTrackPaddingRect.bottom + mThumbExtraMovement * 2; if (mOrientation == HORIZONTAL) range = mSwitchWidth - mThumbWidth - mTrackPaddingRect.left - mTrackPaddingRect.right + mThumbExtraMovement * 2; if (this.mPushStyle) range += this.mTrackTextPadding * 2; // Log.d(TAG,"getThumbScrollRange() = "+ range); return range; } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); int[] myDrawableState = getDrawableState(); // Set the state of the Drawable // Drawable may be null when checked state is set from XML, from super // constructor if (mThumbDrawable != null) mThumbDrawable.setState(myDrawableState); if (mTrackDrawable != null) mTrackDrawable.setState(myDrawableState); invalidate(); } @Override protected boolean verifyDrawable(Drawable who) { return super.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable; } }
Java
package net.cardgame.oraclecard.common; import android.widget.ImageView; public interface CustomAnimationListener { public void onEndAnimation(ImageView imageview); }
Java
/** Automatically generated file. DO NOT MODIFY */ package jp.jma.oraclecard; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
/** Automatically generated file. DO NOT MODIFY */ package gracedave.CoopATMFinder; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package gracedave.CoopATMFinder; import android.app.Activity; import android.os.Bundle; public class CoopATMFinderActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
Java
package com.hlidskialf.android.hardware; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; public class ShakeListener implements SensorEventListener { private static final int FORCE_THRESHOLD = 350; private static final int TIME_THRESHOLD = 100; private static final int SHAKE_TIMEOUT = 500; private static final int SHAKE_DURATION = 1000; private static final int SHAKE_COUNT = 3; private SensorManager mSensorMgr; private Sensor mSensor; private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f; private long mLastTime; private OnShakeListener mShakeListener; private Context mContext; private int mShakeCount = 0; private long mLastShake; private long mLastForce; public interface OnShakeListener { public void onShake(); } public ShakeListener(Context context) { mContext = context; resume(); } public void setOnShakeListener(OnShakeListener listener) { mShakeListener = listener; } public void resume() { mSensorMgr = (SensorManager) mContext .getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorMgr .getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER); if (mSensorMgr == null) { throw new UnsupportedOperationException("Sensors not supported"); } boolean supported = mSensorMgr.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_GAME); if (!supported) { mSensorMgr.unregisterListener(this, mSensor); throw new UnsupportedOperationException( "Accelerometer not supported"); } } public void pause() { if (mSensorMgr != null) { mSensorMgr.unregisterListener(this, mSensor); mSensorMgr = null; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { Sensor sensor = event.sensor; float[] values = event.values; if (sensor.getType() != SensorManager.SENSOR_ACCELEROMETER) return; long now = System.currentTimeMillis(); if ((now - mLastForce) > SHAKE_TIMEOUT) { mShakeCount = 0; } if ((now - mLastTime) > TIME_THRESHOLD) { long diff = now - mLastTime; float speed = Math.abs(values[SensorManager.DATA_X] + values[SensorManager.DATA_Y] + values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000; if (speed > FORCE_THRESHOLD) { if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) { mLastShake = now; mShakeCount = 0; if (mShakeListener != null) { mShakeListener.onShake(); } } mLastForce = now; } mLastTime = now; mLastX = values[SensorManager.DATA_X]; mLastY = values[SensorManager.DATA_Y]; mLastZ = values[SensorManager.DATA_Z]; } } }
Java
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (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.commonsware.cwac.sacklist; import java.util.ArrayList; import java.util.List; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; /** * Adapter that simply returns row views from a list. * * If you supply a size, you must implement newView(), to create a required * view. The adapter will then cache these views. * * If you supply a list of views in the constructor, that list will be used * directly. If any elements in the list are null, then newView() will be called * just for those slots. * * Subclasses may also wish to override areAllItemsEnabled() (default: false) * and isEnabled() (default: false), if some of their rows should be selectable. * * It is assumed each view is unique, and therefore will not get recycled. * * Note that this adapter is not designed for long lists. It is more for screens * that should behave like a list. This is particularly useful if you combine * this with other adapters (e.g., SectionedAdapter) that might have an * arbitrary number of rows, so it all appears seamless. */ public class SackOfViewsAdapter extends BaseAdapter { private List<View> views = null; /** * Constructor creating an empty list of views, but with a specified count. * Subclasses must override newView(). */ public SackOfViewsAdapter(int count) { super(); views = new ArrayList<View>(count); for (int i = 0; i < count; i++) { views.add(null); } } /** * Constructor wrapping a supplied list of views. Subclasses must override * newView() if any of the elements in the list are null. */ public SackOfViewsAdapter(List<View> views) { super(); this.views = views; } /** * Get the data item associated with the specified position in the data set. * * @param position * Position of the item whose data we want */ @Override public Object getItem(int position) { return (views.get(position)); } /** * How many items are in the data set represented by this Adapter. */ @Override public int getCount() { return (views.size()); } /** * Returns the number of types of Views that will be created by getView(). */ @Override public int getViewTypeCount() { return (getCount()); } /** * Get the type of View that will be created by getView() for the specified * item. * * @param position * Position of the item whose data we want */ @Override public int getItemViewType(int position) { return (position); } /** * Are all items in this ListAdapter enabled? If yes it means all items are * selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return (false); } /** * Returns true if the item at the specified position is not a separator. * * @param position * Position of the item whose data we want */ @Override public boolean isEnabled(int position) { return (false); } /** * Get a View that displays the data at the specified position in the data * set. * * @param position * Position of the item whose data we want * @param convertView * View to recycle, if not null * @param parent * ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { View result = views.get(position); if (result == null) { result = newView(position, parent); views.set(position, result); } return (result); } /** * Get the row id associated with the specified position in the list. * * @param position * Position of the item whose data we want */ @Override public long getItemId(int position) { return (position); } /** * Create a new View to go into the list at the specified position. * * @param position * Position of the item whose data we want * @param parent * ViewGroup containing the returned View */ protected View newView(int position, ViewGroup parent) { throw new RuntimeException("You must override newView()!"); } }
Java
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (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.commonsware.cwac.merge; import java.util.ArrayList; import java.util.List; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.SectionIndexer; import com.commonsware.cwac.sacklist.SackOfViewsAdapter; /** * Adapter that merges multiple child adapters and views into a single * contiguous whole. * * Adapters used as pieces within MergeAdapter must have view type IDs * monotonically increasing from 0. Ideally, adapters also have distinct ranges * for their row ids, as returned by getItemId(). * */ public class MergeAdapter extends BaseAdapter implements SectionIndexer { private ArrayList<ListAdapter> pieces = new ArrayList<ListAdapter>(); /** * Stock constructor, simply chaining to the superclass. */ public MergeAdapter() { super(); } /** * Adds a new adapter to the roster of things to appear in the aggregate * list. * * @param adapter * Source for row views for this section */ public void addAdapter(ListAdapter adapter) { pieces.add(adapter); adapter.registerDataSetObserver(new CascadeDataSetObserver()); } /** * Adds a new View to the roster of things to appear in the aggregate list. * * @param view * Single view to add */ public void addView(View view) { addView(view, false); } /** * Adds a new View to the roster of things to appear in the aggregate list. * * @param view * Single view to add * @param enabled * false if views are disabled, true if enabled */ public void addView(View view, boolean enabled) { ArrayList<View> list = new ArrayList<View>(1); list.add(view); addViews(list, enabled); } /** * Adds a list of views to the roster of things to appear in the aggregate * list. * * @param views * List of views to add */ public void addViews(List<View> views) { addViews(views, false); } /** * Adds a list of views to the roster of things to appear in the aggregate * list. * * @param views * List of views to add * @param enabled * false if views are disabled, true if enabled */ public void addViews(List<View> views, boolean enabled) { if (enabled) { addAdapter(new EnabledSackAdapter(views)); } else { addAdapter(new SackOfViewsAdapter(views)); } } /** * Get the data item associated with the specified position in the data set. * * @param position * Position of the item whose data we want */ @Override public Object getItem(int position) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece.getItem(position)); } position -= size; } return (null); } /** * Get the adapter associated with the specified position in the data set. * * @param position * Position of the item whose adapter we want */ public ListAdapter getAdapter(int position) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece); } position -= size; } return (null); } /** * How many items are in the data set represented by this Adapter. */ @Override public int getCount() { int total = 0; for (ListAdapter piece : pieces) { total += piece.getCount(); } return (total); } /** * Returns the number of types of Views that will be created by getView(). */ @Override public int getViewTypeCount() { int total = 0; for (ListAdapter piece : pieces) { total += piece.getViewTypeCount(); } return (Math.max(total, 1)); // needed for setListAdapter() before // content add' } /** * Get the type of View that will be created by getView() for the specified * item. * * @param position * Position of the item whose data we want */ @Override public int getItemViewType(int position) { int typeOffset = 0; int result = -1; for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { result = typeOffset + piece.getItemViewType(position); break; } position -= size; typeOffset += piece.getViewTypeCount(); } return (result); } /** * Are all items in this ListAdapter enabled? If yes it means all items are * selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return (false); } /** * Returns true if the item at the specified position is not a separator. * * @param position * Position of the item whose data we want */ @Override public boolean isEnabled(int position) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece.isEnabled(position)); } position -= size; } return (false); } /** * Get a View that displays the data at the specified position in the data * set. * * @param position * Position of the item whose data we want * @param convertView * View to recycle, if not null * @param parent * ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece.getView(position, convertView, parent)); } position -= size; } return (null); } /** * Get the row id associated with the specified position in the list. * * @param position * Position of the item whose data we want */ @Override public long getItemId(int position) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece.getItemId(position)); } position -= size; } return (-1); } @Override public int getPositionForSection(int section) { int position = 0; for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] sections = ((SectionIndexer) piece).getSections(); int numSections = 0; if (sections != null) { numSections = sections.length; } if (section < numSections) { return (position + ((SectionIndexer) piece) .getPositionForSection(section)); } else if (sections != null) { section -= numSections; } } position += piece.getCount(); } return (0); } @Override public int getSectionForPosition(int position) { int section = 0; for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { if (piece instanceof SectionIndexer) { return (section + ((SectionIndexer) piece) .getSectionForPosition(position)); } return (0); } else { if (piece instanceof SectionIndexer) { Object[] sections = ((SectionIndexer) piece).getSections(); if (sections != null) { section += sections.length; } } } position -= size; } return (0); } @Override public Object[] getSections() { ArrayList<Object> sections = new ArrayList<Object>(); for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] curSections = ((SectionIndexer) piece).getSections(); if (curSections != null) { for (Object section : curSections) { sections.add(section); } } } } if (sections.size() == 0) { return (null); } return (sections.toArray(new Object[0])); } private static class EnabledSackAdapter extends SackOfViewsAdapter { public EnabledSackAdapter(List<View> views) { super(views); } @Override public boolean areAllItemsEnabled() { return (true); } @Override public boolean isEnabled(int position) { return (true); } } private class CascadeDataSetObserver extends DataSetObserver { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { notifyDataSetInvalidated(); } } }
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; import com.ch_linghu.fanfoudroid.R; public class FanfouWidgetSmall extends AppWidgetProvider { public final String TAG = "FanfouWidgetSmall"; public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidgetSmall.NEXT"; public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidgetSmall.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.small_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(false); } 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, FanfouWidgetSmall.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_small_initial_layout); // updateViews.setTextViewText(R.id.small_status_text, // TextHelper.getSimpleTweetText("请登录")); // updateViews.setTextViewText(R.id.small_status_screen_name, ""); // updateViews.setTextViewText(R.id.small_tweet_source, ""); // updateViews.setTextViewText(R.id.small_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, FanfouWidgetSmall.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_small_initial_layout); Tweet t = tweets.get(position); Log.d(TAG, "tweet=" + t); // updateViews.setTextViewText(R.id.small_status_screen_name, t.screenName); // updateViews.setTextViewText(R.id.small_status_text, // TextHelper.getSimpleTweetText(t.text)); // // updateViews.setTextViewText(R.id.small_tweet_source, // context.getString(R.string.tweet_source_prefix) + t.source); // updateViews.setTextViewText(R.id.small_tweet_created_at, // DateTimeHelper.getRelativeDate(t.createdAt)); // // updateViews.setImageViewBitmap(R.id.small_status_image, // TwitterApplication.mImageLoader.get(t.profileImageUrl, // new CacheCallback(updateViews))); // Intent inext = new Intent(context, FanfouWidgetSmall.class); // inext.setAction(NEXTACTION); // PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext, // PendingIntent.FLAG_UPDATE_CURRENT); // updateViews.setOnClickPendingIntent(R.id.small_btn_next, pinext); // Intent ipre = new Intent(context, FanfouWidgetSmall.class); // ipre.setAction(PREACTION); // PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre, // PendingIntent.FLAG_UPDATE_CURRENT); // updateViews.setOnClickPendingIntent(R.id.small_btn_pre, pipre); Intent write = WriteActivity.createNewTweetIntent(""); PendingIntent piwrite = PendingIntent.getActivity(context, 0, write, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.small_write_message, piwrite); Intent home = TwitterActivity.createIntent(context); PendingIntent pihome = PendingIntent.getActivity(context, 0, home, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.small_logo_image, pihome); Intent status = StatusActivity.createIntent(t); PendingIntent pistatus = PendingIntent.getActivity(context, 0, status, PendingIntent.FLAG_UPDATE_CURRENT); // updateViews.setOnClickPendingIntent(R.id.small_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.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; import com.ch_linghu.fanfoudroid.R; /** * * @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(false); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { this.userId = myself; this.userName = TwitterApplication.getMyselfName(false); } 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; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.fanfou.Query; import com.ch_linghu.fanfoudroid.fanfou.QueryResult; 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.TwitterListBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter; import com.ch_linghu.fanfoudroid.R; import com.markupartist.android.widget.PullToRefreshListView; import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener; public class SearchResultActivity extends TwitterListBaseActivity { private static final String TAG = "SearchActivity"; // Views. private PullToRefreshListView mTweetList; private View mListFooter; private ProgressBar loadMoreGIF; // State. private String mSearchQuery; private ArrayList<Tweet> mTweets; private TweetArrayAdapter mAdapter; private int mNextPage = 1; private String mLastId = null; private boolean mIsGetMore = false; private static class State { State(SearchResultActivity activity) { mTweets = activity.mTweets; mNextPage = activity.mNextPage; mLastId = activity.mLastId; } public ArrayList<Tweet> mTweets; public int mNextPage; public String mLastId; } // Tasks. private GenericTask mSearchTask; private TaskListener mSearchTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { if (mIsGetMore){ loadMoreGIF.setVisibility(View.VISIBLE); } if (mNextPage == 1) { updateProgress(getString(R.string.page_status_refreshing)); } else { updateProgress(getString(R.string.page_status_refreshing)); } mTweetList.prepareForRefresh(); } @Override public void onProgressUpdate(GenericTask task, Object param) { draw(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { loadMoreGIF.setVisibility(View.GONE); mTweetList.onRefreshComplete(); if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { draw(); if (!mIsGetMore){ mTweetList.setSelection(1); } } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "SearchTask"; } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { Intent intent = getIntent(); // Assume it's SEARCH. // String action = intent.getAction(); mSearchQuery = intent.getStringExtra(SearchManager.QUERY); if (TextUtils.isEmpty(mSearchQuery)) { mSearchQuery = intent.getData().getLastPathSegment(); } mNavbar.setHeaderTitle(mSearchQuery); setTitle(mSearchQuery); State state = (State) getLastNonConfigurationInstance(); if (state != null) { mTweets = state.mTweets; mNextPage = state.mNextPage; mLastId = state.mLastId; draw(); } else { doSearch(false); } return true; } else { return false; } } @Override protected int getLayoutId() { return R.layout.main; } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override public Object onRetainNonConfigurationInstance() { return createState(); } private synchronized State createState() { return new State(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mSearchTask != null && mSearchTask.getStatus() == GenericTask.Status.RUNNING) { mSearchTask.cancel(true); } super.onDestroy(); } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } @Override protected void draw() { mAdapter.refresh(mTweets); } private void doSearch(boolean isGetMore) { Log.d(TAG, "Attempting search."); if (mSearchTask != null && mSearchTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mIsGetMore = isGetMore; mSearchTask = new SearchTask(); mSearchTask.setFeedback(mFeedback); mSearchTask.setListener(mSearchTaskListener); mSearchTask.execute(); } } private class SearchTask extends GenericTask { ArrayList<Tweet> mTweets = new ArrayList<Tweet>(); @Override protected TaskResult _doInBackground(TaskParams... params) { QueryResult result; try { Query query = new Query(mSearchQuery); if (!TextUtils.isEmpty(mLastId)) { query.setMaxId(mLastId); } result = getApi().search(query);// .search(mSearchQuery, // mNextPage); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } List<com.ch_linghu.fanfoudroid.fanfou.Status> statuses = result .getStatus(); HashSet<String> imageUrls = new HashSet<String>(); publishProgress(SimpleFeedback.calProgressBySize(40, 20, statuses)); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statuses) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet; tweet = Tweet.create(status); mLastId = tweet.id; mTweets.add(tweet); imageUrls.add(tweet.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } addTweets(mTweets); // if (isCancelled()) { // return TaskResult.CANCELLED; // } // // publishProgress(); // // // TODO: what if orientation change? // ImageManager imageManager = getImageManager(); // MemoryImageCache imageCache = new MemoryImageCache(); // // for (String imageUrl : imageUrls) { // if (!Utils.isEmpty(imageUrl)) { // // Fetch image to cache. // try { // Bitmap bitmap = imageManager.fetchImage(imageUrl); // imageCache.put(imageUrl, bitmap); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } // // if (isCancelled()) { // return TaskResult.CANCELLED; // } // } // // addImages(imageCache); return TaskResult.OK; } } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } public void doGetMore() { if (!isLastPage()) { doSearch(true); } } public boolean isLastPage() { return mNextPage == -1; } @Override protected void adapterRefresh() { mAdapter.refresh(mTweets); } private synchronized void addTweets(ArrayList<Tweet> tweets) { if (tweets.size() == 0) { mNextPage = -1; return; } mTweets.addAll(tweets); ++mNextPage; } @Override protected String getActivityTitle() { return mSearchQuery; } @Override protected Tweet getContextItemTweet(int position) { if (position >= 1 && position <= mAdapter.getCount()) { Tweet item = (Tweet) mAdapter.getItem(position - 1); if (item == null) { return null; } else { return item; } } else { return null; } } @Override protected TweetAdapter getTweetAdapter() { return mAdapter; } @Override protected ListView getTweetList() { return mTweetList; } @Override protected void updateTweet(Tweet tweet) { // TODO Simple and stupid implementation for (Tweet t : mTweets) { if (t.id.equals(tweet.id)) { t.favorited = tweet.favorited; break; } } } @Override protected boolean useBasicMenu() { return true; } @Override protected void setupState() { mTweets = new ArrayList<Tweet>(); mTweetList = (PullToRefreshListView) findViewById(R.id.tweet_list); mAdapter = new TweetArrayAdapter(this); mTweetList.setAdapter(mAdapter); mTweetList.setOnRefreshListener(new OnRefreshListener(){ @Override public void onRefresh(){ doRetrieve(); } }); // Add Footer to ListView mListFooter = View.inflate(this, R.layout.listview_footer, null); mTweetList.addFooterView(mListFooter, null, true); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); } @Override public void doRetrieve() { doSearch(false); } @Override protected void specialItemClicked(int position) { // 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别 // 前者仅包含数据的数量(不包括foot和head),后者包含foot和head // 因此在同时存在foot和head的情况下,list.count = adapter.count + 2 if (position == 0) { doRetrieve(); } else if (position == mTweetList.getCount() - 1) { // 最后一个Item(footer) doGetMore(); } } }
Java
package com.ch_linghu.fanfoudroid.service; public interface IService { void startService(); void stopService(); }
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
/* * 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 java.text.DateFormat; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.FanfouWidget; import com.ch_linghu.fanfoudroid.FanfouWidgetSmall; import com.ch_linghu.fanfoudroid.MentionActivity; 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.data.Dm; 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.fanfou.Paging; 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; import com.ch_linghu.fanfoudroid.util.TextHelper; public class TwitterService extends Service { private static final String TAG = "TwitterService"; private NotificationManager mNotificationManager; private ArrayList<Tweet> mNewTweets; private ArrayList<Tweet> mNewMentions; private ArrayList<Dm> mNewDms; private GenericTask mRetrieveTask; public String getUserId() { return TwitterApplication.getMyselfId(false); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // fetchMessages(); // handler.postDelayed(mTask, 10000); Log.d(TAG, "Start Once"); return super.onStartCommand(intent, flags, startId); } private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences preferences = TwitterApplication.mPref; boolean needCheck = preferences.getBoolean( Preferences.CHECK_UPDATES_KEY, false); boolean timeline_only = preferences.getBoolean( Preferences.TIMELINE_ONLY_KEY, false); boolean replies_only = preferences.getBoolean( Preferences.REPLIES_ONLY_KEY, true); boolean dm_only = preferences.getBoolean( Preferences.DM_ONLY_KEY, true); if (needCheck) { if (timeline_only) { processNewTweets(); } if (replies_only) { processNewMentions(); } if (dm_only) { processNewDms(); } } } // 原widget try { Intent intent = new Intent(TwitterService.this, FanfouWidget.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); PendingIntent pi = PendingIntent.getBroadcast( TwitterService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); pi.send(); } catch (CanceledException e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } // 小widget // try { // Intent intent = new Intent(TwitterService.this, // FanfouWidgetSmall.class); // intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); // PendingIntent pi = PendingIntent.getBroadcast( // TwitterService.this, 0, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // pi.send(); // } catch (CanceledException e) { // Log.e(TAG, e.getMessage()); // e.printStackTrace(); // } stopSelf(); } @Override public String getName() { return "ServiceRetrieveTask"; } }; private WakeLock mWakeLock; @Override public IBinder onBind(Intent intent) { return null; } private TwitterDatabase getDb() { return TwitterApplication.mDb; } private Weibo getApi() { return TwitterApplication.mApi; } @Override public void onCreate() { Log.v(TAG, "Server Created"); super.onCreate(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); mWakeLock.acquire(); boolean needCheck = TwitterApplication.mPref.getBoolean( Preferences.CHECK_UPDATES_KEY, false); boolean widgetIsEnabled = TwitterService.widgetIsEnabled; Log.v(TAG, "Check Updates is " + needCheck + "/wg:" + widgetIsEnabled); if (!needCheck && !widgetIsEnabled) { Log.d(TAG, "Check update preference is false."); stopSelf(); return; } if (!getApi().isLoggedIn()) { Log.d(TAG, "Not logged in."); stopSelf(); return; } schedule(TwitterService.this); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNewTweets = new ArrayList<Tweet>(); mNewMentions = new ArrayList<Tweet>(); mNewDms = new ArrayList<Dm>(); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute((TaskParams[]) null); } } private void processNewTweets() { int count = mNewTweets.size(); if (count <= 0) { return; } Tweet latestTweet = mNewTweets.get(0); String title; String text; if (count == 1) { title = latestTweet.screenName; text = TextHelper.getSimpleTweetText(latestTweet.text); } else { title = getString(R.string.service_new_twitter_updates); text = getString(R.string.service_x_new_tweets); text = MessageFormat.format(text, count); } PendingIntent intent = PendingIntent.getActivity(this, 0, TwitterActivity.createIntent(this), 0); notify(intent, TWEET_NOTIFICATION_ID, R.drawable.notify_tweet, TextHelper.getSimpleTweetText(latestTweet.text), title, text); } private void processNewMentions() { int count = mNewMentions.size(); if (count <= 0) { return; } Tweet latestTweet = mNewMentions.get(0); String title; String text; if (count == 1) { title = latestTweet.screenName; text = TextHelper.getSimpleTweetText(latestTweet.text); } else { title = getString(R.string.service_new_mention_updates); text = getString(R.string.service_x_new_mentions); text = MessageFormat.format(text, count); } PendingIntent intent = PendingIntent.getActivity(this, 0, MentionActivity.createIntent(this), 0); notify(intent, MENTION_NOTIFICATION_ID, R.drawable.notify_mention, TextHelper.getSimpleTweetText(latestTweet.text), title, text); } private static int TWEET_NOTIFICATION_ID = 0; private static int DM_NOTIFICATION_ID = 1; private static int MENTION_NOTIFICATION_ID = 2; private void notify(PendingIntent intent, int notificationId, int notifyIconId, String tickerText, String title, String text) { Notification notification = new Notification(notifyIconId, tickerText, System.currentTimeMillis()); notification.setLatestEventInfo(this, title, text, intent); notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_SHOW_LIGHTS; notification.ledARGB = 0xFF84E4FA; notification.ledOnMS = 5000; notification.ledOffMS = 5000; String ringtoneUri = TwitterApplication.mPref.getString( Preferences.RINGTONE_KEY, null); if (ringtoneUri == null) { notification.defaults |= Notification.DEFAULT_SOUND; } else { notification.sound = Uri.parse(ringtoneUri); } if (TwitterApplication.mPref.getBoolean(Preferences.VIBRATE_KEY, false)) { notification.defaults |= Notification.DEFAULT_VIBRATE; } mNotificationManager.notify(notificationId, notification); } private void processNewDms() { int count = mNewDms.size(); if (count <= 0) { return; } Dm latest = mNewDms.get(0); String title; String text; if (count == 1) { title = latest.screenName; text = TextHelper.getSimpleTweetText(latest.text); } else { title = getString(R.string.service_new_direct_message_updates); text = getString(R.string.service_x_new_direct_messages); text = MessageFormat.format(text, count); } PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, DmActivity.createIntent(), 0); notify(pendingIntent, DM_NOTIFICATION_ID, R.drawable.notify_dm, TextHelper.getSimpleTweetText(latest.text), title, text); } @Override public void onDestroy() { Log.d(TAG, "Service Destroy."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } mWakeLock.release(); super.onDestroy(); } public static void schedule(Context context) { SharedPreferences preferences = TwitterApplication.mPref; boolean needCheck = preferences.getBoolean( Preferences.CHECK_UPDATES_KEY, false); boolean widgetIsEnabled = TwitterService.widgetIsEnabled; if (!needCheck && !widgetIsEnabled) { Log.d(TAG, "Check update preference is false."); return; } String intervalPref = preferences .getString( Preferences.CHECK_UPDATE_INTERVAL_KEY, context.getString(R.string.pref_check_updates_interval_default)); int interval = Integer.parseInt(intervalPref); // interval = 1; //for debug Intent intent = new Intent(context, TwitterService.class); PendingIntent pending = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); Calendar c = new GregorianCalendar(); c.add(Calendar.MINUTE, interval); DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); Log.d(TAG, "Schedule, next run at " + df.format(c.getTime())); AlarmManager alarm = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); alarm.cancel(pending); if (needCheck) { alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending); } else { // only for widget alarm.set(AlarmManager.RTC, c.getTimeInMillis(), pending); } } public static void unschedule(Context context) { Intent intent = new Intent(context, TwitterService.class); PendingIntent pending = PendingIntent.getService(context, 0, intent, 0); AlarmManager alarm = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Log.d(TAG, "Cancelling alarms."); alarm.cancel(pending); } private static boolean widgetIsEnabled = false; public static void setWidgetStatus(boolean isEnabled) { widgetIsEnabled = isEnabled; } public static boolean isWidgetEnabled() { return widgetIsEnabled; } private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { SharedPreferences preferences = TwitterApplication.mPref; boolean timeline_only = preferences.getBoolean( Preferences.TIMELINE_ONLY_KEY, false); boolean replies_only = preferences.getBoolean( Preferences.REPLIES_ONLY_KEY, true); boolean dm_only = preferences.getBoolean(Preferences.DM_ONLY_KEY, true); Log.d(TAG, "Widget Is Enabled? " + TwitterService.widgetIsEnabled); if (timeline_only || TwitterService.widgetIsEnabled) { String maxId = getDb() .fetchMaxTweetId(TwitterApplication.getMyselfId(false), StatusTable.TYPE_HOME); Log.d(TAG, "Max id is:" + maxId); List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; try { if (maxId != null) { statusList = getApi().getFriendsTimeline( new Paging(maxId)); } else { statusList = getApi().getFriendsTimeline(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet; tweet = Tweet.create(status); mNewTweets.add(tweet); Log.d(TAG, mNewTweets.size() + " new tweets."); int count = getDb().addNewTweetsAndCountUnread(mNewTweets, TwitterApplication.getMyselfId(false), StatusTable.TYPE_HOME); if (count <= 0) { return TaskResult.FAILED; } } if (isCancelled()) { return TaskResult.CANCELLED; } } if (replies_only) { String maxMentionId = getDb().fetchMaxTweetId( TwitterApplication.getMyselfId(false), StatusTable.TYPE_MENTION); Log.d(TAG, "Max mention id is:" + maxMentionId); List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; try { if (maxMentionId != null) { statusList = getApi().getMentions( new Paging(maxMentionId)); } else { statusList = getApi().getMentions(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } int unReadMentionsCount = 0; for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet = Tweet.create(status); mNewMentions.add(tweet); unReadMentionsCount = getDb().addNewTweetsAndCountUnread( mNewMentions, TwitterApplication.getMyselfId(false), StatusTable.TYPE_MENTION); if (unReadMentionsCount <= 0) { return TaskResult.FAILED; } } Log.v(TAG, "Got mentions " + unReadMentionsCount + "/" + mNewMentions.size()); if (isCancelled()) { return TaskResult.CANCELLED; } } if (dm_only) { String maxId = getDb().fetchMaxDmId(false); Log.d(TAG, "Max DM id is:" + maxId); List<com.ch_linghu.fanfoudroid.fanfou.DirectMessage> dmList; try { if (maxId != null) { dmList = getApi().getDirectMessages(new Paging(maxId)); } else { dmList = getApi().getDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (com.ch_linghu.fanfoudroid.fanfou.DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, false); mNewDms.add(dm); Log.d(TAG, mNewDms.size() + " new DMs."); int count = 0; TwitterDatabase db = getDb(); if (db.fetchDmCount() > 0) { count = db.addNewDmsAndCountUnread(mNewDms); } else { Log.d(TAG, "No existing DMs. Don't notify."); db.addDms(mNewDms, false); } if (count <= 0) { return TaskResult.FAILED; } } if (isCancelled()) { return TaskResult.CANCELLED; } } return TaskResult.OK; } } }
Java
package com.ch_linghu.fanfoudroid.service; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.widget.RemoteViews; import com.ch_linghu.fanfoudroid.FanfouWidget; import com.ch_linghu.fanfoudroid.FanfouWidgetSmall; 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.db.TwitterDatabase; public class WidgetService extends Service { protected static final String TAG = "WidgetService"; private int position = 0; private List<Tweet> tweets; private TwitterDatabase getDb() { return TwitterApplication.mDb; } public String getUserId() { return TwitterApplication.getMyselfId(false); } 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()); } } } public RemoteViews buildUpdate(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_initial_layout); updateViews .setTextViewText(R.id.status_text, tweets.get(position).text); // updateViews.setOnClickPendingIntent(viewId, pendingIntent) position++; return updateViews; } private Handler handler = new Handler(); private Runnable mTask = new Runnable() { @Override public void run() { Log.d(TAG, "tweets size=" + tweets.size() + " position=" + position); if (position >= tweets.size()) { position = 0; } ComponentName fanfouWidget = new ComponentName(WidgetService.this, FanfouWidget.class); AppWidgetManager manager = AppWidgetManager .getInstance(getBaseContext()); manager.updateAppWidget(fanfouWidget, buildUpdate(WidgetService.this)); handler.postDelayed(mTask, 10000); ComponentName fanfouWidgetSmall = new ComponentName( WidgetService.this, FanfouWidgetSmall.class); AppWidgetManager manager2 = AppWidgetManager .getInstance(getBaseContext()); manager2.updateAppWidget(fanfouWidgetSmall, buildUpdate(WidgetService.this)); handler.postDelayed(mTask, 10000); } }; public static void schedule(Context context) { SharedPreferences preferences = TwitterApplication.mPref; if (!preferences.getBoolean(Preferences.CHECK_UPDATES_KEY, false)) { Log.d(TAG, "Check update preference is false."); return; } String intervalPref = preferences .getString( Preferences.CHECK_UPDATE_INTERVAL_KEY, context.getString(R.string.pref_check_updates_interval_default)); int interval = Integer.parseInt(intervalPref); Intent intent = new Intent(context, WidgetService.class); PendingIntent pending = PendingIntent.getService(context, 0, intent, 0); Calendar c = new GregorianCalendar(); c.add(Calendar.MINUTE, interval); DateFormat df = new SimpleDateFormat("h:mm a"); Log.d(TAG, "Scheduling alarm at " + df.format(c.getTime())); AlarmManager alarm = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); alarm.cancel(pending); alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending); } /** * @see android.app.Service#onBind(Intent) */ @Override public IBinder onBind(Intent intent) { // TODO Put your code here return null; } /** * @see android.app.Service#onCreate() */ @Override public void onCreate() { Log.d(TAG, "WidgetService onCreate"); schedule(WidgetService.this); } /** * @see android.app.Service#onStart(Intent,int) */ @Override public void onStart(Intent intent, int startId) { Log.d(TAG, "WidgetService onStart"); fetchMessages(); handler.removeCallbacks(mTask); handler.postDelayed(mTask, 10000); } @Override public void onDestroy() { Log.d(TAG, "WidgetService Stop "); handler.removeCallbacks(mTask);// 当服务结束时,删除线程 super.onDestroy(); } }
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; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.R; public class AboutActivity extends Activity { //反馈信息 private String versionName = null; private String deviceModel = null; private String versionRelease = null; private String feedback = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); deviceModel=android.os.Build.MODEL; versionRelease=android.os.Build.VERSION.RELEASE; if (TwitterApplication.mPref.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } // set real version ComponentName comp = new ComponentName(this, getClass()); PackageInfo pinfo = null; try { pinfo = getPackageManager() .getPackageInfo(comp.getPackageName(), 0); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } TextView version = (TextView) findViewById(R.id.version); String versionString; if (TwitterApplication.DEBUG){ version.setText(String.format("v %d(nightly)", pinfo.versionCode)); versionName = String.format("%d", pinfo.versionCode); }else{ version.setText(String.format("v %s", pinfo.versionName)); versionName = pinfo.versionName; } // bind button click event Button okBtn = (Button) findViewById(R.id.ok_btn); okBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { finish(); } }); feedback = "@令狐虫 @三日坊主 @内存地址 @PhoenixG @忽然兔 "+"#安能饭否#"+" "+versionName+"/"+deviceModel+"/"+versionRelease+" "; Button feedbackBtn = (Button) findViewById(R.id.feedback_btn); feedbackBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewTweetIntent(feedback); startActivity(intent); } }); } }
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
/* * 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 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.data; import android.database.Cursor; public interface BaseContent { long insert(); int delete(); int update(); Cursor select(); }
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.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
/* * 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 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.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 HIGHLIGHT_BACKGROUND = "highlight_background"; 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 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
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