repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/eliminateprocess/TaskInfoProvider.java
src/com/droid/activitys/eliminateprocess/TaskInfoProvider.java
package com.droid.activitys.eliminateprocess; import java.util.ArrayList; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; /* * by:kangzizhaung */ public class TaskInfoProvider { private PackageManager pmManager; private ActivityManager aManager; public TaskInfoProvider(Context context) { pmManager = context.getPackageManager(); aManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); } // 遍历传入的列表,将所有应用的信息传入taskinfo中 public List<TaskInfo> GetAllTask(List<RunningAppProcessInfo> list) { List<TaskInfo> taskInfos = new ArrayList<TaskInfo>(); for (RunningAppProcessInfo appProcessInfo : list) { TaskInfo info = new TaskInfo(); int id = appProcessInfo.pid; info.setId(id); String packageName = appProcessInfo.processName; info.setPackageName(packageName); try { // ApplicationInfo是AndroidMainfest文件里面整个Application节点的封装װ ApplicationInfo applicationInfo = pmManager.getPackageInfo( packageName, 0).applicationInfo; Drawable icon = applicationInfo.loadIcon(pmManager); info.setIcon(icon); String name = applicationInfo.loadLabel(pmManager).toString(); info.setName(name); info.setIsSystemProcess(!IsSystemApp(applicationInfo)); android.os.Debug.MemoryInfo[] memoryInfo = aManager .getProcessMemoryInfo(new int[] { id }); int memory = memoryInfo[0].getTotalPrivateDirty(); info.setMemory(memory); taskInfos.add(info); info = null; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); info.setName(packageName); info.setIsSystemProcess(true); } } return taskInfos; } public Boolean IsSystemApp(ApplicationInfo info) { // 有些系统应用是可以更新的,如果用户自己下载了一个系统的应用来更新了原来的, // 它就不是系统应用啦,这个就是判断这种情况的 if ((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) { return true; } else if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { return true; } return false; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/eliminateprocess/TaskInfo.java
src/com/droid/activitys/eliminateprocess/TaskInfo.java
package com.droid.activitys.eliminateprocess; import android.graphics.drawable.Drawable; public class TaskInfo { private String name; private Drawable icon; private int id; private int memory; private Boolean isCheck; private String packageName; private Boolean isSystemProcess;// 是否为系统进程 public String getName() { return name; } public void setName(String name) { this.name = name; } public Drawable getIcon() { return icon; } public void setIcon(Drawable icon) { this.icon = icon; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getMemory() { return memory; } public void setMemory(int memory) { this.memory = memory; } public Boolean getIsCheck() { return isCheck; } public void setIsCheck(Boolean isCheck) { this.isCheck = isCheck; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public Boolean getIsSystemProcess() { return isSystemProcess; } public void setIsSystemProcess(Boolean isSystemProcess) { this.isSystemProcess = isSystemProcess; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/eliminateprocess/TextFormater.java
src/com/droid/activitys/eliminateprocess/TextFormater.java
package com.droid.activitys.eliminateprocess; import java.text.DecimalFormat; public class TextFormater { public static String longtoString(long size) { DecimalFormat format = new DecimalFormat("####.00"); if (size < 1024) { return size + "byte"; } else if (size < (1 << 20)) // 左移20位,相当于1024 * 1024 { float kSize = size >> 10; // 右移10位,相当于除以1024 return format.format(kSize) + "KB"; } else if (size < (1 << 30)) // 左移30位,相当于1024 * 1024 * 1024 { float mSize = size >> 20;// 右移20位,相当于除以1024再除以1024 return format.format(mSize) + "MB"; } else if (size < (1 << 40)) { float gSize = size >> 30; return format.format(gSize) + "GB"; } else { return "size error"; } } public static String floattoString(float size){ if(size<0){ return 0+""; }else { return size+"MB"; } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/eliminateprocess/EliminateMainActivity.java
src/com/droid/activitys/eliminateprocess/EliminateMainActivity.java
package com.droid.activitys.eliminateprocess; import java.io.BufferedReader; import java.io.FileReader; import java.text.DecimalFormat; import java.util.List; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.MemoryInfo; import android.app.ActivityManager.RunningAppProcessInfo; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; 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.droid.R; /* * by: kangzizhuang */ @SuppressLint("InflateParams") public class EliminateMainActivity extends Activity { protected static final int LOAD_FINISH = 0; public final int CLEAR_FINISH=1; public final int NEEDENT_CLEAR=2; public final int PERCENT_CHANGE=3; private List<RunningAppProcessInfo> appProcessInfo; private ActivityManager activityManager; private List<TaskInfo> UserTaskInfo; private ImageView Round_img; private Button Start_kill; private TextView increase_speed; private TextView Allpercent; private String percentnum; private TextView release_memory; private String Clearmemory; private LinearLayout clear_endlayout; private RelativeLayout Clearing_layout; private static float MemorySurPlus; private static float TotalMemory; private MemoryInfo info ; private int allpercent; private Boolean ISRound=true; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case LOAD_FINISH: break; case CLEAR_FINISH: ISRound=false; Animation animation=null; Round_img.setAnimation(animation); Clearing_layout.setVisibility(View.GONE); clear_endlayout.setVisibility(View.VISIBLE); increase_speed.setText(percentnum+"%"); release_memory.setText(Clearmemory+"MB"); Start_kill.setText("清理完成"); break; case NEEDENT_CLEAR: percentnum=0+""; Clearmemory=0+""; Toast.makeText(EliminateMainActivity.this, "当前不需要清理", Toast.LENGTH_LONG).show(); break; case PERCENT_CHANGE: Allpercent.setText(allpercent+"%"); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.eliminateactivity_main); activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); // 获取activityManager对象 Init(); InitData(); } public void Init() { GetSurplusMemory(); Round_img=(ImageView)findViewById(R.id.eliminate_roundimg); Start_kill=(Button)findViewById(R.id.start_killtask); release_memory=(TextView)findViewById(R.id.relase_memory); increase_speed=(TextView)findViewById(R.id.increase_speed); Allpercent=(TextView)findViewById(R.id.all_percent); clear_endlayout=(LinearLayout)findViewById(R.id.clear_endlayout); Clearing_layout=(RelativeLayout)findViewById(R.id.clearing_layout); Animation animation=AnimationUtils.loadAnimation(EliminateMainActivity.this, R.anim.eliminatedialog_anmiation); TotalMemory=GetTotalMemory(); Round_img.setAnimation(animation); Start_kill.setClickable(false); Start_kill.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub finish(); } }); } // 加载所有获取到的应用的信息 public void InitData() { new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while (ISRound) { allpercent=(int)((float)(MemorySurPlus/TotalMemory)*100); handler.sendEmptyMessage(PERCENT_CHANGE); } } }).start(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub getRunningApp(); TaskInfoProvider taskInfoProvider = new TaskInfoProvider( EliminateMainActivity.this); UserTaskInfo = taskInfoProvider.GetAllTask(appProcessInfo); KillTask(); } }).start(); } // 得到当前运行的进程数目 public List<RunningAppProcessInfo> getRunningApp() { appProcessInfo = activityManager.getRunningAppProcesses(); return appProcessInfo; } // 得到当前剩余的内存 public long GetSurplusMemory() { info = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(info); long MemorySize = info.availMem; MemorySurPlus = (float) MemorySize / 1024 / 1024; return MemorySize; } public float GetTotalMemory(){ String str1 = "/proc/meminfo";// 系统内存信息文件 String str2; String[] arrayOfString; long initial_memory = 0; try { FileReader fileReader=new FileReader(str1); BufferedReader bufferedReader=new BufferedReader(fileReader, 8192); str2=bufferedReader.readLine(); arrayOfString=str2.split("\\s+"); initial_memory=Integer.valueOf(arrayOfString[1]); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return (float)(initial_memory/1024); } private void KillTask() { for (TaskInfo info : UserTaskInfo) { if (!info.getIsSystemProcess()) { activityManager.killBackgroundProcesses(info.getPackageName()); // 高级清理 // try { // Method method = // Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", // String.class); // method.invoke(activityManager, info.getPackageName()); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } } MemoryInfo info = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(info); float MemorySize = (float) info.availMem / 1024 / 1024; float size = MemorySize - MemorySurPlus; if (size > 0) { DecimalFormat decimalFormat = new DecimalFormat("0.00"); Clearmemory = decimalFormat.format(size); percentnum=decimalFormat.format((size/TotalMemory)*100); } else { Message message=new Message(); message.what=NEEDENT_CLEAR; handler.sendMessage(message); } Message message=new Message(); message.what=CLEAR_FINISH; handler.sendMessage(message); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/setting/SettingFragment.java
src/com/droid/activitys/setting/SettingFragment.java
package com.droid.activitys.setting; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import com.droid.R; import com.droid.activitys.WoDouGameBaseFragment; import com.droid.activitys.app.AppAutoRun; import com.droid.activitys.app.AppUninstall; import com.droid.application.ClientApplication; import com.droid.cache.ImageCache; import com.droid.cache.loader.ImageFetcher; import com.droid.cache.loader.ImageWorker; import com.droid.activitys.eliminateprocess.EliminateMainActivity; import com.droid.activitys.garbageclear.GarbageClear; import com.droid.activitys.speedtest.SpeedTestActivity; import java.util.List; /** * Created by Administrator on 2014/9/9. */ public class SettingFragment extends WoDouGameBaseFragment implements View.OnClickListener { private ImageWorker mImageLoader; private ImageButton Setting_Clean;// 垃圾清理 private ImageButton Setting_Accelerate;// 一键加速 private ImageButton appUninstall; private ImageButton setNet; private ImageButton setMore; private ImageButton netSpeed; private ImageButton sysUpdate; private ImageButton fileManage; private ImageButton about; private ImageButton autoRun; private View view;// 视图 private Intent JumpIntent; private static final boolean d = ClientApplication.debug; private Context context; /** * 用来存放 */ private List<ContentValues> datas; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this.getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = LayoutInflater.from(getActivity()).inflate( R.layout.fragment_setting, null); initView(view); setListener(); // Bundle bundle = this.getArguments(); // String data = bundle.getString("url_data"); // UIResponseParam uiResponseParam = null; // try { // uiResponseParam = new UIResponseParam(data); // datas = uiResponseParam.getUIInfo(); // showImages(); // } catch (JSONException e) { // e.printStackTrace(); // } return view; } private void initView(View view) { // FocusedRelativeLayout focus = (FocusedRelativeLayout) view // .findViewById(R.id.setting_focus_rl); // focus.setFocusResId(R.drawable.focus_bg); // focus.setFocusShadowResId(R.drawable.focus_shadow); // focus.setFocusable(true); // focus.setFocusableInTouchMode(true); // focus.requestFocus(); // focus.requestFocusFromTouch(); appUninstall = (ImageButton) view.findViewById(R.id.setting_uninstall); setNet = (ImageButton) view.findViewById(R.id.setting_net); setMore = (ImageButton) view.findViewById(R.id.setting_more); netSpeed = (ImageButton) view.findViewById(R.id.setting_net_speed); sysUpdate = (ImageButton) view.findViewById(R.id.setting_update); fileManage = (ImageButton) view.findViewById(R.id.setting_file); about = (ImageButton) view.findViewById(R.id.setting_about); Setting_Clean = (ImageButton) view.findViewById(R.id.setting_clean); Setting_Accelerate = (ImageButton) view.findViewById(R.id.setting_accelerate); autoRun = (ImageButton) view.findViewById(R.id.setting_autorun); appUninstall.setOnFocusChangeListener(mFocusChangeListener); setNet.setOnFocusChangeListener(mFocusChangeListener); setMore.setOnFocusChangeListener(mFocusChangeListener); netSpeed.setOnFocusChangeListener(mFocusChangeListener); sysUpdate.setOnFocusChangeListener(mFocusChangeListener); fileManage.setOnFocusChangeListener(mFocusChangeListener); about.setOnFocusChangeListener(mFocusChangeListener); Setting_Clean.setOnFocusChangeListener(mFocusChangeListener); Setting_Accelerate.setOnFocusChangeListener(mFocusChangeListener); autoRun.setOnFocusChangeListener(mFocusChangeListener); } private void setListener() { Setting_Clean.setOnClickListener(this); Setting_Accelerate.setOnClickListener(this); about.setOnClickListener(this); setMore.setOnClickListener(this); appUninstall.setOnClickListener(this); setNet.setOnClickListener(this); fileManage.setOnClickListener(this); netSpeed.setOnClickListener(this); sysUpdate.setOnClickListener(this); autoRun.setOnClickListener(this); } private void showImages() { mImageLoader = new ImageFetcher(this.getActivity()); mImageLoader.setImageCache(ImageCache.getInstance(this.getActivity())); datas = datas.subList(11, 17); for (int i = 0; i < datas.size(); i++) { int picPosition = datas.get(i).getAsInteger("picPosition"); String picPath = datas.get(i).getAsString("picPath"); switch (picPosition) { case 1: // mImageLoader.loadImage(picPath, iv_1, // R.drawable.where_is_father); break; } } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.setting_clean: JumpIntent = new Intent(context, GarbageClear.class); startActivity(JumpIntent); break; case R.id.setting_accelerate: JumpIntent = new Intent(context, EliminateMainActivity.class); startActivity(JumpIntent); break; case R.id.setting_about: break; case R.id.setting_more: JumpIntent = new Intent(Settings.ACTION_SETTINGS); startActivity(JumpIntent); break; case R.id.setting_file: break; case R.id.setting_update: break; case R.id.setting_net: JumpIntent = new Intent(context, SettingCustom.class); startActivity(JumpIntent); break; case R.id.setting_uninstall: JumpIntent = new Intent(context, AppUninstall.class); startActivity(JumpIntent); break; case R.id.setting_autorun: JumpIntent = new Intent(context, AppAutoRun.class); startActivity(JumpIntent); break; case R.id.setting_net_speed: JumpIntent = new Intent(context, SpeedTestActivity.class); startActivity(JumpIntent); break; } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/setting/SettingCustom.java
src/com/droid/activitys/setting/SettingCustom.java
package com.droid.activitys.setting; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import com.droid.R; import com.droid.activitys.Bluetooth; import com.droid.activitys.Ethernet; import com.droid.activitys.speedtest.SpeedTestActivity; import com.droid.activitys.wifi.WifiActivity; /** *@author Droid */ public class SettingCustom extends Activity implements View.OnClickListener { private static final String TAG = "UPDATE"; private static final boolean d = false; private TextView wifi; private TextView ethernet; private TextView bluetooth; private TextView detection; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_setting_custom); context = this; initViews(); setListener(); } private void initViews() { wifi = (TextView) findViewById(R.id.setting_custom_wifi); ethernet = (TextView) findViewById(R.id.setting_custom_ethernet); bluetooth = (TextView) findViewById(R.id.setting_custom_bluetooth); detection = (TextView) findViewById(R.id.setting_custom_net_detection); } private void setListener() { wifi.setOnClickListener(this); ethernet.setOnClickListener(this); bluetooth.setOnClickListener(this); detection.setOnClickListener(this); } @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "============onRestart========"); } @Override protected void onPause() { super.onPause(); Log.i(TAG, "=====onPause==========="); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "=========onResume======="); } @Override public void onClick(View v) { Intent i = new Intent(); switch (v.getId()){ case R.id.setting_custom_wifi: i.setClass(context, WifiActivity.class); startActivity(i); break; case R.id.setting_custom_ethernet: i.setClass(context,Ethernet.class); startActivity(i); break; case R.id.setting_custom_bluetooth: i.setClass(context,Bluetooth.class); startActivity(i); break; case R.id.setting_custom_net_detection: i.setClass(context, SpeedTestActivity.class); startActivity(i); break; } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/cache/ImageCache.java
src/com/droid/cache/ImageCache.java
package com.droid.cache; import android.content.Context; import android.graphics.Bitmap; import android.support.v4.util.LruCache; import com.droid.cache.base.DiskLruCache; import com.droid.cache.base.ImageDiskLruCache; import com.droid.cache.util.CacheConfig; import com.droid.cache.util.CacheUtils; import com.droid.cache.util.LogUtil; /** *图片缓存. *@Title: *@Description: *@Since:2014-3-6 *@Version: */ public class ImageCache { /** 日志TAG. **/ private static final String TAG = "ImageCache"; /** 图片硬盘缓存. */ private ImageDiskLruCache mImageDiskCache; /** 图片内存缓存. */ private LruCache<String, Bitmap> mMemoryCache; /** 图片缓存实例. */ private static ImageCache mInstance; /** * 获得一个图片缓存实例. * @param context context */ public static ImageCache getInstance(Context context) { if(mInstance == null) { mInstance = new ImageCache(context); } return mInstance; } /** * 构造方法. * @param context context */ private ImageCache(Context context) { init(context); } /** * 初始化<硬盘缓存>和<内存缓存> * @param context context * @Description: */ private void init(Context context) { //设置硬盘缓存 mImageDiskCache = ImageDiskLruCache.openImageCache(context, CacheConfig.Image.DISK_CACHE_NAME, CacheConfig.Image.DISK_CACHE_MAX_SIZE); // 设置内存缓存. final int imageMemorySize = CacheUtils.getMemorySize(context, CacheConfig.Image.MEMORY_SHRINK_FACTOR); LogUtil.d(TAG, "memory size : " + imageMemorySize); mMemoryCache = new LruCache<String, Bitmap>(imageMemorySize) { @Override protected int sizeOf(String key, Bitmap bitmap) { return CacheUtils.getBitmapSize(bitmap); } @Override protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) { } }; } /** * 添加图片到缓存 * @param key key * @param bitmap 图片. */ public void addBitmapToCache(String key, Bitmap bitmap) { //如果key或者bitmap有一个为null,直接返回. if (key == null || bitmap == null) { return; } // 添加到内存缓存. if (mMemoryCache != null && mMemoryCache.get(key) == null) { mMemoryCache.put(key, bitmap); } // 添加到硬盘缓存. if (mImageDiskCache != null && !mImageDiskCache.containsKey(key)) { mImageDiskCache.putImage(key, bitmap); } } /** * 是否存在. * @Date 2014-3-6 */ public boolean exists(String key) { if (mImageDiskCache != null && mImageDiskCache.containsKey(key)) { return true; } return false; } /** * 从内存缓存中去图片. * @Date 2014-3-6 */ public Bitmap getBitmapFromMemCache(String key) { if (mMemoryCache != null) { final Bitmap bitmap = mMemoryCache.get(key); if (bitmap != null) { LogUtil.d(TAG, "memory cache hit : " + key); return bitmap; } } return null; } /** * 从硬盘缓存中取图片. * @Date 2014-3-6 */ public Bitmap getBitmapFromDiskCache(String key) { if (mImageDiskCache != null) { return mImageDiskCache.getImage(key); } return null; } /** * 清除内存缓存. * @Date 2014-3-6 */ public void clearMemoryCache() { mMemoryCache.evictAll(); } /** * 得到硬盘缓存. * @Date 2014-3-6 */ public DiskLruCache getDiskCache() { return mImageDiskCache; } private void test() { } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/cache/util/CacheConfig.java
src/com/droid/cache/util/CacheConfig.java
package com.droid.cache.util; /** * 缓存配置 *@Title: *@Description: */ public interface CacheConfig { /** 缓冲字节流一次读入大小 ( google 推荐 8192 ). **/ int IO_BUFFER_SIZE = 8 * 1024; /** 缓存总目录. **/ String DISK_CACHE_NAME = "/CacheDir"; /** * 图片缓存的配置. *@Title: */ interface Image { /** 图片缓存的目录. **/ String DISK_CACHE_NAME = "/images"; /** 图片缓存的最大大小. (20MB) **/ int DISK_CACHE_MAX_SIZE = 1024 * 1024 * 20; /** 图片缓存的内存大小. (1/8内存大小) **/ int MEMORY_SHRINK_FACTOR = 8; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/cache/util/LogUtil.java
src/com/droid/cache/util/LogUtil.java
package com.droid.cache.util; import android.util.Log; import com.droid.BuildConfig; /** * log工具. *@Title: *@Description: */ public class LogUtil { /** 日志log. */ private static final String TAG = "Cache_Log"; /** 是否打印log. */ private static final boolean DEBUG = BuildConfig.DEBUG; //======================================= log.e =========================================// public static void e(String tag, String err) { if (DEBUG) { Log.e(tag, err); } } public static void e(String tag, String debug, Throwable e) { if (DEBUG) { Log.e(tag, debug, e); } } public static void e(String msg) { if (DEBUG) { Log.e(TAG, msg); } } //======================================= log.d =========================================// public static void d(String tag, String debug) { if (DEBUG && debug != null) { Log.d(tag, debug); } } public static void d(String tag, String debug, Throwable e) { if (DEBUG) { Log.d(tag, debug, e); } } public static void d(String msg) { if (DEBUG) { Log.d(TAG, msg); } } //======================================= log.i =========================================// public static void i(String tag, String info) { if (DEBUG) { Log.i(tag, info); } } public static void i(String tag, String debug, Throwable e) { if (DEBUG) { Log.i(tag, debug, e); } } public static void i(String msg) { if (DEBUG) { Log.i(TAG, msg); } } //======================================= log.w =========================================// public static void w(String tag, String info) { if (DEBUG) { Log.w(tag, info); } } public static void w(String tag, String debug, Throwable e) { if (DEBUG) { Log.w(tag, debug, e); } } public static void w(String msg) { if (DEBUG) { Log.w(TAG, msg); } } // ===================================== log.exception =======================================// public static void logException(Throwable e) { if (DEBUG) { e.printStackTrace(); } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/cache/util/CacheUtils.java
src/com/droid/cache/util/CacheUtils.java
package com.droid.cache.util; import android.app.ActivityManager; import android.content.Context; import android.graphics.Bitmap; import android.os.Environment; import android.os.StatFs; import java.io.File; /** * 缓存工具类. *@Title: *@Description: */ public final class CacheUtils { /** * 获得bitmap的字节大小. */ public static int getBitmapSize(Bitmap bitmap) { return bitmap.getRowBytes() * bitmap.getHeight(); } /** * 外部存储是否可读写. */ public static boolean isExternalStorageRWable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } /** * 获得可使用的<缓存主目录>(先外部,后外部) */ public static File getEnabledCacheDir(Context context, String cacheName) { String cachePath; if(isExternalStorageRWable()) { cachePath = Environment.getExternalStorageDirectory().getPath(); } else { cachePath = context.getCacheDir().getPath(); } File cacheFile = new File(cachePath + CacheConfig.DISK_CACHE_NAME + cacheName); //如果缓存目录不存在,创建缓存目录. if (!cacheFile.exists()) { cacheFile.mkdirs(); } return cacheFile; } /** * 这个文件路径下,有多少空间可用. * @param path 文件路径. * @return 可用空间. */ public static long getUsableSpace(File path) { final StatFs stats = new StatFs(path.getPath()); return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks(); } /** * Return the approximate per-application memory class of the current device. * This gives you an idea of how hard a memory limit you should impose on your * application to let the overall system work best. The returned value is in megabytes; * the baseline Android memory class is 16 (which happens to be the Java heap limit of those devices); * some device with more memory may return 24 or even higher numbers. */ private static int getMemoryClass(Context context) { return ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass(); } /** * * @param context context * @param shrinkFactor 内存总大小的缩小倍数(如:如果传入8,将得到内存1/8的大小) */ public static int getMemorySize(Context context, int shrinkFactor) { int totalSize = getMemoryClass(context)*1024*1024; return totalSize / shrinkFactor; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/cache/loader/ImageWorker.java
src/com/droid/cache/loader/ImageWorker.java
package com.droid.cache.loader; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.os.AsyncTask; import android.text.TextUtils; import android.util.SparseArray; import android.widget.ImageView; import com.droid.cache.ImageCache; import com.droid.cache.util.LogUtil; import java.lang.ref.WeakReference; /** * 图片加载器.<P> * 图片的加载过程:1.从自身的图片缓存中取;2.如果取不到,则从网络中获取.<P> * 同时,我们可以停止后台的图片获取线程. *@Title: *@Description: */ public abstract class ImageWorker { /** 日志TAG. */ private static final String TAG = "ImageWorker"; /** 图片加载效果时间<淡入时间>. */ private static final int FADE_IN_TIME = 200; /** 图片缓存. */ private ImageCache mImageCache; /** 是否将要推出加载<如:应用程序结束的时候,加载线程就应该停止>. */ private boolean mExitTasksEarly = false; /** 上下文Context. */ protected Context mContext; /** 正在加载时候的图片. */ private SparseArray<Bitmap> loadingImageMap; /** * 构造方法. * @param context context */ protected ImageWorker(Context context) { mContext = context; loadingImageMap = new SparseArray<Bitmap>(); } /** * 根据url加载一个图片到ImageView上,未加载成功的时候显示加载图片<loadingImageId> * * @param url 图片网络地址. * @param imageView 图片View * @param loadingImageId 加载图片资源ID * @Description: */ public void loadImage(String url, ImageView imageView, int loadingImageId) { //如果图片网络地址为空,直接返回. if(TextUtils.isEmpty(url)) { return; } Bitmap bitmap = null; if (mImageCache != null) { //先从内存缓存中取. bitmap = mImageCache.getBitmapFromMemCache(url); } if (bitmap != null) { //如果取到了,直接显示. imageView.setImageBitmap(bitmap); } else if (cancelPotentialWork(url, imageView)) { //如果没有取到,取消之前相同的加载线程,取消成功,就启动一个新的加载线程. final BitmapWorkerTask task = new BitmapWorkerTask(imageView); final AsyncDrawable asyncDrawable = new AsyncDrawable(mContext.getResources(), getLoadingImage(loadingImageId), task); imageView.setImageDrawable(asyncDrawable); task.execute(url); } } /** * 根据资源ID获取加载中的图片. * @param resId 资源ID. * @Description: */ private Bitmap getLoadingImage(int resId) { //先从所有加载中的图片列表中取,如果取到,直接返回 Bitmap loadingBitmap = null; loadingBitmap = loadingImageMap.get(resId); //如果没有取到 if (loadingBitmap == null) { //从资源文件中获取,并且放到列表中,供后期提取. loadingBitmap = BitmapFactory.decodeResource(mContext.getResources(), resId); loadingImageMap.put(resId, loadingBitmap); } return loadingBitmap; } /** * 设置图片缓存. * @param imageCache 图片缓存. */ public void setImageCache(ImageCache imageCache) { mImageCache = imageCache; } /** * 获得图片缓存. * @return imageCache * @Description: */ public ImageCache getImageCache() { return mImageCache; } /** * 设置是否停止加载. */ public void setExitTasksEarly(boolean exitTasksEarly) { mExitTasksEarly = exitTasksEarly; } /** * 根据url得到bitmap图片. */ protected abstract Bitmap processBitmap(String url); /** * 取消一个ImageView的加载线程. * @param imageView 被取消加载线程的ImageView. * @Description: */ public static void cancelWork(ImageView imageView) { final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (bitmapWorkerTask != null) { bitmapWorkerTask.cancel(true); LogUtil.d(TAG, "cancel load : " + bitmapWorkerTask.url); } } /** * 取消指定url的图片加载线程. * @param url 图片网络地址 * @param imageView 图片View * @return 如果有相同的线程在进行,返回false,否则返回 true. */ public static boolean cancelPotentialWork(String url, ImageView imageView) { //从ImageView中获取加载线程. final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (bitmapWorkerTask != null) { final String taskUrl = bitmapWorkerTask.url; if (TextUtils.isEmpty(taskUrl) || !taskUrl.equals(url)) { //如果加载的url为空,获得加载的url不等指定的url,则取消当前的加载线程. bitmapWorkerTask.cancel(true); LogUtil.d(TAG, "cancel load : " + taskUrl); } else { // 如果加载的url等于指定的url,则说明不需要重新加载,返回false. return false; } } return true; } /** * 从ImageView获得加载线程. * @param imageView 图片View. */ private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { //如果IamgeView不为空. if (imageView != null) { final Drawable drawable = imageView.getDrawable(); if (drawable instanceof AsyncDrawable) { //获得ImageView的drawable,如果是AsyncDrawable的实例,返回加载线程. final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; return asyncDrawable.getBitmapWorkerTask(); } } return null; } /** * 图片加载线程. */ private class BitmapWorkerTask extends AsyncTask<String, String, Bitmap> { /** 图片网络地址. */ private String url; /** 弱引用显示图片的ImageView. */ private final WeakReference<ImageView> imageViewReference; /** * 构造方法 * @param imageView 显示图片的ImageView */ public BitmapWorkerTask(ImageView imageView) { //进行弱引用 imageViewReference = new WeakReference<ImageView>(imageView); } @Override protected Bitmap doInBackground(String... params) { url = params[0]; Bitmap bitmap = null; // 1.如果图片缓存不为null. // 2.如果当前线程没有被取消. // 3.如果被弱引用的ImageView没有被销毁. // 4.如果加载程序无须退出. if (mImageCache != null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) { //从硬盘缓存中去. bitmap = mImageCache.getBitmapFromDiskCache(url); } // 1.如果从硬盘缓存中获取的图片为Null. // 2.如果当前线程没有被取消. // 3.如果被弱引用的ImageView没有被销毁. // 4.如果加载程序无须退出. if (bitmap == null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) { //后台获取图片<网络获取> bitmap = processBitmap(params[0]); } // 1.如果加载过后的图片不为null. // 2.如果图片缓存不为null. if (bitmap != null && mImageCache != null) { //添加到缓存中. mImageCache.addBitmapToCache(url, bitmap); } return bitmap; } @Override protected void onPostExecute(Bitmap result) { // 1.如果当前线程<被取消>. // 2.如果加载程序<被命令退出>. if (isCancelled() || mExitTasksEarly) { result = null; } final ImageView imageView = getAttachedImageView(); if (result != null && imageView != null) { //如果弱引用的ImageView还在,并且加载的图片不为空,则显示图片. setImageBitmap(imageView, result); } }; /** * 获得弱引用的ImageView */ private ImageView getAttachedImageView() { final ImageView imageView = imageViewReference.get(); final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); //获得的ImageView中的加载线程 为 当前线程 if (this == bitmapWorkerTask) { //则返回这个IamgeView. return imageView; } return null; } } /** * 弱引用加载线程的BitmapDrawable *@Title: */ private class AsyncDrawable extends BitmapDrawable { /** 弱引用加载线程. */ private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference; /** * 构造方法. * @param res 系统资源 * @param bitmap 加载过程中的图片. * @param bitmapWorkerTask 图片加载线程. */ public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) { super(res, bitmap); //弱引用加载线程. bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(bitmapWorkerTask); } /** * 返回弱引用的图片加载线程. */ public BitmapWorkerTask getBitmapWorkerTask() { return bitmapWorkerTaskReference.get(); } } /** * 将图片设置到ImageView中. */ private void setImageBitmap(ImageView imageView, Bitmap bitmap) { //当图片加载好的时候,设置一个跳转样式,从一个<透明图片>跳至<加载好的图片>,用时<FADE_IN_TIME><200ms> final Drawable[] layers = new Drawable[] { new ColorDrawable(android.R.color.transparent), new BitmapDrawable(mContext.getResources(), bitmap) }; final TransitionDrawable transDrawable = new TransitionDrawable(layers); imageView.setImageDrawable(transDrawable); //开始展示. transDrawable.startTransition(FADE_IN_TIME); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/cache/loader/ImageFetcher.java
src/com/droid/cache/loader/ImageFetcher.java
package com.droid.cache.loader; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.text.TextUtils; import com.droid.cache.base.DiskLruCache; import com.droid.cache.util.LogUtil; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * 图片撷取器. *@Title: *@Description: *@Version: */ public class ImageFetcher extends ImageWorker { /** 日志TAG. */ private static final String TAG = "ImageFetcher"; /** * 构造方法. * @param context 上下文 */ public ImageFetcher(Context context) { super(context); } @Override protected Bitmap processBitmap(String url) { //从网络下载图片. final File file = downloadBitmap(url); if (file != null) { // 如果下载成功,转换成Bitmap返回. return BitmapFactory.decodeFile(file.getAbsolutePath()); } return null; } /** * 从网络下载一个图片. * @param netUrl 图片网络地址. * @Description: */ private File downloadBitmap(String netUrl) { DiskLruCache diskCache = getImageCache().getDiskCache(); LogUtil.d(TAG, "load : " + netUrl); HttpURLConnection urlConnection = null; try { final URL url = new URL(netUrl); urlConnection = (HttpURLConnection) url.openConnection(); //放到图片的硬盘缓存中. String filePath = diskCache.put(netUrl, urlConnection.getInputStream()); if(!TextUtils.isEmpty(filePath)) { return new File(filePath); } } catch (IOException e) { LogUtil.e(TAG, "load error :" + netUrl, e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return null; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/cache/base/DiskLruCache.java
src/com/droid/cache/base/DiskLruCache.java
package com.droid.cache.base; import android.content.Context; import com.droid.cache.util.CacheConfig; import com.droid.cache.util.CacheUtils; import com.droid.cache.util.LogUtil; import java.io.*; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; /** * 硬盘缓存. * * @Title: * @Description: * @Since:2014-3-5 * @Version: */ public class DiskLruCache { /** * 日志TAG. */ private static final String TAG = "DiskLruCache"; /** * 缓存文件命名开始符. */ private static final String CACHE_FILENAME_PREFIX = "cache_"; /** * 一次最大移除数. */ private static final int MAX_REMOVALS = 4; /** * 缓存文件路径. */ private final File mCacheDir; /** * 当前缓存文件个数. */ private int cacheNumSize = 0; /** * 当前缓存文件字节大小. */ private int cacheByteSize = 0; /** * 缓存最多文件个数 <默认:512个> */ private static final int maxCacheNumSize = 512; /** * 缓存最大字节数 <默认:10MB> */ private long maxCacheByteSize = 1024 * 1024 * 10; /** * map<key, 缓存文件路径>. */ protected final Map<String, String> mLinkedHashMap = Collections.synchronizedMap(new LinkedHashMap<String, String>(32, 0.75f, true)); /** * 缓存文件获取过滤器. * 文件名以 {@link #CACHE_FILENAME_PREFIX} 开头 */ private static final FilenameFilter CAHE_FILE_FILTER = new FilenameFilter() { @Override public boolean accept(File dir, String filename) { //以我们定义的<缓存文件命名开始符>开始的文件名,才认为是缓存文件. return filename.startsWith(CACHE_FILENAME_PREFIX); } }; /** * 打开一个硬盘缓存. * * @Description: * @Date 2014-3-5 */ public final static DiskLruCache openCache(Context context, String cacheName, long maxByteSize) { File cacheDir = CacheUtils.getEnabledCacheDir(context, cacheName); if (cacheDir.isDirectory() && cacheDir.canWrite() && CacheUtils.getUsableSpace(cacheDir) > maxByteSize) { return new DiskLruCache(cacheDir, maxByteSize); } return null; } /** * 构造方法. * * @param cacheDir 缓存目录. * @param maxByteSize 最大缓存字节数. */ protected DiskLruCache(File cacheDir, long maxByteSize) { mCacheDir = cacheDir; maxCacheByteSize = maxByteSize; } /** * 把一个字节数组以文件存放在缓存中. * * @param key 关键字 * @param inputStream 字节流 * @return 缓存文件路径. * @Description: * @Date 2014-3-5 */ public final String put(String key, InputStream inputStream) { BufferedInputStream bufferedInputStream = null; OutputStream bufferOps = null; try { bufferedInputStream = new BufferedInputStream(inputStream); String filePath = createFilePath(key); bufferOps = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] b = new byte[CacheConfig.IO_BUFFER_SIZE]; int count; while ((count = bufferedInputStream.read(b)) > 0) { bufferOps.write(b, 0, count); } bufferOps.flush(); LogUtil.d(TAG, "put success : " + key); onPutSuccess(key, filePath); flushCache(); return filePath; } catch (IOException e) { LogUtil.d(TAG, "store failed to store: " + key, e); } finally { try { if (bufferOps != null) { bufferOps.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e) { LogUtil.d(TAG, "close stream error : " + e.getMessage()); } } return ""; } /** * 把一个字节数组以文件存放在缓存中. * * @param key 关键字 * @param data 字节数组 * @return 缓存文件路径. */ public final String put(String key, byte[] data) { if (data != null) { OutputStream bufferOps = null; try { String filePath = createFilePath(key); bufferOps = new BufferedOutputStream(new FileOutputStream(filePath)); bufferOps.write(data, 0, data.length); bufferOps.flush(); LogUtil.d(TAG, "put success : " + key); onPutSuccess(key, filePath); flushCache(); return filePath; } catch (IOException e) { LogUtil.d(TAG, "put fail : " + key, e); } finally { try { if (bufferOps != null) { bufferOps.close(); } } catch (IOException e) { LogUtil.d(TAG, "close outputStream error : " + e.getMessage()); } } } return ""; } /** * 放入一个文件. * * @param key 关键字 * @param filePath 文件路径 */ protected final void onPutSuccess(String key, String filePath) { mLinkedHashMap.put(key, filePath); cacheNumSize = mLinkedHashMap.size(); cacheByteSize += new File(filePath).length(); } /** * 缓存大小溢出处理. * * @Description: * @Date 2014-3-5 */ protected final void flushCache() { Entry<String, String> eldestEntry; File eldestFile; long eldestFileSize; int count = 0; //超过最大缓存文件个数 or 超过最大空间大小 移除不常用的文件,并且一次最多只能移除4个. while (count < MAX_REMOVALS && (cacheNumSize > maxCacheNumSize || cacheByteSize > maxCacheByteSize)) { eldestEntry = mLinkedHashMap.entrySet().iterator().next(); eldestFile = new File(eldestEntry.getValue()); eldestFileSize = eldestFile.length(); mLinkedHashMap.remove(eldestEntry.getKey()); eldestFile.delete(); cacheNumSize = mLinkedHashMap.size(); cacheByteSize -= eldestFileSize; count++; LogUtil.d(TAG, "flushCache - Removed :" + eldestFile.getAbsolutePath() + ", " + eldestFileSize); } } /** * 根据key返回缓存文件. * * @param key key * @Description: * @Date 2014-3-6 */ public final File get(String key) { if (containsKey(key)) { final File file = new File(createFilePath(key)); if (file.exists()) { return file; } } return null; } /** * 缓存中是否有key的数据保存 * * @param key 关键字 * @Description: * @Date 2014-3-5 */ public final boolean containsKey(String key) { //是否在map中. if (mLinkedHashMap.containsKey(key)) { return true; } //如果不在map中,看是或否在文件夹中. final String existingFile = createFilePath(key); if (new File(existingFile).exists()) { //如果存在,放入map后期直接提取. onPutSuccess(key, existingFile); return true; } return false; } /** * 清除缓存. * * @Description: * @Date 2014-3-5 */ public final void clearCache() { final File[] files = mCacheDir.listFiles(CAHE_FILE_FILTER); for (int i = 0; i < files.length; i++) { files[i].delete(); } } /** * 根据key获得缓存文件路径. * * @param key 关键字 * @Description: * @Date 2014-3-5 */ public final String createFilePath(String key) { return new StringBuffer().append(mCacheDir.getAbsolutePath()) .append(File.separator).append(CACHE_FILENAME_PREFIX) .append(key.hashCode()).toString(); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/cache/base/ImageDiskLruCache.java
src/com/droid/cache/base/ImageDiskLruCache.java
package com.droid.cache.base; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.text.TextUtils; import com.droid.cache.util.CacheConfig; import com.droid.cache.util.CacheUtils; import com.droid.cache.util.LogUtil; import java.io.*; import java.util.Locale; /** * 硬盘缓存. * * @Title: * @Description: * @Since:2014-3-5 * @Version: */ public final class ImageDiskLruCache extends DiskLruCache { /** * 日志TAG. * */ private final static String TAG = "ImageDiskLruCache"; /** * Hint to the compressor, 0-100. 0 meaning compress for small size, * 100 meaning compress for max quality. * Some formats, like PNG which is lossless, will ignore the quality setting */ private int mCompressQuality = 100; /** * 构造函数. * * @param cacheDir 缓存文件目录 * @param maxByteSize 最大缓存大小 */ protected ImageDiskLruCache(File cacheDir, long maxByteSize) { super(cacheDir, maxByteSize); } /** * 打开一个图片硬盘缓存. * * @Description: * @Date 2014-3-6 */ public final static ImageDiskLruCache openImageCache(Context context, String cacheName, long maxByteSize) { File cacheDir = CacheUtils.getEnabledCacheDir(context, cacheName); if (cacheDir.isDirectory() && cacheDir.canWrite() && CacheUtils.getUsableSpace(cacheDir) > maxByteSize) { return new ImageDiskLruCache(cacheDir, maxByteSize); } return null; } /** * 存入图片. * * @param url key 关键字 * @param bitmap bitmap * @Description: * @Date 2014-3-5 */ public final void putImage(String url, Bitmap bitmap) { synchronized (mLinkedHashMap) { if (mLinkedHashMap.get(url) == null) { final String filePath = createFilePath(url); if (writeBitmapToFile(bitmap, filePath, url)) { onPutSuccess(url, filePath); flushCache(); } } } } /** * 获取图片. * * @param url key 关键字 * @return bitmap * @Description: * @Date 2014-3-5 */ public final Bitmap getImage(String url) { synchronized (mLinkedHashMap) { final String filePath = mLinkedHashMap.get(url); if (!TextUtils.isEmpty(filePath)) { LogUtil.d(TAG, "cache hit : " + url); return BitmapFactory.decodeFile(filePath); } else { final String existFilePath = createFilePath(url); if (new File(existFilePath).exists()) { onPutSuccess(url, existFilePath); LogUtil.d(TAG, "cache hit : " + url); return BitmapFactory.decodeFile(existFilePath); } } return null; } } /** * 把bitmap写入到缓存文件中. * * @param bitmap bitmap * @param filePath 缓存文件路径 * @Description: * @Date 2014-3-5 */ private boolean writeBitmapToFile(Bitmap bitmap, String filePath, String url) { OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(filePath), CacheConfig.IO_BUFFER_SIZE); return bitmap.compress(getCompressFormat(url), mCompressQuality, outputStream); } catch (FileNotFoundException e) { LogUtil.d(TAG, "bitmap compress fail : " + filePath, e); } finally { try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { LogUtil.d(TAG, "close outputStream error : " + e.getMessage()); } } return false; } /** * 根据文件类型获得CompressFormat. * * @Description: * @Date 2014-3-7 */ private CompressFormat getCompressFormat(String url) { String lowerUrl = url.toLowerCase(Locale.ENGLISH); if (lowerUrl.endsWith(".jpg")) { return CompressFormat.JPEG; } else if (lowerUrl.endsWith(".png")) { return CompressFormat.PNG; } return CompressFormat.JPEG; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/db/DBManager.java
src/com/droid/db/DBManager.java
package com.droid.db; import android.content.Context; import android.os.Environment; import android.util.Log; import com.droid.R; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class DBManager { private final int BUFFER_SIZE = 400000; public static final String PACKAGE_NAME = "com.cqsmiletv"; public static final String DB_NAME = "myapp.db"; public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME + "/databases"; private Context context; private static final String TAG ="DBManager"; private final boolean d = true; public DBManager(Context context) { this.context = context; } /** copy the database under raw */ public void copyDatabase() { } private void readDB(FileOutputStream fos, byte[] buffer, int db_id) throws IOException { int count; InputStream is; is = this.context.getResources().openRawResource(db_id); while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } is.close(); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/db/DBHelper.java
src/com/droid/db/DBHelper.java
package com.droid.db; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public DBHelper(Context context) { super(context, DBManager.DB_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public void update(String table_name, int id, String text) { SQLiteDatabase db = this.getWritableDatabase(); String where = "_id" + " = ?"; String[] whereValue = {Integer.toString(id)}; ContentValues cv = new ContentValues(); cv.put("url_data", text); db.update(table_name, cv, where, whereValue); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/db/DataBaseHelper.java
src/com/droid/db/DataBaseHelper.java
package com.droid.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DataBaseHelper extends SQLiteOpenHelper { private static final int VERSION = 1; String sql = "create table if not exists selectedApps" + "( position integer primary key,packageName string ,appName String,appIcon Blob)"; // String sql = "create table if not exists TestUsers"+ // "(id int primary key,name varchar,sex varchar)"; /** * 在SQLiteOpenHelper的子类当中,必须有该构造函数 * * @param context * 上下文对象 * @param name * 数据库名称 * @param factory * @param version * 当前数据库的版本,值必须是整数并且是递增的状态 */ public DataBaseHelper(Context context, String name, CursorFactory factory, int version) { // 必须通过super调用父类当中的构造函数 super(context, name, factory, version); } public DataBaseHelper(Context context, String name, int version) { this(context, name, null, version); } public DataBaseHelper(Context context, String name) { this(context, name, VERSION); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/db/SharedPreferencesUtil.java
src/com/droid/db/SharedPreferencesUtil.java
package com.droid.db; import android.content.Context; import android.content.SharedPreferences; import java.util.Set; /** * @author Droid */ public class SharedPreferencesUtil { private static final String SHAREDPREFERENCE_NAME = "sharedpreferences_droid"; private static SharedPreferencesUtil mInstance; private static SharedPreferences mSharedPreferences; private static SharedPreferences.Editor mEditor; public synchronized static SharedPreferencesUtil getInstance(Context context) { if (mInstance == null) { mInstance = new SharedPreferencesUtil(context); } return mInstance; } private SharedPreferencesUtil(Context context) { mSharedPreferences = context.getSharedPreferences( SHAREDPREFERENCE_NAME, Context.MODE_WORLD_READABLE); mEditor = mSharedPreferences.edit(); } public synchronized boolean putString(String key, String value) { mEditor.putString(key, value); return mEditor.commit(); } public synchronized boolean putInt(String key, int value) { mEditor.putInt(key, value); return mEditor.commit(); } public synchronized boolean putLong(String key, long value) { mEditor.putLong(key, value); return mEditor.commit(); } public synchronized boolean putFloat(String key, float value) { mEditor.putFloat(key, value); return mEditor.commit(); } public synchronized boolean putBoolean(String key, boolean value) { mEditor.putBoolean(key, value); return mEditor.commit(); } public synchronized boolean putStringSet(String key, Set<String> value) { mEditor.putStringSet(key, value); return mEditor.commit(); } public String getString(String key, String value) { return mSharedPreferences.getString(key, value); } public int getInt(String key, int value) { return mSharedPreferences.getInt(key, value); } public long getLong(String key, long value) { return mSharedPreferences.getLong(key, value); } public float getFloat(String key, float value) { return mSharedPreferences.getFloat(key, value); } public boolean getBoolean(String key, boolean value) { return mSharedPreferences.getBoolean(key, value); } public Set<String> getStringSet(String key, Set<String> value) { return mSharedPreferences.getStringSet(key, value); } public boolean remove(String key) { mEditor.remove(key); return mEditor.commit(); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/application/ClientApplication.java
src/com/droid/application/ClientApplication.java
package com.droid.application; import android.app.Application; import android.content.Context; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; public class ClientApplication extends Application { /** * 请求协议 */ public static final String HTTP = "http"; public static final boolean d = true; public static boolean netFlag = false; private static Context context; /** * 调试模式 */ public static boolean debug =false; @Override public void onCreate() { super.onCreate(); this.context = getApplicationContext(); initImageLoader(getApplicationContext()); } public static Context getContext() { return context; } /** * init UIL ImageLoader */ public static void initImageLoader(Context context) { // This configuration tuning is custom. You can tune every option, you // may tune some of them, // or you can create default configuration by // ImageLoaderConfiguration.createDefault(this); // method. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( context).threadPriority(Thread.NORM_PRIORITY - 2) .denyCacheImageMultipleSizesInMemory() .discCacheFileNameGenerator(new Md5FileNameGenerator()) .tasksProcessingOrder(QueueProcessingType.LIFO) .writeDebugLogs() // Remove for release app .build(); // Initialize ImageLoader with configuration. ImageLoader.getInstance().init(config); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/ImageTools.java
src/com/droid/utils/ImageTools.java
package com.droid.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader.TileMode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import com.droid.R; public class ImageTools { /** * 修改图片尺寸 * @param bitmap * @param width * @param height */ public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) { if (bitmap == null) { return null; } int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidth = ((float) width / w); float scaleHeight = ((float) height / h); matrix.postScale(scaleWidth, scaleHeight); Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true); return newbmp; } /** *图片阴影 * @param originalBitmap */ public static Drawable drawImageDropShadow(Bitmap originalBitmap, Context context) { BlurMaskFilter blurFilter = new BlurMaskFilter(3,BlurMaskFilter.Blur.NORMAL); Paint shadowPaint = new Paint(); shadowPaint.setAlpha(80); shadowPaint.setColor(context.getResources().getColor(R.color.black)); shadowPaint.setMaskFilter(blurFilter); int[] offsetXY = new int[2]; Bitmap shadowBitmap = originalBitmap.extractAlpha(shadowPaint, offsetXY); Bitmap shadowImage32 = shadowBitmap.copy(Bitmap.Config.ARGB_8888, true); if ( !shadowImage32.isPremultiplied() ) { shadowImage32.setPremultiplied( true ); } Canvas c = new Canvas(shadowImage32); c.drawBitmap(originalBitmap, offsetXY[0], offsetXY[1], null); return new BitmapDrawable(shadowImage32); } /** *圆形图片 * @param bitmap * @return */ public static Bitmap toRoundBitmap(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; if (width <= height) { roundPx = width / 2; left = 0; top = 0; right = width; bottom = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom); final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom); final RectF rectF = new RectF(dst); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, src, dst, paint); return output; } /** *圆角图片 * @param bitmap * @return */ public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); final float roundPx = 12; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } /** * 倒影图片 * @param originalBitmap * @return */ public static Bitmap createReflectedImage(Bitmap originalBitmap) { final int reflectionGap = 4; int width = originalBitmap.getWidth(); int height = originalBitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionBitmap = Bitmap.createBitmap(originalBitmap, 0, height / 2, width, height / 2, matrix, false); Bitmap withReflectionBitmap = Bitmap.createBitmap(width, (height + height / 2 + reflectionGap), Config.ARGB_8888); Canvas canvas = new Canvas(withReflectionBitmap); canvas.drawBitmap(originalBitmap, 0, 0, null); Paint defaultPaint = new Paint(); canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint); canvas.drawBitmap(reflectionBitmap, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, originalBitmap.getHeight(), 0, withReflectionBitmap.getHeight(), 0x70ffffff, 0x00ffffff, TileMode.MIRROR); paint.setShader(shader); paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); canvas.drawRect(0, height, width, withReflectionBitmap.getHeight(), paint); return withReflectionBitmap; } 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); //canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } public static Drawable bitmapToDrawable(Bitmap bitmap) { return new BitmapDrawable(bitmap); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/Tools.java
src/com/droid/utils/Tools.java
package com.droid.utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.security.MessageDigest; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.annotation.SuppressLint; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Environment; import android.os.StatFs; import android.telephony.TelephonyManager; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.Toast; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.http.HttpHandler; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import org.apache.http.HttpException; import org.json.JSONException; import org.json.JSONObject; @SuppressLint("DefaultLocale") public class Tools { private static boolean d = true; private static String TAG = "Tools"; private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public static String byteArrayToHexString(byte[] b) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++) { resultSb.append(byteToHexString(b[i])); } return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) n = 256 + n; int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; } /** * * @param origin * @return */ public static String md5Encode(String origin) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); resultString = byteArrayToHexString(md.digest(resultString .getBytes())); } catch (Exception ex) { ex.printStackTrace(); } return resultString; } /** * * @param mobiles * @return */ public static boolean isMobileNO(String mobiles) { Pattern p = Pattern .compile("^((13[0-9])|(15[^4,\\D])|(18[0,1,3,5-9]))\\d{8}$"); Matcher m = p.matcher(mobiles); System.out.println(m.matches() + "-telnum-"); return m.matches(); } /** * * @param expression * @param text * @return */ private static boolean matchingText(String expression, String text) { Pattern p = Pattern.compile(expression); Matcher m = p.matcher(text); boolean b = m.matches(); return b; } /** * * @param zipcode * @return */ public static boolean isZipcode(String zipcode) { Pattern p = Pattern.compile("[0-9]\\d{5}"); Matcher m = p.matcher(zipcode); System.out.println(m.matches() + "-zipcode-"); return m.matches(); } /** * * @param email * @return */ public static boolean isValidEmail(String email) { Pattern p = Pattern .compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"); Matcher m = p.matcher(email); System.out.println(m.matches() + "-email-"); return m.matches(); } /** * * @param telfix * @return */ public static boolean isTelfix(String telfix) { Pattern p = Pattern.compile("d{3}-d{8}|d{4}-d{7}"); Matcher m = p.matcher(telfix); System.out.println(m.matches() + "-telfix-"); return m.matches(); } /** * * @param name * @return */ public static boolean isCorrectUserName(String name) { Pattern p = Pattern.compile("([A-Za-z0-9]){2,10}"); Matcher m = p.matcher(name); System.out.println(m.matches() + "-name-"); return m.matches(); } /** * * @param pwd * @return * */ public static boolean isCorrectUserPwd(String pwd) { Pattern p = Pattern.compile("\\w{6,18}"); Matcher m = p.matcher(pwd); System.out.println(m.matches() + "-pwd-"); return m.matches(); } /** * * @return */ public static boolean hasSdcard() { String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } /** * * @param endTime * @param countDown * @return 剩余时间 */ public static String calculationRemainTime(String endTime, long countDown) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date now = new Date(System.currentTimeMillis());// ��ȡ��ǰʱ�� Date endData = df.parse(endTime); long l = endData.getTime() - countDown - now.getTime(); long day = l / (24 * 60 * 60 * 1000); long hour = (l / (60 * 60 * 1000) - day * 24); long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60); long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); return "ʣ��" + day + "��" + hour + "Сʱ" + min + "��" + s + "��"; } catch (ParseException e) { e.printStackTrace(); } return ""; } public static void showLongToast(Context act, String pMsg) { Toast toast = Toast.makeText(act, pMsg, Toast.LENGTH_LONG); toast.show(); } public static void showShortToast(Context act, String pMsg) { Toast toast = Toast.makeText(act, pMsg, Toast.LENGTH_SHORT); toast.show(); } /** * * @param context * @return */ public static String getImeiCode(Context context) { TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); return tm.getDeviceId(); } /** * @author sunglasses * @param listView * @category 计算listview高度 */ public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } public static PackageInfo getAPKVersionInfo(Context context, String packageName) { PackageManager packageManager = context.getPackageManager(); PackageInfo packInfo = null; try { packInfo = packageManager.getPackageInfo(packageName, 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return packInfo; } public static void download(String url, String path, final IOAuthCallBack iOAuthCallBack) { HttpUtils http = new HttpUtils(); HttpHandler<File> handler = http.download(url, path, false, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。 false, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。 new RequestCallBack<File>() { @Override public void onSuccess(ResponseInfo<File> arg0) { if (d) Log.d("-----downfile-----", "success"); iOAuthCallBack.getIOAuthCallBack(arg0.result.getName(), 0); } @Override public void onFailure(com.lidroid.xutils.exception.HttpException e, String s) { if (d) Log.d("-----downfile-----", "fail"); iOAuthCallBack.getIOAuthCallBack(e.toString(), 1); } }); } public static void installApk(Context context, File apk, String md5) { // 校验文件MD5 值 // try { // Log.d(TAG, // "md5" + MD5Util.getFileMD5String(apk).equalsIgnoreCase(md5)); // if (!apk.exists() // || !MD5Util.getFileMD5String(apk).equalsIgnoreCase(md5)) { // Log.d(TAG, "md5 check error"); // return; // } // } catch (Exception e) { // e.printStackTrace(); // } FileUtils.modifyFile(apk);// 修改文件权限之可执行 Log.i(TAG, "===========install apk =========" + apk.getAbsolutePath()); Intent i = new Intent(Intent.ACTION_VIEW); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setDataAndType(Uri.parse("file://" + apk.getAbsolutePath()), "application/vnd.android.package-archive"); context.startActivity(i); } /** * @author cat * @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网) * @return */ public static final boolean ping() { String result = null; try { String ip = "www.baidu.com";// 除非百度挂了,否则用这个应该没问题(也可以换成自己要连接的服务器地址) Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " + ip);// ping3次 // 读取ping的内容,可不加。 InputStream input = p.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); StringBuffer stringBuffer = new StringBuffer(); String content = ""; while ((content = in.readLine()) != null) { stringBuffer.append(content); } Log.i("TTT", "result content : " + stringBuffer.toString()); // PING的状态 int status = p.waitFor(); if (status == 0) { result = "successful~"; return true; } else { result = "failed~ cannot reach the IP address"; } } catch (IOException e) { result = "failed~ IOException"; } catch (InterruptedException e) { result = "failed~ InterruptedException"; } finally { Log.i("TTT", "result = " + result); } return false; } /** * 得到sd卡剩余大小 * @return */ public static long getSDAvailableSize() { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return blockSize * availableBlocks/1024; } /** * 判断是否是json结构 */ public static boolean isJson(String value) { try { new JSONObject(value); } catch (JSONException e) { return false; } return true; } public static List<ResolveInfo> findActivitiesForPackage(Context context, String packageName) { final PackageManager packageManager = context.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); mainIntent.setPackage(packageName); final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); return apps != null ? apps : new ArrayList<ResolveInfo>(); } static public boolean removeBond(Class btClass,BluetoothDevice btDevice) throws Exception { Method removeBondMethod = btClass.getMethod("removeBond"); Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice); return returnValue.booleanValue(); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/MD5Util.java
src/com/droid/utils/MD5Util.java
package com.droid.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Util { /** * 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合 */ protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; protected static MessageDigest messagedigest = null; static { try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsaex) { System.err.println(MD5Util.class.getName() + "初始化失败,MessageDigest不支持MD5Util。"); nsaex.printStackTrace(); } } /** * 生成字符串的md5校验值 * * @param s * @return */ public static String getMD5String(String s) { return getMD5String(s.getBytes()); } /** * 判断字符串的md5校验码是否与一个已知的md5码相匹配 * * @param password 要校验的字符串 * @param md5PwdStr 已知的md5校验码 * @return */ public static boolean checkPassword(String password, String md5PwdStr) { String s = getMD5String(password); return s.equals(md5PwdStr); } /** * 生成文件的md5校验值 * * @param file * @return * @throws java.io.IOException */ public static String getFileMD5String(File file) throws IOException { InputStream fis; fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int numRead = 0; while ((numRead = fis.read(buffer)) > 0) { messagedigest.update(buffer, 0, numRead); } fis.close(); return bufferToHex(messagedigest.digest()); } /** * JDK1.4中不支持以MappedByteBuffer类型为参数update方法,并且网上有讨论要慎用MappedByteBuffer, * 原因是当使用 FileChannel.map 方法时,MappedByteBuffer 已经在系统内占用了一个句柄, 而使用 * FileChannel.close 方法是无法释放这个句柄的,且FileChannel有没有提供类似 unmap 的方法, * 因此会出现无法删除文件的情况。 * * 不推荐使用 * * @param file * @return * @throws java.io.IOException */ public static String getFileMD5String_old(File file) throws IOException { FileInputStream in = new FileInputStream(file); FileChannel ch = in.getChannel(); MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); messagedigest.update(byteBuffer); return bufferToHex(messagedigest.digest()); } public static String getMD5String(byte[] bytes) { if (bytes !=null) { messagedigest.update(bytes); return bufferToHex(messagedigest.digest()); } else { return null; } } private static String bufferToHex(byte bytes[]) { return bufferToHex(bytes, 0, bytes.length); } private static String bufferToHex(byte bytes[], int m, int n) { StringBuffer stringbuffer = new StringBuffer(2 * n); int k = m + n; for (int l = m; l < k; l++) { appendHexPair(bytes[l], stringbuffer); } return stringbuffer.toString(); } private static void appendHexPair(byte bt, StringBuffer stringbuffer) { char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>> // 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同 char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换 stringbuffer.append(c0); stringbuffer.append(c1); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/NetWorkUtil.java
src/com/droid/utils/NetWorkUtil.java
package com.droid.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.net.wifi.WifiManager; import java.lang.reflect.Method; import java.security.MessageDigest; /** * @author Droid */ public class NetWorkUtil { private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public static final int STATE_DISCONNECT = 0; public static final int STATE_WIFI = 1; public static final int STATE_MOBILE = 2; // wifi 热点 public static final int WIFI_AP_STATE_DISABLING = 10; public static final int WIFI_AP_STATE_DISABLED = 11; public static final int WIFI_AP_STATE_ENABLING = 12; public static final int WIFI_AP_STATE_ENABLED = 13; public static final int WIFI_AP_STATE_FAILED = 14; private static int getWifiApState(Context mContext) { WifiManager wifiManager = (WifiManager) mContext .getSystemService(Context.WIFI_SERVICE); try { Method method = wifiManager.getClass().getMethod("getWifiApState"); int i = (Integer) method.invoke(wifiManager); return i; } catch (Exception e) { return WIFI_AP_STATE_FAILED; } } private static boolean isApEnabled(Context mContext) { int state = getWifiApState(mContext); return WIFI_AP_STATE_ENABLING == state || WIFI_AP_STATE_ENABLED == state; } private static boolean isWifiApEnabled(Context context) { WifiManager wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); try { Method method = wifiManager.getClass().getMethod("isWifiApEnabled"); method.setAccessible(true); return (Boolean) method.invoke(wifiManager); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return false; } public static String concatUrlParams() { return null; } public static String encodeUrl() { return null; } public static boolean isNetWorkConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] nis = cm.getAllNetworkInfo(); if (nis != null) { for (NetworkInfo ni : nis) { if (ni != null) { if (ni.isConnected()) { return true; } } } } return false; } public static boolean isWifiConnected(Context context) { WifiManager wifiMgr = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); boolean isWifiEnable = wifiMgr.isWifiEnabled(); return isWifiEnable; } public static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null) { return networkInfo.isAvailable(); } return false; } private static String byteArrayToHexString(byte[] b) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++) { resultSb.append(byteToHexString(b[i])); } return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) n = 256 + n; int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; } public static String md5Encode(String origin) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); resultString = new String(md.digest(resultString.getBytes())); } catch (Exception ex) { ex.printStackTrace(); } return resultString; } public static String md5EncodeToHexString(String origin) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); resultString = byteArrayToHexString(md.digest(resultString .getBytes())); } catch (Exception ex) { ex.printStackTrace(); } return resultString; } public static int getNetworkState(Context context) { ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); // Wifi State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); if (state == State.CONNECTED || state == State.CONNECTING) { return STATE_WIFI; } // 3G state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) .getState(); if (state == State.CONNECTED || state == State.CONNECTING) { return STATE_MOBILE; } return STATE_DISCONNECT; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/UpdateManager.java
src/com/droid/utils/UpdateManager.java
package com.droid.utils; import android.content.*; import android.os.Handler; import android.os.Message; import com.droid.db.SharedPreferencesUtil; import org.json.JSONArray; import org.json.JSONException; /** * apk更新下载 */ public class UpdateManager { private static final String TAG = "UpdateManager"; private Context mContext; private static final int DOWN_UPDATE = 1; private static final int DOWN_OVER = 2; private String packageVersion; private String packageDownloadPath; private String packageMD5; private JSONArray appList; private boolean d = true;// debug flag private SharedPreferencesUtil sp; private FileCache fileCache; public UpdateManager(Context context) { this.mContext = context; fileCache = new FileCache(mContext); sp = SharedPreferencesUtil.getInstance(mContext); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case DOWN_UPDATE: break; case DOWN_OVER: break; default: break; } } }; /** * 外部接口让主Activity调用 请求服务器并检查服务器apk版本信息 */ public void checkUpdateInfo() { } public String getCacheDir() { return fileCache.getCacheDir(); } /** * 下载apk * */ private void downloadApk() throws JSONException { } /** * 下载zip */ private void downloadZip() {} }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/FileCache.java
src/com/droid/utils/FileCache.java
package com.droid.utils; import java.io.File; import java.util.ArrayList; import android.content.Context; public class FileCache { public File cacheDir; public FileCache(Context context) { if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { cacheDir = new File( android.os.Environment.getExternalStorageDirectory(), "WoDouCache"); } else { cacheDir = context.getCacheDir(); } if (!cacheDir.exists()) { cacheDir.mkdirs(); } } public ArrayList<File> getFile() { File file[] = cacheDir.listFiles(); ArrayList<File> list = new ArrayList<File>(); for (int i = 0; i < file.length; i++) { list.add(file[i]); } return list; } public String getCacheDir(){ return cacheDir.toString(); } public void clear() { File[] files = cacheDir.listFiles(); for (File f : files) f.delete(); } public String getCacheSize() { long size = 0; if (cacheDir.exists()) { File[] files = cacheDir.listFiles(); for (File f : files) { size += f.length(); } } String cacheSize = String.valueOf(size / 1024 / 1024) + "M"; return cacheSize; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/FileUtils.java
src/com/droid/utils/FileUtils.java
package com.droid.utils; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import android.content.Context; import android.os.Environment; import android.os.StatFs; import android.util.Log; import com.droid.application.ClientApplication; /** * 读取文件工具类 */ public class FileUtils { private final static String TAG = "FileUitl------读取文件工具类"; private static final boolean d = ClientApplication.debug; private static String path = "/sdcard/GMYZ/log/"; private static String padFilePath = "/sdcard/driver.ini"; /** * 写文本文件 在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下 * * @param context */ public static void write(Context context, String fileName, String content) { if (content == null) content = ""; try { FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); fos.write(content.getBytes()); fos.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 读取文本文件 * * @param context * @param fileName * @return */ public static String read(Context context, String fileName) { try { FileInputStream in = context.openFileInput(fileName); return readInStream(in); } catch (Exception e) { // e.printStackTrace(); return ""; } } private static String readInStream(FileInputStream inStream) { try { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[512]; int length = -1; while ((length = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, length); } outStream.close(); inStream.close(); return outStream.toString(); } catch (IOException e) { // UIHelper.Log("e", "", "FileReadError", true); } return null; } public static File createFile(String folderPath, String fileName) { File destDir = new File(folderPath); if (!destDir.exists()) { destDir.mkdirs(); } return new File(folderPath, fileName + fileName); } /** * * * @param buffer * @param folder * @param fileName * @return */ public static boolean writeFile(byte[] buffer, String folder, String fileName) { boolean writeSucc = false; boolean sdCardExist = Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED); String folderPath = ""; if (sdCardExist) { folderPath = Environment.getExternalStorageDirectory() + File.separator + folder + File.separator; } else { writeSucc = false; } File fileDir = new File(folderPath); if (!fileDir.exists()) { fileDir.mkdirs(); } File file = new File(folderPath + fileName); FileOutputStream out = null; try { out = new FileOutputStream(file); out.write(buffer); writeSucc = true; } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } return writeSucc; } /** * 根据文件绝对路径获取文件名 * * @param filePath * @return */ public static String getFileName(String filePath) { if (null == filePath || "".equals(filePath)) return ""; return filePath.substring(filePath.lastIndexOf(File.separator) + 1); } /** * 根据文件的绝对路径获取文件名但不包含扩展名 * * @param filePath * @return */ public static String getFileNameNoFormat(String filePath) { if (null == filePath || "".equals(filePath)) { return ""; } int point = filePath.lastIndexOf('.'); return filePath.substring(filePath.lastIndexOf(File.separator) + 1, point); } /** * 获取文件扩展名 * * @param fileName * @return */ public static String getFileFormat(String fileName) { if (null == fileName || "".equals(fileName)) return ""; int point = fileName.lastIndexOf('.'); return fileName.substring(point + 1); } /** * 获取文件大小 * * @param filePath * @return */ public static long getFileSize(String filePath) { long size = 0; File file = new File(filePath); if (file != null && file.exists()) { size = file.length(); } return size; } /** * 获取文件大小 * * @param size * 字节 * @return */ public static String getFileSize(long size) { if (size <= 0) return "0"; java.text.DecimalFormat df = new java.text.DecimalFormat("##.##"); float temp = (float) size / 1024; if (temp >= 1024) { return df.format(temp / 1024) + "M"; } else { return df.format(temp) + "K"; } } /** * 转换文件大小 * * @param fileS * @return B/KB/MB/GB */ public static String formatFileSize(long fileS) { java.text.DecimalFormat df = new java.text.DecimalFormat("#.00"); String fileSizeString = ""; if (fileS < 1024) { fileSizeString = df.format((double) fileS) + "B"; } else if (fileS < 1048576) { fileSizeString = df.format((double) fileS / 1024) + "KB"; } else if (fileS < 1073741824) { fileSizeString = df.format((double) fileS / 1048576) + "MB"; } else { fileSizeString = df.format((double) fileS / 1073741824) + "G"; } return fileSizeString; } /** * 获取目录文件大小 * * @param dir * @return */ public static long getDirSize(File dir) { if (dir == null) { return 0; } if (!dir.isDirectory()) { return 0; } long dirSize = 0; File[] files = dir.listFiles(); for (File file : files) { if (file.isFile()) { dirSize += file.length(); } else if (file.isDirectory()) { dirSize += file.length(); dirSize += getDirSize(file); // 递归调用继续统计 } } return dirSize; } /** * 获取目录文件个数 * * @param * @return */ public long getFileList(File dir) { long count = 0; File[] files = dir.listFiles(); count = files.length; for (File file : files) { if (file.isDirectory()) { count = count + getFileList(file);// 递归 count--; } } return count; } public static byte[] toBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int ch; while ((ch = in.read()) != -1) { out.write(ch); } byte buffer[] = out.toByteArray(); out.close(); return buffer; } /** * 检查文件是否存在 * * @param name * @return */ public static boolean checkFileExists(String name) { boolean status; if (!name.equals("")) { File path = Environment.getExternalStorageDirectory(); File newPath = new File(path.toString() + name); status = newPath.exists(); } else { status = false; } return status; } /** * 计算SD卡的剩余空间 * * @return 返回-1,说明没有安装sd卡 */ public static long getFreeDiskSpace() { String status = Environment.getExternalStorageState(); long freeSpace = 0; if (status.equals(Environment.MEDIA_MOUNTED)) { try { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); freeSpace = availableBlocks * blockSize / 1024; } catch (Exception e) { e.printStackTrace(); } } else { return -1; } return (freeSpace); } /** * 新建目录 * * @param directoryName * @return */ public static boolean createDirectory(String directoryName) { boolean status; if (!directoryName.equals("")) { File path = Environment.getExternalStorageDirectory(); File newPath = new File(path.toString() + directoryName); status = newPath.mkdir(); status = true; } else status = false; return status; } /** * 检查是否安装SD卡 * * @return */ public static boolean checkSaveLocationExists() { String sDCardStatus = Environment.getExternalStorageState(); boolean status; if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) { status = true; } else status = false; return status; } /** * 删除目录(包括:目录里的所有文件) * * @param fileName * @return */ public static boolean deleteDirectory(String fileName) { boolean status; SecurityManager checker = new SecurityManager(); if (!fileName.equals("")) { File path = Environment.getExternalStorageDirectory(); File newPath = new File(path.toString() + fileName); checker.checkDelete(newPath.toString()); if (newPath.isDirectory()) { String[] listfile = newPath.list(); // delete all files within the specified directory and then // delete the directory try { for (int i = 0; i < listfile.length; i++) { File deletedFile = new File(newPath.toString() + "/" + listfile[i].toString()); deletedFile.delete(); } newPath.delete(); // UIHelper.Log("i", "", fileName, true); status = true; } catch (Exception e) { e.printStackTrace(); status = false; } } else status = false; } else status = false; return status; } /** * 删除文件 * * @param fileName * @return */ public static boolean deleteFile(String fileName) { boolean status; SecurityManager checker = new SecurityManager(); if (!fileName.equals("")) { File path = Environment.getExternalStorageDirectory(); File newPath = new File(path.toString() + fileName); checker.checkDelete(newPath.toString()); if (newPath.isFile()) { try { // UIHelper.Log("i", "", fileName); newPath.delete(); status = true; } catch (SecurityException se) { se.printStackTrace(); status = false; } } else status = false; } else status = false; return status; } /** * @param msgID * @param log * @param isLog * @return */ public static String saveLog(String msgID, String log, boolean isLog, String fileName) { if (!isLog) { return null; } SimpleDateFormat logTime = new SimpleDateFormat("yyyyMMddHHmmss"); Date logD = new Date(System.currentTimeMillis()); StringBuffer sb = new StringBuffer(); if (msgID != null && !msgID.equals("")) { sb.append(logTime.format(logD) + "【" + msgID + "】\n"); } else { sb.append(logTime.format(logD) + "\t\t"); } String logStr = ""; String splitStr = "body"; String[] tempStr = log.split(splitStr); if (tempStr.length > 1) { logStr += tempStr[0] + "\n" + splitStr; String body = tempStr[1].replaceAll(",", ""); tempStr = body.split("]"); for (int i = 0; i < tempStr.length; i++) { if (i != tempStr.length - 2) { logStr += tempStr[i] + "],\n"; } else { logStr += tempStr[i] + ""; } } sb.append(logStr.substring(0, logStr.length() - 4)); } else { sb.append(log); } sb.append("\n"); SimpleDateFormat logFt = new SimpleDateFormat("yyyyMMdd"); Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); printWriter.close(); try { long timestamp = System.currentTimeMillis(); Date d = new Date(timestamp); String time = logFt.format(d); if (null == fileName || fileName.equals("")) { fileName = "log"; } fileName += ("-" + time + ".txt"); if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } File f = new File(path + fileName); if (!f.exists()) { f.createNewFile(); } FileOutputStream fost = new FileOutputStream(f, true); BufferedWriter myo = new BufferedWriter(new OutputStreamWriter( fost, "GBK")); myo.write(sb.toString()); myo.close(); } return fileName; } catch (Exception e) { if(d)Log.e(TAG, "an error occured while writing file...", e); } return null; } public static String saveLog(String log, boolean isLog, String fileName) { return saveLog(log, "", isLog, fileName); } public static String saveLog(String log, boolean isLog) { return saveLog(log, "", isLog, null); } public String readSDFile(String fileName) { StringBuffer sb = new StringBuffer(); File file = new File(padFilePath + "//" + fileName); if (!file.exists()) { return ""; } try { FileInputStream fis = new FileInputStream(file); int c; while ((c = fis.read()) != -1) { sb.append((char) c); } fis.close(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } public static List<File> list(File dir, String nametxt, String ext, String type, List<File> fs) { listFile(dir, nametxt, type, ext, fs); File[] all = dir.listFiles(); // 递归获得当前目录的所有子目录 for (int i = 0; i < all.length; i++) { File d = all[i]; if (d.isDirectory()) { list(d, nametxt, ext, type, fs); } } return null; // 遍历子目,列出每个子目录的文�? } /** * @param dir * 根目 * @param nametxt * 文件名中包含的关键字 * @param type * 文件夹的类型 * @param ext * 后缀 * @param fs * 返回的结 * @return */ private static List<File> listFile(File dir, String nametxt, String type, String ext, List<File> fs) { File[] all = dir.listFiles(new Fileter(ext)); for (int i = 0; i < all.length; i++) { File d = all[i]; if (d.getName().toLowerCase().indexOf(nametxt.toLowerCase()) >= 0) { if (type.equals("1")) { fs.add(d); } else if (d.isDirectory() && type.equals("2")) { fs.add(d); } else if (!d.isDirectory() && type.equals("3")) { fs.add(d); } } } return fs; } public static boolean delFile(String filePathAndName) { boolean bea = false; try { String filePath = filePathAndName; File myDelFile = new File(filePath); if (myDelFile.exists()) { myDelFile.delete(); bea = true; } else { bea = false; } } catch (Exception e) { e.printStackTrace(); } return bea; } static class Fileter implements FilenameFilter { private final String ext; public Fileter(String ext) { this.ext = ext; } @Override public boolean accept(File dir, String name) { return name.endsWith(ext); } } public static void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { // 文件存在 InputStream inStream = new FileInputStream(oldPathFile); // 读入源文�? File n = new File(newPathFile); if (!n.exists()) { n.createNewFile(); } FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; // 字节 文件大小 fs.write(buffer, 0, byteread); } fs.flush(); fs.close(); inStream.close(); } } catch (Exception e) { e.printStackTrace(); } } public static void moveFile(String oldPath, String newPath) { copyFile(oldPath, newPath); delFile(oldPath); } /** * 修改文件权限 * * @param file */ public static void modifyFile(File file) { Process process = null; try { String command = "chmod -R 777 " + file.getAbsolutePath(); Runtime runtime = Runtime.getRuntime(); process = runtime.exec(command); process.waitFor(); } catch (Exception e) { e.printStackTrace(); } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/LogUtil.java
src/com/droid/utils/LogUtil.java
package com.droid.utils; /** * Created by suncat on 2015/1/5. */ import android.content.Context; import android.os.Environment; import android.util.Log; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.regex.Pattern; /** * 打印工具类 * @author meimuan * 功能点: * 可以控制打印输出 * 可以简便打印,经过包装得到精准特定格式的日志信息 * 可以直接打印异常 * 可以定位异常信息 * 可以便捷统一修改,优化 * 同步输出日志到本地sdcard文件 * 需要注册权限: * 读写SD卡权限 * android.permission.WRITE_EXTERNAL_STORAGE * 网络权限 * android.permission.INTERNET * 说明: * 1. 日志是针对天数级别的,自动生成的日志名称yyyyMMdd.log形式 * 2. 如果当天的日志需要新开一个(比如:日志很大了,需要从新生成一个) */ public class LogUtil { /** 控制打印级别 在level级别之上才可以被打印出来 */ public static int LEVEL = 3; /** 打印级别为V,对应Log.v*/ public final static int V = 1; /** 打印级别为W,对应Log.w*/ public final static int W = 2; /** 打印级别为I,对应Log.i*/ public final static int I = 3; /** 打印级别为D,对应Log.d*/ public final static int D = 4; /** 打印级别为E,对应Log.e*/ public final static int E = 5; /** 最高级别打印,强制性打印,LEVEL无法关闭。 */ private final static int P = Integer.MAX_VALUE; /** 打印修饰符号*/ private static final String _L = "["; private static final String _R = "]"; /** 是否同步输出到本地日志文件 */ private static boolean IS_SYNS = true; /** 打印日志保存路径*/ private static String LOG_FILE_DIR = SDcardUtil.getPath() + File.separator + "smileTvLog"; /** 生成一个日期文件名格式的日式格式对象*/ private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.getDefault()); /** 是否新建一个日志文件。*/ private static boolean IF_START_NEWLOG = false; /** 保存创建的文件路径 */ private static String CURRENT_LOG_NAME = ""; /** 针对天数级别的。如果当天已经存在一个LOG了,而使用者需要新开一个LOG,那么将计数 */ private static int FILE_LOG_COUNT = 0; /** 单个日志的最大的容量,如果一个日志太大了,打开会影响效率*/ private static int LOG_MAX_SIZE = 6 * 1024 * 1024; /** 检测文件目的地址是否正确 */ private static Pattern pattern = Pattern.compile("(\\w+/)+"); /** 设置是否同步记录信息或者异常到日志文件。*/ public static void setSyns(boolean flag) { synchronized (LogUtil.class){ IS_SYNS = flag; } } /** 开启一个新的LOG */ public static void startNewLog() { IF_START_NEWLOG = true; } /** * 打印信息 * @param message */ public static void i(String message) { if (LEVEL <= I) { Log.i(getTag(message), message); if (IS_SYNS) { LogFile.writeLog(message); } } } public static void i(Exception exp) { if (LEVEL <= I) { Log.i(getTag(exp),getMessage(exp)); if (IS_SYNS) { LogFile.writeLog(exp); } } } public static void e(String message) { if (LEVEL <= E) { Log.e(getTag(message), message); if (IS_SYNS) { LogFile.writeLog(message); } } } public static void e(Exception exp) { if (LEVEL <= E) { Log.e(getTag(exp),getMessage(exp)); if (IS_SYNS) { LogFile.writeLog(exp); } } } public static void w(String message) { if (LEVEL <= W) { Log.w(getTag(message), message); if (IS_SYNS) { LogFile.writeLog(message); } } } public static void w(Exception exp) { if (LEVEL <= W) { Log.w(getTag(exp),getMessage(exp)); if (IS_SYNS) { LogFile.writeLog(exp); } } } public static void v(String message) { if (LEVEL <= V) { Log.v(getTag(message), message); if (IS_SYNS) { LogFile.writeLog(message); } } } public static void v(Exception exp) { if (LEVEL <= V) { Log.v(getTag(exp),getMessage(exp)); if (IS_SYNS) { LogFile.writeLog(exp); } } } public static void d(String message) { if (LEVEL <= D) { Log.d(getTag(message), message); if (IS_SYNS) { LogFile.writeLog(message); } } } public static void d(Exception exp) { if (LEVEL <= D) { Log.d(getTag(exp),getMessage(exp)); if (IS_SYNS) { LogFile.writeLog(exp); } } } /** * 强制打印信息 * @param message */ public static void print(String message) { if (LEVEL <= P) { Log.e(getTag(message), message); if (IS_SYNS) LogFile.writeLog(message); } } /** * 强制打印异常 * @param exp */ public static void print(Exception exp) { if (LEVEL <= P) { Log.e(getTag(exp), getMessage(exp)); if (IS_SYNS) LogFile.writeLog(exp); } } /** 获取一个Tag打印标签 * @param msg * @return * @since JDK 1.5 */ private static String getTag(String msg) { if (msg != null) { //since jdk 1.5 if (Thread.currentThread().getStackTrace().length > 0) { String name = Thread.currentThread().getStackTrace()[0].getClassName(); return _L + name.substring(name.lastIndexOf(".") + 1) + _R; } } return _L + "null" + _R; } /** * 跟据变量获取一个打印的标签。 * @param exp * @return */ private static String getTag(Exception exp) { if (exp != null) { if (exp.getStackTrace().length > 0) { String name = exp.getStackTrace()[0].getClassName(); return _L + name.substring(name.lastIndexOf(".") + 1) + _R; } return _L + "exception" + _R; } return _L + "null" + _R; } /** * 获取Exception的简便异常信息 * @param exp * @return */ private static String getMessage(Exception exp) { StringBuilder sb = new StringBuilder(); StackTraceElement[] element = exp.getStackTrace(); int n = 0; sb.append("\n"); sb.append(exp.toString()); sb.append("\n"); for (StackTraceElement e : element) { sb.append(e.getClassName()); sb.append("."); sb.append(e.getMethodName()); sb.append("["); sb.append(e.getLineNumber()); sb.append("]"); sb.append("\n"); n++; if (n >= 2) break; } if (exp.getCause() != null) { sb.append("Caused by: "); sb.append(exp.getMessage()); } return sb.toString(); } /** 自定义保存文件路径,如果是多重路径,请以xxx/xxx/xxx 形式的‘文件夹’ * @parma path : 文件夹名称 * * [将自动以当前时间为文件名拼接成完整路径。请慎用] * */ public static void setLogFilePath(String path) { String url = SDcardUtil.getPath() + File.separator + path; boolean flag = pattern.matcher(url).matches(); if (flag) { LOG_FILE_DIR = url; } else { LogFile.print("the url is not match file`s dir"); } } /** 设置默认路径,以包名为格式的文件夹*/ public static void setDefaultFilePath(Context context) { String pkName = context.getPackageName().replaceAll("\\.", "\\/"); setLogFilePath(pkName); } /** 获取时间字符串 */ private static String getCurrTimeDir() { return sdf.format(new Date()); } /** LOG定制类。 * 输出LOG到日志。 */ private static class LogFile { /** 内部强制性打印使用。区分print , 是为了解决无限循环打印exception*/ private static void print(String msg) { if (LEVEL <= P) { Log.e(getTag(msg), msg); } } /** * 打印信息 * @param message */ public static synchronized void writeLog(String message) { File f = getFile(); if (f != null) { try { FileWriter fw = new FileWriter(f , true); BufferedWriter bw = new BufferedWriter(fw); bw.append("\n"); bw.append(message); bw.append("\n"); bw.flush(); bw.close(); fw.close(); } catch (IOException e) { print("writeLog error, " + e.getMessage()); } } else { print("writeLog error, due to the file dir is error"); } } /** * 打印异常 * @param exp */ public static synchronized void writeLog(Exception exp) { File f = getFile(); if (f != null) { try { FileWriter fw = new FileWriter(f , true); PrintWriter pw = new PrintWriter(fw); pw.append("\n"); exp.printStackTrace(pw); pw.flush(); pw.close(); fw.close(); } catch (IOException e) { print("writeLog error, " + e.getMessage()); } } else { print("writeLog error, due to the file dir is error"); } } /** * 获取文件 * @return */ private static File getFile() { if ("".equals(LOG_FILE_DIR)) { return null; } synchronized (LogUtil.class) { if (!IF_START_NEWLOG) { File currFile = new File(CURRENT_LOG_NAME); if (currFile.length() >= LOG_MAX_SIZE) { IF_START_NEWLOG = true; return getFile(); } return currFile; } File f = new File(LOG_FILE_DIR); if (!f.exists()) { f.mkdirs(); } File file = new File(f.getAbsolutePath() + File.separator + getCurrTimeDir() + ".log"); if (!file.exists()) { try { file.createNewFile(); FILE_LOG_COUNT = 0; IF_START_NEWLOG = false; CURRENT_LOG_NAME = file.getAbsolutePath(); } catch (IOException e) { print("createFile error , " + e.getMessage()); } } else { //已经存在了 if (IF_START_NEWLOG) { FILE_LOG_COUNT ++; return new File(f.getAbsolutePath() + File.separator + getCurrTimeDir() + "_" + FILE_LOG_COUNT+ ".log"); } } return file; } } } /** * SD卡管理器 */ private static class SDcardUtil { // public static String getAbsPath() { // if (isMounted()) { // return Environment.getExternalStorageDirectory().getAbsolutePath(); // } // return ""; // } /** 获取Path*/ public static String getPath() { if (isMounted()) { return Environment.getExternalStorageDirectory().getPath(); } LogFile.print("please check if sd card is not mounted"); return ""; } /** 判断SD卡是否mounted*/ public static boolean isMounted() { return Environment.isExternalStorageEmulated(); } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/IOAuthCallBack.java
src/com/droid/utils/IOAuthCallBack.java
package com.droid.utils; /** * 数据回调接口 */ public interface IOAuthCallBack { public void getIOAuthCallBack(String result,int state); }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/ZipUtil.java
src/com/droid/utils/ZipUtil.java
package com.droid.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; 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.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; public class ZipUtil { private static final int BUFF_SIZE = 1024 * 1024; // 1M Byte /** * 批量压缩文件(夹) * * @param resFileList 要压缩的文件(夹)列表 * @param zipFile 生成的压缩文件 * @throws IOException 当压缩过程出错时抛出 */ public static void zipFiles(Collection<File> resFileList, File zipFile) throws IOException { ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream( zipFile), BUFF_SIZE)); for (File resFile : resFileList) { zipFile(resFile, zipout, ""); } zipout.close(); } /** * 批量压缩文件(夹) * * @param resFileList 要压缩的文件(夹)列表 * @param zipFile 生成的压缩文件 * @param comment 压缩文件的注释 * @throws IOException 当压缩过程出错时抛出 */ public static void zipFiles(Collection<File> resFileList, File zipFile, String comment) throws IOException { ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream( zipFile), BUFF_SIZE)); for (File resFile : resFileList) { zipFile(resFile, zipout, ""); } zipout.setComment(comment); zipout.close(); } /** * 解压缩一个文件 * * @param zipFile 压缩文件 * @param folderPath 解压缩的目标目录 * @throws IOException 当解压缩过程出错时抛出 */ public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException { File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdirs(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry)entries.nextElement()); InputStream in = zf.getInputStream(entry); String name = entry.getName(); name = name.split("_")[0]; String str = folderPath + File.separator + name+".apk"; str = new String(str.getBytes("8859_1"), "GB2312"); File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); } } /** * 解压文件名包含传入文字的文件 * * @param zipFile 压缩文件 * @param folderPath 目标文件夹 * @param nameContains 传入的文件匹配名 * @throws ZipException 压缩格式有误时抛出 * @throws IOException IO错误时抛出 */ public static ArrayList<File> upZipSelectedFile(File zipFile, String folderPath, String nameContains) throws ZipException, IOException { ArrayList<File> fileList = new ArrayList<File>(); File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdir(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry)entries.nextElement()); if (entry.getName().contains(nameContains)) { InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = new String(str.getBytes("8859_1"), "GB2312"); // str.getBytes("GB2312"),"8859_1" 输出 // str.getBytes("8859_1"),"GB2312" 输入 File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); fileList.add(desFile); } } return fileList; } /** * 获得压缩文件内文件列表 * * @param zipFile 压缩文件 * @return 压缩文件内文件名称 * @throws ZipException 压缩文件格式有误时抛出 * @throws IOException 当解压缩过程出错时抛出 */ public static ArrayList<String> getEntriesNames(File zipFile) throws ZipException, IOException { ArrayList<String> entryNames = new ArrayList<String>(); Enumeration<?> entries = getEntriesEnumeration(zipFile); while (entries.hasMoreElements()) { ZipEntry entry = ((ZipEntry)entries.nextElement()); entryNames.add(new String(getEntryName(entry).getBytes("GB2312"), "8859_1")); } return entryNames; } /** * 获得压缩文件内压缩文件对象以取得其属性 * @param zipFile 压缩文件 * @return 返回一个压缩文件列表 * @throws ZipException 压缩文件格式有误时抛出 * @throws IOException IO操作有误时抛出 */ public static Enumeration<?> getEntriesEnumeration(File zipFile) throws ZipException, IOException { ZipFile zf = new ZipFile(zipFile); return zf.entries(); } /** * 取得压缩文件对象的注释 * * @param entry 压缩文件对象 * @return 压缩文件对象的注释 * @throws UnsupportedEncodingException */ public static String getEntryComment(ZipEntry entry) throws UnsupportedEncodingException { return new String(entry.getComment().getBytes("GB2312"), "8859_1"); } /** * 取得压缩文件对象的名称 * * @param entry 压缩文件对象 * @return 压缩文件对象的名称 * @throws UnsupportedEncodingException */ public static String getEntryName(ZipEntry entry) throws UnsupportedEncodingException { return new String(entry.getName().getBytes("GB2312"), "8859_1"); } /** * 压缩文件 * * @param resFile 需要压缩的文件(夹) * @param zipout 压缩的目的文件 * @param rootpath 压缩的文件路径 * @throws FileNotFoundException 找不到文件时抛出 * @throws IOException 当压缩过程出错时抛出 */ private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException { rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName(); rootpath = new String(rootpath.getBytes("8859_1"), "GB2312"); if (resFile.isDirectory()) { File[] fileList = resFile.listFiles(); for (File file : fileList) { zipFile(file, zipout, rootpath); } } else { byte buffer[] = new byte[BUFF_SIZE]; BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile), BUFF_SIZE); zipout.putNextEntry(new ZipEntry(rootpath)); int realLength; while ((realLength = in.read(buffer)) != -1) { zipout.write(buffer, 0, realLength); } in.close(); zipout.flush(); zipout.closeEntry(); } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/utils/BitmapUtil.java
src/com/droid/utils/BitmapUtil.java
package com.droid.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.util.Log; import android.util.LruCache; import com.droid.network.HttpClient; import com.example.android.bitmapfun.util.DiskLruCache; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.params.CoreConnectionPNames; import java.io.File; import java.net.URI; import java.net.URL; /** * 使用 内存硬盘 双重缓存 * * @author shenhui * */ public class BitmapUtil { private static final String TAG = "BitmapUtil"; private static Context mContext; private static BitmapUtil instance; private static LruCache<String, Bitmap> memoryCache; private static DiskLruCache mDiskCache; private static final long DISK_CACHE_SIZE = 1024 * 1024 * 80; // 80MB private static final int MEMORY_CACHE_SIZE = 1024 * 1024 * 20; // 20MB private static final String DISK_CACHE_SUBDIR = "diskCache"; private BitmapUtil(Context context) { mContext = context; // init memoryCache memoryCache = new LruCache<String, Bitmap>(MEMORY_CACHE_SIZE); // init DiskCache File cacheDir = new File(mContext.getCacheDir(), DISK_CACHE_SUBDIR); mDiskCache = DiskLruCache .openCache(mContext, cacheDir, DISK_CACHE_SIZE); } public static synchronized BitmapUtil getInstance(Context context) { if (null == instance) { instance = new BitmapUtil(context); } return instance; } /** * 得到指定大小的 bitmap * @param data * @param width * @param height * @return */ public Bitmap getBitmap(byte[] data, int width, int height) { Bitmap bitmap = null; Options opts = new Options(); opts.inJustDecodeBounds = true; opts.inSampleSize = calculateInSampleSize(opts, width, height); opts.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts); return bitmap; } /** * 计算缩放比例 * @param options * @param reqWidth * 目标宽 * @param reqHeight * 目标高 * @return */ private int calculateInSampleSize(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 (reqWidth == 0 || reqHeight == 0) { return inSampleSize; } if (height > reqHeight || width > reqWidth) { if (width > height) { inSampleSize = Math.round((float) height / (float) reqHeight); } else { inSampleSize = Math.round((float) width / (float) reqWidth); } } Log.d("", "原图尺寸:" + width + "x" + height + ",实际尺寸:" + reqWidth + "x" + reqHeight + ",inSampleSize = " + inSampleSize); return inSampleSize; } /** * 直接从网络 获取 图片 不缓存 * todo : 还未测试 * @param url * @return * @throws org.apache.http.conn.ConnectTimeoutException * @throws java.io.IOException */ public static Bitmap getBitmap(String url) { Bitmap bitmap = null; // byte[] data = HttpUtils.getBinary(url, null, null); try { URL mUrl =new URL(url); byte[] data = HttpClient.connect(mUrl, HttpClient.HTTP_POST, null, 30000, 10000); if (data != null) { bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } }catch (Exception e){ e.printStackTrace(); } return bitmap; } /** * 该方法为静态方法,从网络下载图片,如果硬盘有数据 ,优先从硬盘缓存获取<br> * 并加入到内存缓存和 硬盘缓存<br> * 存在网络下载,只能运行在工作线程<br> * * @param context * @param url * @param isLurCache * 是否加入到内存缓存,后台更新的时候不需要加入到内存缓存 * @return */ public static Bitmap getBitmap(Context context, String url, boolean isLurCache) { Bitmap bitmap = null; getInstance(context); bitmap = instance.getBitmapFromDisk(url); if (bitmap != null) { Log.d(TAG, "sp:from disk bitmap" + bitmap); instance.addToCache(url, bitmap, isLurCache, true); return bitmap; } bitmap = instance.getBitmapFromNet(url, 0, 0); if (bitmap != null) { instance.addToCache(url, bitmap, isLurCache, true); } return bitmap; } public Bitmap getBitmapFromMemory(String url) { String key = MD5Util.getMD5String(url); Bitmap bitmap = memoryCache.get(key); return bitmap; } public Bitmap getBitmapFromDisk(String url) { if (url != null) { String key = MD5Util.getMD5String(url).substring(8, 17) + ".png"; // Log.d("info", "tvRcommendKey="+key); return mDiskCache.get(key); } else { return null; } } public Bitmap getBitmapFromNet(String url, int width, int height) { Bitmap bitmap = null; DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000); client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(5, false)); HttpGet get = new HttpGet(); int retryCount = 0; try { get.setURI(new URI(url)); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { bitmap = BitmapFactory.decodeStream(response.getEntity() .getContent()); } if (bitmap == null) { Log.e(TAG, "getBitmapFromNet 下载失败 " + retryCount + " 次, url = " + url); } } catch (Exception e) { } finally { get.abort(); client.getConnectionManager().shutdown(); } return bitmap; } public void addToCache(String url, Bitmap bitmap, boolean lruCache, boolean diskLruCache) { if (url == null || bitmap == null) { return; } String key = MD5Util.getMD5String(url); if (lruCache) { memoryCache.put(key, bitmap); } if (diskLruCache) { mDiskCache.put(key + ".png", bitmap); } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/ApplicationsStackLayout.java
src/com/droid/views/ApplicationsStackLayout.java
/* * Copyright (C) 2007 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 com.droid.views; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.TextView; import com.droid.R; import java.util.List; /** * The ApplicationsStackLayout is a specialized layout used for the purpose of the home screen * only. This layout stacks various icons in three distinct areas: the recents, the favorites * (or faves) and the button. * * This layout supports two different orientations: vertical and horizontal. When horizontal, * the areas are laid out this way: * * [RECENTS][FAVES][BUTTON] * * When vertical, the layout is the following: * * [RECENTS] * [FAVES] * [BUTTON] * * The layout operates from the "bottom up" (or from right to left.) This means that the button * area will first be laid out, then the faves area, then the recents. When there are too many * favorites, the recents area is not displayed. * * The following attributes can be set in XML: * * orientation: horizontal or vertical * marginLeft: the left margin of each element in the stack * marginTop: the top margin of each element in the stack * marginRight: the right margin of each element in the stack * marginBottom: the bottom margin of each element in the stack */ public class ApplicationsStackLayout extends ViewGroup implements View.OnClickListener { public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; private View mButton; private LayoutInflater mInflater; private int mFavoritesEnd; private int mFavoritesStart; private List<ApplicationInfo> mFavorites; private List<ApplicationInfo> mRecents; private int mOrientation = VERTICAL; private int mMarginLeft; private int mMarginTop; private int mMarginRight; private int mMarginBottom; private Rect mDrawRect = new Rect(); private Drawable mBackground; private int mIconSize; public ApplicationsStackLayout(Context context) { super(context); initLayout(); } public ApplicationsStackLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ApplicationsStackLayout); mOrientation = a.getInt(R.styleable.ApplicationsStackLayout_stackOrientation, VERTICAL); mMarginLeft = a.getDimensionPixelSize(R.styleable.ApplicationsStackLayout_marginLeft, 0); mMarginTop = a.getDimensionPixelSize(R.styleable.ApplicationsStackLayout_marginTop, 0); mMarginRight = a.getDimensionPixelSize(R.styleable.ApplicationsStackLayout_marginRight, 0); mMarginBottom = a.getDimensionPixelSize(R.styleable.ApplicationsStackLayout_marginBottom, 0); a.recycle(); mIconSize = 42; //(int) getResources().getDimension(android.R.dimen.app_icon_size); initLayout(); } private void initLayout() { mInflater = LayoutInflater.from(getContext()); mButton = mInflater.inflate(R.layout.all_applications_button, this, false); addView(mButton); mBackground = getBackground(); setBackgroundDrawable(null); setWillNotDraw(false); } /** * Return the current orientation, either VERTICAL (default) or HORIZONTAL. * * @return the stack orientation */ public int getOrientation() { return mOrientation; } @Override protected void onDraw(Canvas canvas) { final Drawable background = mBackground; final int right = getWidth(); final int bottom = getHeight(); // Draw behind recents if (mOrientation == VERTICAL) { mDrawRect.set(0, 0, right, mFavoritesStart); } else { mDrawRect.set(0, 0, mFavoritesStart, bottom); } background.setBounds(mDrawRect); background.draw(canvas); // Draw behind favorites if (mFavoritesStart > -1) { if (mOrientation == VERTICAL) { mDrawRect.set(0, mFavoritesStart, right, mFavoritesEnd); } else { mDrawRect.set(mFavoritesStart, 0, mFavoritesEnd, bottom); } background.setBounds(mDrawRect); background.draw(canvas); } super.onDraw(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int widthSize = MeasureSpec.getSize(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) { throw new IllegalStateException("ApplicationsStackLayout can only be used with " + "measure spec mode=EXACTLY"); } setMeasuredDimension(widthSize, heightSize); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { removeAllApplications(); LayoutParams layoutParams = mButton.getLayoutParams(); final int widthSpec = MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.EXACTLY); final int heightSpec = MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY); mButton.measure(widthSpec, heightSpec); if (mOrientation == VERTICAL) { layoutVertical(); } else { layoutHorizontal(); } } private void layoutVertical() { int childLeft = 0; int childTop = getHeight(); int childWidth = mButton.getMeasuredWidth(); int childHeight = mButton.getMeasuredHeight(); childTop -= childHeight + mMarginBottom; mButton.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); childTop -= mMarginTop; mFavoritesEnd = childTop - mMarginBottom; int oldChildTop = childTop; childTop = stackApplications(mFavorites, childLeft, childTop); if (childTop != oldChildTop) { mFavoritesStart = childTop + mMarginTop; } else { mFavoritesStart = -1; } stackApplications(mRecents, childLeft, childTop); } private void layoutHorizontal() { int childLeft = getWidth(); int childTop = 0; int childWidth = mButton.getMeasuredWidth(); int childHeight = mButton.getMeasuredHeight(); childLeft -= childWidth; mButton.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); childLeft -= mMarginLeft; mFavoritesEnd = childLeft - mMarginRight; int oldChildLeft = childLeft; childLeft = stackApplications(mFavorites, childLeft, childTop); if (childLeft != oldChildLeft) { mFavoritesStart = childLeft + mMarginLeft; } else { mFavoritesStart = -1; } stackApplications(mRecents, childLeft, childTop); } private int stackApplications(List<ApplicationInfo> applications, int childLeft, int childTop) { LayoutParams layoutParams; int widthSpec; int heightSpec; int childWidth; int childHeight; final boolean isVertical = mOrientation == VERTICAL; final int count = applications.size(); for (int i = count - 1; i >= 0; i--) { final ApplicationInfo info = applications.get(i); final View view = createApplicationIcon(mInflater, this, info); layoutParams = view.getLayoutParams(); widthSpec = MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.EXACTLY); heightSpec = MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY); view.measure(widthSpec, heightSpec); childWidth = view.getMeasuredWidth(); childHeight = view.getMeasuredHeight(); if (isVertical) { childTop -= childHeight + mMarginBottom; if (childTop < 0) { childTop += childHeight + mMarginBottom; break; } } else { childLeft -= childWidth + mMarginRight; if (childLeft < 0) { childLeft += childWidth + mMarginRight; break; } } addViewInLayout(view, -1, layoutParams); view.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); if (isVertical) { childTop -= mMarginTop; } else { childLeft -= mMarginLeft; } } return isVertical ? childTop : childLeft; } private void removeAllApplications() { final int count = getChildCount(); for (int i = count - 1; i >= 0; i--) { final View view = getChildAt(i); if (view != mButton) { removeViewAt(i); } } } private View createApplicationIcon(LayoutInflater inflater, ViewGroup group, ApplicationInfo info) { TextView textView = (TextView) inflater.inflate(R.layout.favorite, group, false); info.icon.setBounds(0, 0, mIconSize, mIconSize); textView.setCompoundDrawables(null, info.icon, null, null); textView.setText(info.title); textView.setTag(info.intent); textView.setOnClickListener(this); return textView; } /** * Sets the list of favorites. * * @param applications the applications to put in the favorites area */ public void setFavorites(List<ApplicationInfo> applications) { mFavorites = applications; requestLayout(); } /** * Sets the list of recents. * * @param applications the applications to put in the recents area */ public void setRecents(List<ApplicationInfo> applications) { mRecents = applications; requestLayout(); } public void onClick(View v) { getContext().startActivity((Intent) v.getTag()); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/GameTitleView.java
src/com/droid/views/GameTitleView.java
package com.droid.views; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Canvas; import android.graphics.Typeface; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Handler; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.droid.R; import com.droid.utils.NetWorkUtil; import java.util.Timer; public class GameTitleView extends RelativeLayout { private RelativeLayout layout; private View view; private Context context; private Typeface typeface; private static final String TAG = "TitleView"; private static final boolean d = false; private ImageView imgWeather; private TextView tvTime, tvDate; private Timer _timer; private ImageView imgNetWorkState; public GameTitleView(Context context) { super(context); this.context = context; if(!isInEditMode()) initTitleView(); } public GameTitleView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; if(!isInEditMode()) initTitleView(); } public void initTitleView() { view = LayoutInflater.from(context).inflate(R.layout.game_titleview, this, true); layout = (RelativeLayout) view.findViewById(R.id.home_title); tvTime = (TextView) view.findViewById(R.id.title_time_hour); tvDate = (TextView) view.findViewById(R.id.home_date); imgNetWorkState = (ImageView) view.findViewById(R.id.home_networkstate); typeface = Typeface.createFromAsset(context.getAssets(), "font/helvetica_neueltpro_thex.otf"); tvTime.setTypeface(typeface); tvDate.setTypeface(typeface); timeHandle.post(timeRun); imgNetWorkState = (ImageView) this.findViewById(R.id.home_networkstate); context.registerReceiver(this.mConnReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); context.registerReceiver(wifiChange, new IntentFilter( WifiManager.RSSI_CHANGED_ACTION)); } private Handler timeHandle = new Handler(); private Runnable timeRun = new Runnable() { public void run() { setTvTimeText(TitleViewUtil.getTime()); setTvDateDate(TitleViewUtil.getDate()); timeHandle.postDelayed(this, 1000); } }; public void setTvTimeText(String text) { tvTime.setText(text); } public void setTvDateDate(String text) { tvDate.setText(text); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } /** * wifi 信号强度 */ private BroadcastReceiver wifiChange = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { WifiManager wifiManager = (WifiManager) context .getSystemService(context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo.getBSSID() != null) { // wifi信号强度 int signalLevel = WifiManager.calculateSignalLevel( wifiInfo.getRssi(), 4); if (signalLevel == 0) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.wifi_1)); } else if (signalLevel == 1) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.wifi_2)); } else if (signalLevel == 2) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.wifi_3)); } else if (signalLevel == 3) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.networkstate_on)); } if (d) Toast.makeText(context, "wifi level" + signalLevel, Toast.LENGTH_SHORT).show(); } } }; /** * 网络状态 */ private BroadcastReceiver mConnReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { boolean noConnectivity = intent.getBooleanExtra( ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); String reason = intent .getStringExtra(ConnectivityManager.EXTRA_REASON); boolean isFailover = intent.getBooleanExtra( ConnectivityManager.EXTRA_IS_FAILOVER, false); NetworkInfo currentNetworkInfo = (NetworkInfo) intent .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); NetworkInfo otherNetworkInfo = (NetworkInfo) intent .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); if (currentNetworkInfo.isConnected() && currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { if (d) Toast.makeText(context, "Connected", Toast.LENGTH_LONG) .show(); imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.networkstate_on)); } else if (currentNetworkInfo.isConnected() && currentNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.networkstate_ethernet)); } else if (!currentNetworkInfo.isConnected()) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.networkstate_off)); } if (d) Toast.makeText( context, "currentNetworkInfo=>>" + NetWorkUtil.isNetWorkConnected(context), Toast.LENGTH_LONG).show(); } }; }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/FocusedRelativeLayout.java
src/com/droid/views/FocusedRelativeLayout.java
package com.droid.views; import java.util.HashMap; import java.util.Map; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.SoundEffectConstants; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.RelativeLayout; import android.widget.Scroller; /** * 色块高亮布局,但是有焦点问题存在,目前项目没有采用 * */ public class FocusedRelativeLayout extends RelativeLayout implements FocusedBasePositionManager.PositionInterface { public static final String TAG = "FocusedRelativeLayout"; public static final int HORIZONTAL_SINGEL = 1; public static final int HORIZONTAL_FULL = 2; private static final int SCROLL_DURATION = 100; private long KEY_INTERVEL = 20L; private long mKeyTime = 0L; public int mIndex = -1; private boolean mOutsieScroll = false; private boolean mInit = false; private HotScroller mScroller; private int mScreenWidth; private int mViewRight = 20; private int mViewLeft = 0; private int mStartX; private long mScrollTime = 0L; private int mHorizontalMode = -1; private FocusedBasePositionManager.FocusItemSelectedListener mOnItemSelectedListener = null; private FocusedLayoutPositionManager mPositionManager; private OnScrollListener mScrollerListener = null; private int mLastScrollState = 0; private Map<View, NodeInfo> mNodeMap = new HashMap(); boolean isKeyDown = false; public void setManualPadding(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { this.mPositionManager.setManualPadding(paramInt1, paramInt2, paramInt3, paramInt4); } public void setFrameRate(int paramInt) { this.mPositionManager.setFrameRate(paramInt); } public void setFrameRate(int paramInt1, int paramInt2) { this.mPositionManager.setFrameRate(paramInt1, paramInt2); } public void setScaleMode(int paramInt) { this.mPositionManager.setScaleMode(paramInt); } public void setScale(boolean paramBoolean) { this.mPositionManager.setScale(paramBoolean); } public void setFocusResId(int paramInt) { this.mPositionManager.setFocusResId(paramInt); } public void setFocusShadowResId(int paramInt) { this.mPositionManager.setFocusShadowResId(paramInt); } public void setItemScaleValue(float paramFloat1, float paramFloat2) { this.mPositionManager.setItemScaleValue(paramFloat1, paramFloat2); } public void setScrollerListener(OnScrollListener paramOnScrollListener) { this.mScrollerListener = paramOnScrollListener; } public void setOnItemSelectedListener(FocusedBasePositionManager.FocusItemSelectedListener paramFocusItemSelectedListener) { this.mOnItemSelectedListener = paramFocusItemSelectedListener; } private void performItemSelect(View paramView, boolean paramBoolean) { if (this.mOnItemSelectedListener != null) this.mOnItemSelectedListener.onItemSelected(paramView, -1, paramBoolean, this); } public void setOnItemClickListener(AdapterView.OnItemClickListener paramOnItemClickListener) { } public void setItemScaleFixedX(int paramInt) { this.mPositionManager.setItemScaleFixedX(paramInt); } public void setItemScaleFixedY(int paramInt) { this.mPositionManager.setItemScaleFixedY(paramInt); } public void setFocusMode(int paramInt) { this.mPositionManager.setFocusMode(paramInt); } public void setFocusViewId(int paramInt) { } public void setHorizontalMode(int paramInt) { this.mHorizontalMode = paramInt; } private void setInit(boolean paramBoolean) { synchronized (this) { this.mInit = paramBoolean; } } private boolean isInit() { synchronized (this) { return this.mInit; } } public void setViewRight(int paramInt) { this.mViewRight = paramInt; } public void setViewLeft(int paramInt) { this.mViewLeft = paramInt; } public void setOutsideSroll(boolean paramBoolean) { this.mScrollTime = System.currentTimeMillis(); this.mOutsieScroll = paramBoolean; } public FocusedRelativeLayout(Context paramContext) { super(paramContext); setChildrenDrawingOrderEnabled(true); this.mScroller = new HotScroller(paramContext, new DecelerateInterpolator()); this.mScreenWidth = paramContext.getResources().getDisplayMetrics().widthPixels; this.mPositionManager = new FocusedLayoutPositionManager(paramContext, this); } public FocusedRelativeLayout(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); setChildrenDrawingOrderEnabled(true); this.mScroller = new HotScroller(paramContext, new DecelerateInterpolator()); this.mScreenWidth = paramContext.getResources().getDisplayMetrics().widthPixels; this.mPositionManager = new FocusedLayoutPositionManager(paramContext, this); } public FocusedRelativeLayout(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); setChildrenDrawingOrderEnabled(true); this.mScroller = new HotScroller(paramContext, new DecelerateInterpolator()); this.mScreenWidth = paramContext.getResources().getDisplayMetrics().widthPixels; this.mPositionManager = new FocusedLayoutPositionManager(paramContext, this); } protected int getChildDrawingOrder(int paramInt1, int paramInt2) { int i = this.mIndex; if (i < 0) return paramInt2; if (paramInt2 < i) return paramInt2; if (paramInt2 >= i) return paramInt1 - 1 - paramInt2 + i; return paramInt2; } private synchronized void init() { if ((hasFocus()) && (!this.mOutsieScroll) && (!isInit())) { int[] arrayOfInt = new int[2]; int i = 65536; for (int j = 0; j < getChildCount(); j++) { View localView = getChildAt(j); if (!this.mNodeMap.containsKey(localView)) { NodeInfo localNodeInfo = new NodeInfo(); localNodeInfo.index = j; this.mNodeMap.put(localView, localNodeInfo); } localView.getLocationOnScreen(arrayOfInt); if (arrayOfInt[0] < i) i = arrayOfInt[0]; } this.mStartX = i; setInit(true); } } public void release() { this.mNodeMap.clear(); } public void dispatchDraw(Canvas paramCanvas) { super.dispatchDraw(paramCanvas); if (0 == getVisibility()) this.mPositionManager.drawFrame(paramCanvas); } protected void onFocusChanged(boolean paramBoolean, int paramInt, Rect paramRect) { synchronized (this) { this.mKeyTime = System.currentTimeMillis(); } this.mPositionManager.setFocus(paramBoolean); this.mPositionManager.setTransAnimation(true); this.mPositionManager.setNeedDraw(true); this.mPositionManager.setState(1); if (!paramBoolean) { this.mPositionManager.drawFrame(null); this.mPositionManager.setFocusDrawableVisible(false, true); invalidate(); } else { if (-1 == this.mIndex) { this.mIndex = 0; this.mPositionManager.setSelectedView(getSelectedView()); } View v = getSelectedView(); if ((v instanceof ScalePostionInterface)) { ScalePostionInterface localScalePostionInterface = (ScalePostionInterface) v; this.mPositionManager.setScaleCurrentView(localScalePostionInterface.getIfScale()); } this.mPositionManager.setLastSelectedView(null); invalidate(); } } public void getFocusedRect(Rect paramRect) { View localView = getSelectedView(); if (localView != null) { localView.getFocusedRect(paramRect); offsetDescendantRectToMyCoords(localView, paramRect); return; } super.getFocusedRect(paramRect); } public View getSelectedView() { int i = this.mIndex; View localView = getChildAt(i); return localView; } public boolean onKeyUp(int paramInt, KeyEvent paramKeyEvent) { if (((23 == paramInt)||(96 == paramInt)) && (this.isKeyDown) && (getSelectedView() != null)) getSelectedView().performClick(); this.isKeyDown = false; return super.onKeyUp(paramInt, paramKeyEvent); } public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) { if (paramKeyEvent.getRepeatCount() == 0) this.isKeyDown = true; synchronized (this) { if ((System.currentTimeMillis() - this.mKeyTime <= this.KEY_INTERVEL) || (this.mPositionManager.getState() == 1) || (System.currentTimeMillis() - this.mScrollTime < 100L) || (!this.mScroller.isFinished())) { return true; } this.mKeyTime = System.currentTimeMillis(); } if (!isInit()) { init(); return true; } View v = getSelectedView(); NodeInfo localNodeInfo1 = (NodeInfo)this.mNodeMap.get(v); View localView = null; int i; switch (paramInt) { case 21: if (localNodeInfo1.fromLeft != null) localView = localNodeInfo1.fromLeft; else localView = ((View)v).focusSearch(17); i = 17; break; case 22: if (localNodeInfo1.fromRight != null) localView = localNodeInfo1.fromRight; else localView = ((View)v).focusSearch(66); i = 66; break; case 20: if (localNodeInfo1.fromDown != null) localView = localNodeInfo1.fromDown; else localView = ((View)v).focusSearch(130); i = 130; break; case 19: if (localNodeInfo1.fromUp != null) localView = localNodeInfo1.fromUp; else localView = ((View)v).focusSearch(33); i = 33; break; default: return super.onKeyDown(paramInt, paramKeyEvent); } if ((localView != null) && (this.mNodeMap.containsKey(localView))) { NodeInfo localNodeInfo2 = (NodeInfo)this.mNodeMap.get(localView); this.mIndex = localNodeInfo2.index; if (v != null) { ((View)v).setSelected(false); performItemSelect((View)v, false); View.OnFocusChangeListener localObject2 = ((View)v).getOnFocusChangeListener(); if (localObject2 != null) ((View.OnFocusChangeListener)localObject2).onFocusChange((View)v, false); } Object localObject2 = getSelectedView(); localObject2 = getSelectedView(); if (localObject2 != null) { ((View)localObject2).setSelected(true); performItemSelect((View)localObject2, true); View.OnFocusChangeListener localOnFocusChangeListener = ((View)localObject2).getOnFocusChangeListener(); if (localOnFocusChangeListener != null) localOnFocusChangeListener.onFocusChange((View)localObject2, true); } switch (paramInt) { case 21: localNodeInfo2.fromRight = ((View)v); break; case 22: localNodeInfo2.fromLeft = ((View)v); break; case 20: localNodeInfo2.fromUp = ((View)v); break; case 19: localNodeInfo2.fromDown = ((View)v); } boolean bool = true; if ((localObject2 instanceof ScalePostionInterface)) { ScalePostionInterface localScalePostionInterface = (ScalePostionInterface)localObject2; bool = localScalePostionInterface.getIfScale(); } this.mPositionManager.setSelectedView(getSelectedView()); this.mPositionManager.computeScaleXY(); this.mPositionManager.setScaleCurrentView(bool); horizontalScroll(); this.mPositionManager.setTransAnimation(true); this.mPositionManager.setNeedDraw(true); this.mPositionManager.setState(1); invalidate(); } else { playSoundEffect(SoundEffectConstants.getContantForFocusDirection(i)); return super.onKeyDown(paramInt, paramKeyEvent); } playSoundEffect(SoundEffectConstants.getContantForFocusDirection(i)); return true; } private void horizontalScroll() { if (1 == this.mHorizontalMode) scrollSingel(); else if (2 == this.mHorizontalMode) scrollFull(); } void scrollFull() { int[] arrayOfInt = new int[2]; getSelectedView().getLocationOnScreen(arrayOfInt); int i = arrayOfInt[0]; int j = arrayOfInt[0] + getSelectedView().getWidth(); int k = getSelectedView().getWidth(); i = (int) (i + (1.0D - this.mPositionManager.getItemScaleXValue()) * k / 2.0D); j = (int) (i + k * this.mPositionManager.getItemScaleXValue()); getLocationOnScreen(arrayOfInt); int m; int n; if ((j - this.mScreenWidth > 3) && (!this.mOutsieScroll)) { m = i - this.mStartX - this.mViewLeft; if (m + this.mScroller.getFinalX() > arrayOfInt[0] + getWidth()) m = arrayOfInt[0] + getWidth() - this.mScroller.getFinalX(); n = m * 100 / 300; smoothScrollBy(m, n); return; } if ((this.mStartX - i > 3) && (!this.mOutsieScroll)) { m = j - this.mScreenWidth; if (this.mScroller.getCurrX() < Math.abs(m)) m = -this.mScroller.getCurrX(); n = -m * 100 / 300; smoothScrollBy(m, n); } } void scrollSingel() { int[] arrayOfInt = new int[2]; getSelectedView().getLocationOnScreen(arrayOfInt); int i = arrayOfInt[0]; int j = arrayOfInt[0] + getSelectedView().getWidth(); int k = getSelectedView().getWidth(); i = (int) (i + (1.0D - this.mPositionManager.getItemScaleXValue()) * k / 2.0D); j = (int) (i + k * this.mPositionManager.getItemScaleXValue()); int m; if ((j >= this.mScreenWidth) && (!this.mOutsieScroll)) { m = j - this.mScreenWidth + this.mViewRight; smoothScrollBy(m, 100); return; } getLocationOnScreen(arrayOfInt); if ((i < this.mStartX) && (!this.mOutsieScroll)) { m = i - this.mStartX; if (this.mScroller.getCurrX() > Math.abs(m)) smoothScrollBy(m, 100); else smoothScrollBy(-this.mScroller.getCurrX(), 100); } } private boolean containView(View paramView) { Rect localRect1 = new Rect(); Rect localRect2 = new Rect(); getGlobalVisibleRect(localRect1); paramView.getGlobalVisibleRect(localRect2); return (localRect1.left <= localRect2.left) && (localRect1.right >= localRect2.right) && (localRect1.top <= localRect2.top) && (localRect1.bottom >= localRect2.bottom); } public void smoothScrollTo(int paramInt1, int paramInt2) { int i = paramInt1 - this.mScroller.getFinalX(); smoothScrollBy(i, paramInt2); } public void smoothScrollBy(int paramInt1, int paramInt2) { this.mScroller.startScroll(this.mScroller.getFinalX(), this.mScroller.getFinalY(), paramInt1, this.mScroller.getFinalY(), paramInt2); reportScrollStateChange(2); invalidate(); } void reportScrollStateChange(int paramInt) { if ((paramInt != this.mLastScrollState) && (this.mScrollerListener != null)) { this.mLastScrollState = paramInt; this.mScrollerListener.onScrollStateChanged(this, paramInt); } } private boolean checkFocusPosition() { if ((null == this.mPositionManager.getCurrentRect()) || (!hasFocus())) return false; Rect localRect = this.mPositionManager.getDstRectAfterScale(true); return (Math.abs(localRect.left - this.mPositionManager.getCurrentRect().left) > 5) || (Math.abs(localRect.right - this.mPositionManager.getCurrentRect().right) > 5) || (Math.abs(localRect.top - this.mPositionManager.getCurrentRect().top) > 5) || (Math.abs(localRect.bottom - this.mPositionManager.getCurrentRect().bottom) > 5); } public void computeScroll() { if (this.mScroller.computeScrollOffset()) { scrollTo(this.mScroller.getCurrX(), this.mScroller.getCurrY()); } if (this.mScroller.isFinished()) reportScrollStateChange(0); super.computeScroll(); } public static abstract interface OnScrollListener { public static final int SCROLL_STATE_IDLE = 0; public static final int SCROLL_STATE_TOUCH_SCROLL = 1; public static final int SCROLL_STATE_FLING = 2; public abstract void onScrollStateChanged(ViewGroup paramViewGroup, int paramInt); public abstract void onScroll(ViewGroup paramViewGroup, int paramInt1, int paramInt2, int paramInt3); } class FocusedLayoutPositionManager extends FocusedBasePositionManager { public FocusedLayoutPositionManager(Context paramView, View arg3) { super(paramView, arg3); } public Rect getDstRectBeforeScale(boolean paramBoolean) { View localView = getSelectedView(); if (null == localView) return null; Rect localRect1 = new Rect(); Rect localRect2 = new Rect(); if ((localView instanceof FocusedRelativeLayout.ScalePostionInterface)) { FocusedRelativeLayout.ScalePostionInterface localScalePostionInterface = (FocusedRelativeLayout.ScalePostionInterface) localView; if (localScalePostionInterface.getIfScale()) localRect1 = localScalePostionInterface.getScaledRect(getItemScaleXValue(), getItemScaleYValue(), true); else localRect1 = localScalePostionInterface.getScaledRect(getItemScaleXValue(), getItemScaleYValue(), false); } else { localView.getGlobalVisibleRect(localRect1); int i = localRect1.right - localRect1.left; int j = localRect1.bottom - localRect1.top; if (!paramBoolean) { localRect1.left = ((int) (localRect1.left + (1.0D - getItemScaleXValue()) * i / 2.0D)); localRect1.top = ((int) (localRect1.top + (1.0D - getItemScaleYValue()) * j / 2.0D)); localRect1.right = ((int) (localRect1.left + i * getItemScaleXValue())); localRect1.bottom = ((int) (localRect1.top + j * getItemScaleYValue())); } } FocusedRelativeLayout.this.getGlobalVisibleRect(localRect2); localRect1.left -= localRect2.left; localRect1.right -= localRect2.left; localRect1.top -= localRect2.top; localRect1.bottom -= localRect2.top; localRect1.left += FocusedRelativeLayout.this.mScroller.getCurrX(); localRect1.right += FocusedRelativeLayout.this.mScroller.getCurrX(); localRect1.top -= getSelectedPaddingTop(); localRect1.left -= getSelectedPaddingLeft(); localRect1.right += getSelectedPaddingRight(); localRect1.bottom += getSelectedPaddingBottom(); localRect1.left += getManualPaddingLeft(); localRect1.right += getManualPaddingRight(); localRect1.top += getManualPaddingTop(); localRect1.bottom += getManualPaddingBottom(); return localRect1; } public Rect getDstRectAfterScale(boolean paramBoolean) { View localView = getSelectedView(); if (null == localView) return null; Rect localRect1 = new Rect(); Rect localRect2 = new Rect(); if ((localView instanceof FocusedRelativeLayout.ScalePostionInterface)) { FocusedRelativeLayout.ScalePostionInterface localScalePostionInterface = (FocusedRelativeLayout.ScalePostionInterface) localView; localRect1 = localScalePostionInterface.getScaledRect(getItemScaleXValue(), getItemScaleYValue(), false); } else { localView.getGlobalVisibleRect(localRect1); } FocusedRelativeLayout.this.getGlobalVisibleRect(localRect2); localRect1.left -= localRect2.left; localRect1.right -= localRect2.left; localRect1.top -= localRect2.top; localRect1.bottom -= localRect2.top; localRect1.left += FocusedRelativeLayout.this.mScroller.getCurrX(); localRect1.right += FocusedRelativeLayout.this.mScroller.getCurrX(); if ((paramBoolean) && (isLastFrame())) { localRect1.top -= getSelectedShadowPaddingTop(); localRect1.left -= getSelectedShadowPaddingLeft(); localRect1.right += getSelectedShadowPaddingRight(); localRect1.bottom += getSelectedShadowPaddingBottom(); } else { localRect1.top -= getSelectedPaddingTop(); localRect1.left -= getSelectedPaddingLeft(); localRect1.right += getSelectedPaddingRight(); localRect1.bottom += getSelectedPaddingBottom(); } localRect1.left += getManualPaddingLeft(); localRect1.right += getManualPaddingRight(); localRect1.top += getManualPaddingTop(); localRect1.bottom += getManualPaddingBottom(); return localRect1; } public void drawChild(Canvas paramCanvas) { } } class NodeInfo { public int index; public View fromLeft; public View fromRight; public View fromUp; public View fromDown; NodeInfo() { } } public static abstract interface ScalePostionInterface { public abstract Rect getScaledRect(float paramFloat1, float paramFloat2, boolean paramBoolean); public abstract boolean getIfScale(); } class HotScroller extends Scroller { public HotScroller(Context paramInterpolator, Interpolator paramBoolean, boolean arg4) { super(paramInterpolator, paramBoolean, arg4); } public HotScroller(Context paramInterpolator, Interpolator arg3) { super(paramInterpolator, arg3); } public HotScroller(Context arg2) { super(arg2); } public boolean computeScrollOffset() { boolean bool1 = isFinished(); boolean bool2 = FocusedRelativeLayout.this.checkFocusPosition(); if ((FocusedRelativeLayout.this.mOutsieScroll) || (!bool1) || (bool2)) FocusedRelativeLayout.this.invalidate(); FocusedRelativeLayout.this.init(); return super.computeScrollOffset(); } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/AdapterView.java
src/com/droid/views/AdapterView.java
package com.droid.views; import java.lang.reflect.Field; import android.annotation.SuppressLint; import android.content.Context; import android.database.DataSetObserver; import android.os.Parcelable; import android.os.SystemClock; import android.util.AttributeSet; import android.util.SparseArray; import android.view.ContextMenu; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.Adapter; @SuppressLint("WrongCall") abstract class AdapterView<T extends Adapter> extends android.widget.AdapterView<Adapter> { protected static final int TUI_TEXT_COLOR_GREY = -6710887; protected static final int TUI_TEXT_COLOR_WHITE = -1; protected static final int TUI_TEXT_SIZE_2 = 24; public static final int ITEM_VIEW_TYPE_IGNORE = -1; public static final int ITEM_VIEW_TYPE_HEADER_OR_FOOTER = -2; @ViewDebug.ExportedProperty(category = "scrolling") int mFirstPosition = 0; int mSpecificTop; int mSyncPosition; long mSyncRowId = -9223372036854775808L; long mSyncHeight; boolean mNeedSync = false; int mSyncMode; private int mLayoutHeight; static final int SYNC_SELECTED_POSITION = 0; static final int SYNC_FIRST_POSITION = 1; static final int SYNC_MAX_DURATION_MILLIS = 100; boolean mInLayout = false; AdapterView.OnItemSelectedListener mOnItemSelectedListener; AdapterView.OnItemClickListener mOnItemClickListener; AdapterView.OnItemLongClickListener mOnItemLongClickListener; boolean mDataChanged; @ViewDebug.ExportedProperty(category = "list") int mNextSelectedPosition = -1; long mNextSelectedRowId = -9223372036854775808L; @ViewDebug.ExportedProperty(category = "list") int mSelectedPosition = -1; long mSelectedRowId = -9223372036854775808L; private View mEmptyView; @ViewDebug.ExportedProperty(category = "list") int mItemCount; int mOldItemCount; public static final int INVALID_POSITION = -1; public static final long INVALID_ROW_ID = -9223372036854775808L; int mOldSelectedPosition = -1; long mOldSelectedRowId = -9223372036854775808L; private boolean mDesiredFocusableState; private boolean mDesiredFocusableInTouchModeState; private AdapterView<T>.SelectionNotifier mSelectionNotifier; boolean mBlockLayoutRequests = false; public AdapterView(Context paramContext) { super(paramContext); } public AdapterView(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); } public AdapterView(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); } public void setOnItemClickListener(AdapterView.OnItemClickListener paramOnItemClickListener) { this.mOnItemClickListener = paramOnItemClickListener; } public boolean performItemClick(View paramView, int paramInt, long paramLong) { if (this.mOnItemClickListener != null) { playSoundEffect(0); if (paramView != null) paramView.sendAccessibilityEvent(1); this.mOnItemClickListener.onItemClick(this, paramView, paramInt, paramLong); return true; } return false; } public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener paramOnItemLongClickListener) { if (!isLongClickable()) setLongClickable(true); this.mOnItemLongClickListener = paramOnItemLongClickListener; } public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener paramOnItemSelectedListener) { this.mOnItemSelectedListener = paramOnItemSelectedListener; } public abstract T getAdapter(); public void addView(View paramView) { throw new UnsupportedOperationException("addView(View) is not supported in AdapterView"); } public void addView(View paramView, int paramInt) { throw new UnsupportedOperationException("addView(View, int) is not supported in AdapterView"); } public void addView(View paramView, ViewGroup.LayoutParams paramLayoutParams) { throw new UnsupportedOperationException("addView(View, LayoutParams) is not supported in AdapterView"); } public void addView(View paramView, int paramInt, ViewGroup.LayoutParams paramLayoutParams) { throw new UnsupportedOperationException("addView(View, int, LayoutParams) is not supported in AdapterView"); } public void removeView(View paramView) { throw new UnsupportedOperationException("removeView(View) is not supported in AdapterView"); } public void removeViewAt(int paramInt) { throw new UnsupportedOperationException("removeViewAt(int) is not supported in AdapterView"); } public void removeAllViews() { throw new UnsupportedOperationException("removeAllViews() is not supported in AdapterView"); } protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { this.mLayoutHeight = getHeight(); } @ViewDebug.CapturedViewProperty public int getSelectedItemPosition() { return this.mNextSelectedPosition; } @ViewDebug.CapturedViewProperty public long getSelectedItemId() { return this.mNextSelectedRowId; } public abstract View getSelectedView(); public Object getSelectedItem() { Adapter localAdapter = getAdapter(); int i = getSelectedItemPosition(); if ((localAdapter != null) && (localAdapter.getCount() > 0) && (i >= 0)) return localAdapter.getItem(i); return null; } @ViewDebug.CapturedViewProperty public int getCount() { return this.mItemCount; } public int getPositionForView(View paramView) { Object localObject = paramView; try { View localView; while (!(localView = (View) ((View) localObject).getParent()).equals(this)) localObject = localView; } catch (ClassCastException localClassCastException) { return -1; } int i = getChildCount(); for (int j = 0; j < i; j++) if (getChildAt(j).equals(localObject)) return this.mFirstPosition + j; return -1; } public int getFirstVisiblePosition() { return this.mFirstPosition; } public int getLastVisiblePosition() { return this.mFirstPosition + getChildCount() - 1; } public abstract void setSelection(int paramInt); public void setEmptyView(View paramView) { this.mEmptyView = paramView; Adapter localAdapter = getAdapter(); boolean bool = (localAdapter == null) || (localAdapter.isEmpty()); updateEmptyStatus(bool); } public View getEmptyView() { return this.mEmptyView; } boolean isInFilterMode() { return false; } public void setFocusable(boolean paramBoolean) { Adapter localAdapter = getAdapter(); int i = (localAdapter == null) || (localAdapter.getCount() == 0) ? 1 : 0; this.mDesiredFocusableState = paramBoolean; if (!paramBoolean) this.mDesiredFocusableInTouchModeState = false; super.setFocusable((paramBoolean) && ((i == 0) || (isInFilterMode()))); } public void setFocusableInTouchMode(boolean paramBoolean) { Adapter localAdapter = getAdapter(); int i = (localAdapter == null) || (localAdapter.getCount() == 0) ? 1 : 0; this.mDesiredFocusableInTouchModeState = paramBoolean; if (paramBoolean) this.mDesiredFocusableState = true; super.setFocusableInTouchMode((paramBoolean) && ((i == 0) || (isInFilterMode()))); } void checkFocus() { Adapter localAdapter = getAdapter(); int i = (localAdapter == null) || (localAdapter.getCount() == 0) ? 1 : 0; int j = (i == 0) || (isInFilterMode()) ? 1 : 0; super.setFocusableInTouchMode((j != 0) && (this.mDesiredFocusableInTouchModeState)); super.setFocusable((j != 0) && (this.mDesiredFocusableState)); if (this.mEmptyView != null) updateEmptyStatus((localAdapter == null) || (localAdapter.isEmpty())); } private void updateEmptyStatus(boolean paramBoolean) { if (isInFilterMode()) paramBoolean = false; if (paramBoolean) { if (this.mEmptyView != null) { this.mEmptyView.setVisibility(0); setVisibility(8); } else { setVisibility(0); } if (this.mDataChanged) { onLayout(false, getLeft(), getTop(), getRight(), getBottom()); } } else { if (this.mEmptyView != null) this.mEmptyView.setVisibility(8); setVisibility(0); } } public Object getItemAtPosition(int paramInt) { Adapter localAdapter = getAdapter(); return (localAdapter == null) || (paramInt < 0) ? null : localAdapter.getItem(paramInt); } public long getItemIdAtPosition(int paramInt) { Adapter localAdapter = getAdapter(); return (localAdapter == null) || (paramInt < 0) ? -9223372036854775808L : localAdapter.getItemId(paramInt); } public void setOnClickListener(View.OnClickListener paramOnClickListener) { throw new RuntimeException("Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead"); } protected void dispatchSaveInstanceState(SparseArray<Parcelable> paramSparseArray) { dispatchFreezeSelfOnly(paramSparseArray); } protected void dispatchRestoreInstanceState(SparseArray<Parcelable> paramSparseArray) { dispatchThawSelfOnly(paramSparseArray); } protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeCallbacks(this.mSelectionNotifier); } void selectionChanged() { if (this.mOnItemSelectedListener != null) if ((this.mInLayout) || (this.mBlockLayoutRequests)) { if (this.mSelectionNotifier == null) this.mSelectionNotifier = new SelectionNotifier(); post(this.mSelectionNotifier); } else { fireOnSelected(); } if ((this.mSelectedPosition != -1) && (isShown()) && (!isInTouchMode())) sendAccessibilityEvent(4); } private void fireOnSelected() { if (this.mOnItemSelectedListener == null) return; int i = getSelectedItemPosition(); if ((i >= 0) && (i < getCount())) { View localView = getSelectedView(); this.mOnItemSelectedListener.onItemSelected(this, localView, i, getAdapter().getItemId(i)); } else { this.mOnItemSelectedListener.onNothingSelected(this); } } public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent paramAccessibilityEvent) { View localView = getSelectedView(); return (localView != null) && (localView.getVisibility() == 0) && (localView.dispatchPopulateAccessibilityEvent(paramAccessibilityEvent)); } public boolean onRequestSendAccessibilityEvent(View paramView, AccessibilityEvent paramAccessibilityEvent) { if (super.onRequestSendAccessibilityEvent(paramView, paramAccessibilityEvent)) { AccessibilityEvent localAccessibilityEvent = AccessibilityEvent.obtain(); onInitializeAccessibilityEvent(localAccessibilityEvent); paramView.dispatchPopulateAccessibilityEvent(localAccessibilityEvent); paramAccessibilityEvent.appendRecord(localAccessibilityEvent); return true; } return false; } public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo paramAccessibilityNodeInfo) { super.onInitializeAccessibilityNodeInfo(paramAccessibilityNodeInfo); paramAccessibilityNodeInfo.setScrollable(isScrollableForAccessibility()); View localView = getSelectedView(); if (localView != null) paramAccessibilityNodeInfo.setEnabled(localView.isEnabled()); } public void onInitializeAccessibilityEvent(AccessibilityEvent paramAccessibilityEvent) { super.onInitializeAccessibilityEvent(paramAccessibilityEvent); paramAccessibilityEvent.setScrollable(isScrollableForAccessibility()); View localView = getSelectedView(); if (localView != null) paramAccessibilityEvent.setEnabled(localView.isEnabled()); paramAccessibilityEvent.setCurrentItemIndex(getSelectedItemPosition()); paramAccessibilityEvent.setFromIndex(getFirstVisiblePosition()); paramAccessibilityEvent.setToIndex(getLastVisiblePosition()); paramAccessibilityEvent.setItemCount(getCount()); } private boolean isScrollableForAccessibility() { Adapter localAdapter = getAdapter(); if (localAdapter != null) { int i = localAdapter.getCount(); return (i > 0) && ((getFirstVisiblePosition() > 0) || (getLastVisiblePosition() < i - 1)); } return false; } protected boolean canAnimate() { return (super.canAnimate()) && (this.mItemCount > 0); } void handleDataChanged() { int i = this.mItemCount; int j = 0; if (i > 0) { int k; int m; if (this.mNeedSync) { this.mNeedSync = false; k = findSyncPosition(); if (k >= 0) { m = lookForSelectablePosition(k, true); if (m == k) { setNextSelectedPositionInt(k); j = 1; } } } if (j == 0) { k = getSelectedItemPosition(); if (k >= i) k = i - 1; if (k < 0) k = 0; m = lookForSelectablePosition(k, true); if (m < 0) m = lookForSelectablePosition(k, false); if (m >= 0) { setNextSelectedPositionInt(m); checkSelectionChanged(); j = 1; } } } if (j == 0) { this.mSelectedPosition = -1; this.mSelectedRowId = -9223372036854775808L; this.mNextSelectedPosition = -1; this.mNextSelectedRowId = -9223372036854775808L; this.mNeedSync = false; checkSelectionChanged(); } } void checkSelectionChanged() { if ((this.mSelectedPosition != this.mOldSelectedPosition) || (this.mSelectedRowId != this.mOldSelectedRowId)) { selectionChanged(); this.mOldSelectedPosition = this.mSelectedPosition; this.mOldSelectedRowId = this.mSelectedRowId; } } int findSyncPosition() { int i = this.mItemCount; if (i == 0) return -1; long l1 = this.mSyncRowId; int j = this.mSyncPosition; if (l1 == -9223372036854775808L) return -1; j = Math.max(0, j); j = Math.min(i - 1, j); long l2 = SystemClock.uptimeMillis() + 100L; int k = j; int m = j; int n = 0; Adapter localAdapter = getAdapter(); if (localAdapter == null) return -1; while (SystemClock.uptimeMillis() <= l2) { long l3 = localAdapter.getItemId(j); if (l3 == l1) return j; int i2 = m == i - 1 ? 1 : 0; int i1 = k == 0 ? 1 : 0; if ((i2 != 0) && (i1 != 0)) break; if ((i1 != 0) || ((n != 0) && (i2 == 0))) { m++; j = m; n = 0; } else if ((i2 != 0) || ((n == 0) && (i1 == 0))) { k--; j = k; n = 1; } } return -1; } int lookForSelectablePosition(int paramInt, boolean paramBoolean) { return paramInt; } void setSelectedPositionInt(int paramInt) { this.mSelectedPosition = paramInt; this.mSelectedRowId = getItemIdAtPosition(paramInt); } void setNextSelectedPositionInt(int paramInt) { this.mNextSelectedPosition = paramInt; this.mNextSelectedRowId = getItemIdAtPosition(paramInt); if ((this.mNeedSync) && (this.mSyncMode == 0) && (paramInt >= 0)) { this.mSyncPosition = paramInt; this.mSyncRowId = this.mNextSelectedRowId; } } void rememberSyncState() { if (getChildCount() > 0) { this.mNeedSync = true; this.mSyncHeight = this.mLayoutHeight; View localView; if (this.mSelectedPosition >= 0) { localView = getChildAt(this.mSelectedPosition - this.mFirstPosition); this.mSyncRowId = this.mNextSelectedRowId; this.mSyncPosition = this.mNextSelectedPosition; if (localView != null) this.mSpecificTop = localView.getTop(); this.mSyncMode = 0; } else { localView = getChildAt(0); Adapter localAdapter = getAdapter(); if ((this.mFirstPosition >= 0) && (this.mFirstPosition < localAdapter.getCount())) this.mSyncRowId = localAdapter.getItemId(this.mFirstPosition); else this.mSyncRowId = -1L; this.mSyncPosition = this.mFirstPosition; if (localView != null) this.mSpecificTop = localView.getTop(); this.mSyncMode = 1; } } } protected int getGroupFlags() { try { Class localClass = Class.forName("android.view.ViewGroup"); Field localField = localClass.getDeclaredField("mGroupFlags"); localField.setAccessible(true); return localField.getInt(this); } catch (SecurityException localSecurityException) { localSecurityException.printStackTrace(); } catch (NoSuchFieldException localNoSuchFieldException) { localNoSuchFieldException.printStackTrace(); } catch (IllegalArgumentException localIllegalArgumentException) { localIllegalArgumentException.printStackTrace(); } catch (IllegalAccessException localIllegalAccessException) { localIllegalAccessException.printStackTrace(); } catch (ClassNotFoundException localClassNotFoundException) { localClassNotFoundException.printStackTrace(); } return 0; } protected void setGroupFlags(int paramInt) { try { Class localClass = Class.forName("android.view.ViewGroup"); Field localField = localClass.getDeclaredField("mGroupFlags"); localField.setAccessible(true); localField.setInt(this, paramInt); } catch (SecurityException localSecurityException) { localSecurityException.printStackTrace(); } catch (NoSuchFieldException localNoSuchFieldException) { localNoSuchFieldException.printStackTrace(); } catch (IllegalArgumentException localIllegalArgumentException) { localIllegalArgumentException.printStackTrace(); } catch (IllegalAccessException localIllegalAccessException) { localIllegalAccessException.printStackTrace(); } catch (ClassNotFoundException localClassNotFoundException) { localClassNotFoundException.printStackTrace(); } } private class SelectionNotifier implements Runnable { private SelectionNotifier() { } public void run() { if (AdapterView.this.mDataChanged) { if (AdapterView.this.getAdapter() != null) AdapterView.this.post(this); } else AdapterView.this.fireOnSelected(); } } class AdapterDataSetObserver extends DataSetObserver { private Parcelable mInstanceState = null; AdapterDataSetObserver() { } public void onChanged() { AdapterView.this.mDataChanged = true; AdapterView.this.mOldItemCount = AdapterView.this.mItemCount; AdapterView.this.mItemCount = AdapterView.this.getAdapter().getCount(); if ((AdapterView.this.getAdapter().hasStableIds()) && (this.mInstanceState != null) && (AdapterView.this.mOldItemCount == 0) && (AdapterView.this.mItemCount > 0)) { AdapterView.this.onRestoreInstanceState(this.mInstanceState); this.mInstanceState = null; } else { AdapterView.this.rememberSyncState(); } AdapterView.this.checkFocus(); AdapterView.this.requestLayout(); } public void onInvalidated() { AdapterView.this.mDataChanged = true; if (AdapterView.this.getAdapter().hasStableIds()) this.mInstanceState = AdapterView.this.onSaveInstanceState(); AdapterView.this.mOldItemCount = AdapterView.this.mItemCount; AdapterView.this.mItemCount = 0; AdapterView.this.mSelectedPosition = -1; AdapterView.this.mSelectedRowId = -9223372036854775808L; AdapterView.this.mNextSelectedPosition = -1; AdapterView.this.mNextSelectedRowId = -9223372036854775808L; AdapterView.this.mNeedSync = false; AdapterView.this.checkFocus(); AdapterView.this.requestLayout(); } public void clearSavedState() { this.mInstanceState = null; } } public static class AdapterContextMenuInfo implements ContextMenu.ContextMenuInfo { public View targetView; public int position; public long id; public AdapterContextMenuInfo(View paramView, int paramInt, long paramLong) { this.targetView = paramView; this.position = paramInt; this.id = paramLong; } } } /* * Location: C:\Users\Administrator\Desktop\AliTvAppSdk.jar Qualified Name: * com.yunos.tv.app.widget.AdapterView JD-Core Version: 0.6.2 */
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/TitleView.java
src/com/droid/views/TitleView.java
package com.droid.views; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Canvas; import android.graphics.Typeface; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Handler; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.droid.R; import java.util.Timer; public class TitleView extends RelativeLayout { private RelativeLayout layout; private View view; private Context context; private Typeface typeface; private final String TAG = "TitleView"; private final boolean d = false; private ImageView imgWeather; private TextView tvTime, tvDate; private Timer timer; private ImageView imgNetWorkState; public TitleView(Context context) { super(context); this.context = context; if(!isInEditMode()) initTitleView(); } public TitleView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; if(!isInEditMode()) initTitleView(); } public void initTitleView() { view = LayoutInflater.from(context).inflate(R.layout.titleview, this, true); layout = (RelativeLayout) view.findViewById(R.id.home_title); tvTime = (TextView) view.findViewById(R.id.title_time_hour); tvDate = (TextView) view.findViewById(R.id.home_date); imgNetWorkState = (ImageView) view.findViewById(R.id.home_networkstate); typeface = Typeface.createFromAsset(context.getAssets(), "font/helvetica_neueltpro_thex.otf"); tvTime.setTypeface(typeface); tvDate.setTypeface(typeface); timeHandle.post(timeRun); imgNetWorkState = (ImageView) this.findViewById(R.id.home_networkstate); context.getApplicationContext().registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); context.getApplicationContext().registerReceiver(wifiChange, new IntentFilter(WifiManager.RSSI_CHANGED_ACTION)); } public void setTvTimeText(String text) { tvTime.setText(text); } public void setTvDateDate(String text) { tvDate.setText(text); } private Handler timeHandle = new Handler(); private Runnable timeRun = new Runnable() { public void run() { setTvTimeText(TitleViewUtil.getTime()); setTvDateDate(TitleViewUtil.getDate()); timeHandle.postDelayed(this, 1000); } }; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } private BroadcastReceiver wifiChange = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { WifiManager wifiManager = (WifiManager) context .getSystemService(context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo.getBSSID() != null) { // wifi信号强度 int signalLevel = WifiManager.calculateSignalLevel( wifiInfo.getRssi(), 4); if (signalLevel == 0) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.wifi_1)); } else if (signalLevel == 1) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.wifi_2)); } else if (signalLevel == 2) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.wifi_3)); } else if (signalLevel == 3) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.networkstate_on)); } if (d) Toast.makeText(context, "wifi level" + signalLevel, Toast.LENGTH_SHORT).show(); } } }; private BroadcastReceiver mConnReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { boolean noConnectivity = intent.getBooleanExtra( ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); String reason = intent .getStringExtra(ConnectivityManager.EXTRA_REASON); boolean isFailover = intent.getBooleanExtra( ConnectivityManager.EXTRA_IS_FAILOVER, false); NetworkInfo currentNetworkInfo = (NetworkInfo) intent .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); NetworkInfo otherNetworkInfo = (NetworkInfo) intent .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); if (currentNetworkInfo.isConnected() && currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { if (d) Toast.makeText(context, "Connected", Toast.LENGTH_LONG) .show(); imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.networkstate_on)); } else if (currentNetworkInfo.isConnected() && currentNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.networkstate_ethernet)); } else if (!currentNetworkInfo.isConnected()) { imgNetWorkState.setImageDrawable(context.getResources() .getDrawable(R.drawable.networkstate_off)); } if (d) Toast.makeText( context, "currentNetworkInfo.getType()=>>" + currentNetworkInfo.getType() + currentNetworkInfo.getTypeName(), Toast.LENGTH_LONG).show(); } }; }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/TitleViewUtil.java
src/com/droid/views/TitleViewUtil.java
package com.droid.views; import android.text.format.Time; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; public class TitleViewUtil { public static String getTime() { String date = getFormattedDate(); String sTime = date.substring(11, date.length() - 3); return sTime; } public static String getDate() { String date = getFormattedDate(); String sDate = date.substring(0, 11); return sDate; } private static String getFormattedDate() { Time time = new Time(); time.setToNow(); DateFormat.getDateInstance(); Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = df.format(c.getTime()); return formattedDate; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/MyViewPager.java
src/com/droid/views/MyViewPager.java
package com.droid.views; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; public class MyViewPager extends ViewPager { private static final String TAG = "WoDouViewPager"; private boolean d = true; private boolean isCanScroll = false; public MyViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } @Override public boolean onTouchEvent(MotionEvent ev) { return true; } @Override public void setOnFocusChangeListener(OnFocusChangeListener l) { super.setOnFocusChangeListener(l); if (d) Log.i(TAG, "============focused change ========"); } @Override public void setOnTouchListener(OnTouchListener l) { if (d) Log.i(TAG, "============on touch dispach ========"); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/WoDouViewPager.java
src/com/droid/views/WoDouViewPager.java
package com.droid.views; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; public class WoDouViewPager extends ViewPager { private static final String TAG = "WoDouViewPager"; private boolean d = true; private boolean isCanScroll = false; public WoDouViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } @Override public boolean onTouchEvent(MotionEvent ev) { return true; } @Override public void setOnFocusChangeListener(OnFocusChangeListener l) { super.setOnFocusChangeListener(l); if(d) Log.i(TAG, "============focused change ========"); } @Override public void setOnTouchListener(OnTouchListener l) { if(d) Log.i(TAG, "============on touch dispach ========"); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/Rotate3dAnimation.java
src/com/droid/views/Rotate3dAnimation.java
package com.droid.views; /** * Created by Droid on 2015/2/3. */ import android.graphics.Camera; import android.graphics.Matrix; import android.view.animation.Animation; import android.view.animation.Transformation; /** * An animation that rotates the view on the Y axis between two specified angles. * This animation also adds a translation on the Z axis (depth) to improve the effect. */ public class Rotate3dAnimation extends Animation { private final float mFromDegrees; private final float mToDegrees; private final float mCenterX; private final float mCenterY; private final float mDepthZ; private final boolean mReverse; private Camera mCamera; /** * Creates a new 3D rotation on the Y axis. The rotation is defined by its * start angle and its end angle. Both angles are in degrees. The rotation * is performed around a center point on the 2D space, definied by a pair * of X and Y coordinates, called centerX and centerY. When the animation * starts, a translation on the Z axis (depth) is performed. The length * of the translation can be specified, as well as whether the translation * should be reversed in time. * * @param fromDegrees the start angle of the 3D rotation * @param toDegrees the end angle of the 3D rotation * @param centerX the X center of the 3D rotation * @param centerY the Y center of the 3D rotation * @param reverse true if the translation should be reversed, false otherwise */ public Rotate3dAnimation(float fromDegrees, float toDegrees, float centerX, float centerY, float depthZ, boolean reverse) { mFromDegrees = fromDegrees; mToDegrees = toDegrees; mCenterX = centerX; mCenterY = centerY; mDepthZ = depthZ; mReverse = reverse; } @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(); if (mReverse) { camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime); } else { camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime)); } camera.rotateY(degrees); camera.getMatrix(matrix); camera.restore(); matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/NoSlipViewPager.java
src/com/droid/views/NoSlipViewPager.java
package com.droid.views; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; public class NoSlipViewPager extends ViewPager { private static final String TAG = "NoSlipViewPager"; private boolean d = true; public NoSlipViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } @Override public boolean onTouchEvent(MotionEvent ev) { return true; } @Override public void setOnFocusChangeListener(OnFocusChangeListener l) { super.setOnFocusChangeListener(l); if(d) Log.i(TAG, "============focused change ========"); } @Override public void setOnTouchListener(OnTouchListener l) { if(d) Log.i(TAG, "============on touch dispach ========"); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/FocusedBasePositionManager.java
src/com/droid/views/FocusedBasePositionManager.java
package com.droid.views; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.View; public abstract class FocusedBasePositionManager { public static final String TAG = "FocusedBasePositionManager"; private static final int DEFAULT_FRAME_RATE = 6; private static final int DEFAULT_FRAME = 1; public static final int FOCUS_SYNC_DRAW = 0; public static final int FOCUS_ASYNC_DRAW = 1; public static final int FOCUS_STATIC_DRAW = 2; public static final int STATE_IDLE = 0; public static final int STATE_DRAWING = 1; public static final int SCALED_FIXED_COEF = 1; public static final int SCALED_FIXED_X = 2; public static final int SCALED_FIXED_Y = 3; private boolean DEBUG = true; private int mCurrentFrame = DEFAULT_FRAME; private int mFrameRate = DEFAULT_FRAME_RATE; private int mFocusFrameRate = 2; private int mScaleFrameRate = 2; private float mScaleXValue = 1.0F; private float mScaleYValue = 1.0F; private int mScaledMode = SCALED_FIXED_X; private int mFixedScaledX = 30; private int mFixedScaledY = 30; private int mState = 0; private boolean mNeedDraw = false; private int mode = FOCUS_ASYNC_DRAW; private Rect mSelectedPaddingRect = new Rect(); private Rect mManualSelectedPaddingRect = new Rect(); protected Drawable mMySelectedDrawable = null; private Drawable mMySelectedDrawableShadow; private Rect mMySelectedPaddingRectShadow; private boolean mIsFirstFrame = true; private boolean mConstrantNotDraw = false; private boolean mIsLastFrame = false; private View mSelectedView; private View mLastSelectedView; private View mContainerView; private boolean mHasFocus = false; private boolean mTransAnimation = false; private Context mContext; private Rect mLastFocusRect; private Rect mFocusRect; private Rect mCurrentRect; private boolean mScaleCurrentView = true; private boolean mScaleLastView = true; private boolean mIsScale = true; public FocusedBasePositionManager(Context paramContext, View paramView) { this.mContext = paramContext; this.mContainerView = paramView; } public void drawFrame(Canvas paramCanvas) { if (FOCUS_SYNC_DRAW == this.mode) { drawSyncFrame(paramCanvas); } else if (FOCUS_ASYNC_DRAW == this.mode) { drawAsyncFrame(paramCanvas); } else if (FOCUS_STATIC_DRAW == this.mode) { drawStaticFrame(paramCanvas); } } public void setScaleMode(int paramInt) { this.mScaledMode = paramInt; } public void setScale(boolean paramBoolean) { this.mIsScale = paramBoolean; } public void setScaleCurrentView(boolean paramBoolean) { this.mScaleCurrentView = paramBoolean; } public void setScaleLastView(boolean paramBoolean) { this.mScaleLastView = paramBoolean; } public boolean isLastFrame() { return this.mIsLastFrame; } public void setContrantNotDraw(boolean paramBoolean) { this.mConstrantNotDraw = paramBoolean; } public boolean getContrantNotDraw() { return this.mConstrantNotDraw; } public void setFocusDrawableVisible(boolean paramBoolean1, boolean paramBoolean2) { this.mMySelectedDrawable.setVisible(paramBoolean1, paramBoolean2); } public void setFocusDrawableShadowVisible(boolean paramBoolean1, boolean paramBoolean2) { this.mMySelectedDrawableShadow.setVisible(paramBoolean1, paramBoolean2); } public void setLastSelectedView(View paramView) { this.mLastSelectedView = paramView; } public void setTransAnimation(boolean paramBoolean) { this.mTransAnimation = paramBoolean; } public void setNeedDraw(boolean paramBoolean) { this.mNeedDraw = paramBoolean; } public void setFocusResId(int paramInt) { this.mMySelectedDrawable = this.mContext.getResources().getDrawable(paramInt); this.mSelectedPaddingRect = new Rect(); this.mMySelectedDrawable.getPadding(this.mSelectedPaddingRect); } public void setFocusShadowResId(int paramInt) { this.mMySelectedDrawableShadow = this.mContext.getResources().getDrawable(paramInt); this.mMySelectedPaddingRectShadow = new Rect(); this.mMySelectedDrawableShadow.getPadding(this.mMySelectedPaddingRectShadow); } public void setItemScaleValue(float paramFloat1, float paramFloat2) { this.mScaleXValue = paramFloat1; this.mScaleYValue = paramFloat2; } public void setItemScaleFixedX(int paramInt) { this.mFixedScaledX = paramInt; } public void setItemScaleFixedY(int paramInt) { this.mFixedScaledY = paramInt; } public float getItemScaleXValue() { return this.mScaleXValue; } public float getItemScaleYValue() { return this.mScaleYValue; } public Rect getCurrentRect() { return this.mCurrentRect; } public void setState(int paramInt) { synchronized (this) { this.mState = paramInt; } } public int getState() { synchronized (this) { return this.mState; } } public void setManualPadding(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { this.mManualSelectedPaddingRect.left = paramInt1; this.mManualSelectedPaddingRect.right = paramInt3; this.mManualSelectedPaddingRect.top = paramInt2; this.mManualSelectedPaddingRect.bottom = paramInt4; } public int getManualPaddingLeft() { return this.mManualSelectedPaddingRect.left; } public int getManualPaddingRight() { return this.mManualSelectedPaddingRect.right; } public int getManualPaddingTop() { return this.mManualSelectedPaddingRect.top; } public int getManualPaddingBottom() { return this.mManualSelectedPaddingRect.bottom; } public int getSelectedPaddingLeft() { return this.mSelectedPaddingRect.left; } public int getSelectedPaddingRight() { return this.mSelectedPaddingRect.right; } public int getSelectedPaddingTop() { return this.mSelectedPaddingRect.top; } public int getSelectedPaddingBottom() { return this.mSelectedPaddingRect.bottom; } public int getSelectedShadowPaddingLeft() { return this.mMySelectedPaddingRectShadow.left; } public int getSelectedShadowPaddingRight() { return this.mMySelectedPaddingRectShadow.right; } public int getSelectedShadowPaddingTop() { return this.mMySelectedPaddingRectShadow.top; } public int getSelectedShadowPaddingBottom() { return this.mMySelectedPaddingRectShadow.bottom; } public void setFocus(boolean paramBoolean) { this.mHasFocus = paramBoolean; } public boolean hasFocus() { return this.mHasFocus; } public void setFocusMode(int paramInt) { this.mode = paramInt; } public void setFrameRate(int paramInt) { this.mFrameRate = paramInt; if (paramInt % 2 == 0) { this.mScaleFrameRate = (paramInt / 2); this.mFocusFrameRate = (paramInt / 2); } else { this.mScaleFrameRate = (paramInt / 2); this.mFocusFrameRate = (paramInt / 2 + 1); } } public void setFrameRate(int paramInt1, int paramInt2) { this.mFrameRate = (paramInt1 + paramInt2); this.mScaleFrameRate = paramInt1; this.mFocusFrameRate = paramInt2; } public void setSelectedView(View paramView) { this.mSelectedView = paramView; } public View getSelectedView() { return this.mSelectedView; } private void drawSyncFrame(Canvas paramCanvas) { if (getSelectedView() != null) { if ((this.mCurrentFrame < this.mFrameRate) && (this.mNeedDraw)) { if (this.mIsFirstFrame) { drawFirstFrame(paramCanvas, true, true); } else { drawOtherFrame(paramCanvas, true, true); } } else if ((this.mCurrentFrame == this.mFrameRate) && (this.mNeedDraw)) { drawLastFrame(paramCanvas, true, true); } else if (hasFocus()) { Rect localRect = getDstRectBeforeScale(true); if (localRect != null) { this.mLastFocusRect = localRect; drawFocus(paramCanvas, false); } } } else { } } private void drawAsyncFrame(Canvas paramCanvas) { if (getSelectedView() != null) { boolean bool = this.mCurrentFrame > this.mFocusFrameRate; if ((this.mCurrentFrame < this.mFrameRate) && (this.mNeedDraw)) { if (this.mIsFirstFrame) { drawFirstFrame(paramCanvas, bool, !bool); } else { drawOtherFrame(paramCanvas, bool, !bool); } } else if (this.mCurrentFrame == this.mFrameRate) { drawLastFrame(paramCanvas, bool, !bool); } else if (!this.mConstrantNotDraw) { if (hasFocus()) { Rect localRect = getDstRectBeforeScale(true); if (localRect != null) { this.mLastFocusRect = localRect; drawFocus(paramCanvas, false); } } return; } } else { } } private void drawStaticFrame(Canvas paramCanvas) { if (getSelectedView() != null) { if ((this.mCurrentFrame < this.mFrameRate) && (this.mNeedDraw)) { if (this.mIsFirstFrame) { drawFirstFrame(paramCanvas, true, false); } else { drawOtherFrame(paramCanvas, true, false); } } else if ((this.mCurrentFrame == this.mFrameRate) && (this.mNeedDraw)) { drawLastFrame(paramCanvas, true, false); } else if (!this.mConstrantNotDraw) { if (hasFocus()) { Rect localRect = getDstRectBeforeScale(true); if (localRect != null) { this.mLastFocusRect = localRect; drawFocus(paramCanvas, false); } } } } else { } } private void drawFirstFrame(Canvas paramCanvas, boolean paramBoolean1, boolean paramBoolean2) { boolean bool = paramBoolean2; if (FOCUS_ASYNC_DRAW == this.mode) { bool = false; } this.mIsLastFrame = false; Rect localRect; if (bool) { localRect = getDstRectBeforeScale(!bool); if (null == localRect) { return; } this.mFocusRect = localRect; } else { localRect = getDstRectAfterScale(!bool); if (null == localRect) { return; } this.mFocusRect = localRect; } this.mCurrentRect = this.mFocusRect; drawScale(paramBoolean1); if (hasFocus()) { drawFocus(paramCanvas, paramBoolean2); } this.mIsFirstFrame = false; this.mCurrentFrame += 1; this.mContainerView.invalidate(); } private void drawOtherFrame(Canvas paramCanvas, boolean paramBoolean1, boolean paramBoolean2) { this.mIsLastFrame = false; drawScale(paramBoolean1); if (hasFocus()) { drawFocus(paramCanvas, paramBoolean2); } this.mCurrentFrame += 1; this.mContainerView.invalidate(); } private void drawLastFrame(Canvas paramCanvas, boolean paramBoolean1, boolean paramBoolean2) { Rect localRect = getDstRectBeforeScale(true); if (null == localRect) { return; } this.mIsLastFrame = true; drawScale(paramBoolean1); if (hasFocus()) { drawFocus(paramCanvas, paramBoolean2); } this.mCurrentFrame = 1; this.mScaleLastView = this.mScaleCurrentView; this.mLastSelectedView = getSelectedView(); this.mNeedDraw = false; this.mIsFirstFrame = true; this.mLastFocusRect = localRect; setState(STATE_IDLE); } private void scaleSelectedView() { View localView = getSelectedView(); if (localView != null) { float f1 = this.mScaleXValue - 1.0F; float f2 = this.mScaleYValue - 1.0F; int i = this.mFrameRate; int j = this.mCurrentFrame; if (1 == this.mode) { i = this.mScaleFrameRate; j -= this.mFocusFrameRate; if (j <= 0) { return; } } float f3 = 1.0F + f1 * j / i; float f4 = 1.0F + f2 * j / i; localView.setScaleX(f3); localView.setScaleY(f4); } } private void scaleLastSelectedView() { if (this.mLastSelectedView != null) { float f1 = this.mScaleXValue - 1.0F; float f2 = this.mScaleYValue - 1.0F; int i = this.mFrameRate; int j = this.mCurrentFrame; if (1 == this.mode) { i = this.mScaleFrameRate; if (j > i) { return; } } j = i - j; float f3 = 1.0F + f1 * j / i; float f4 = 1.0F + f2 * j / i; this.mLastSelectedView.setScaleX(f3); this.mLastSelectedView.setScaleY(f4); } } private void drawScale(boolean paramBoolean) { if ((hasFocus()) && (paramBoolean) && (this.mScaleCurrentView) && (this.mIsScale)) { scaleSelectedView(); } if ((this.mScaleLastView) && (this.mIsScale)) { scaleLastSelectedView(); } } private void drawFocus(Canvas paramCanvas, boolean paramBoolean) { if (this.mConstrantNotDraw) { return; } if ((paramBoolean) && (this.mTransAnimation) && (this.mLastFocusRect != null) && (getState() != 0) && (!isLastFrame())) { drawDynamicFocus(paramCanvas); } else { drawStaticFocus(paramCanvas); } } private void drawStaticFocus(Canvas paramCanvas) { float f1 = this.mScaleXValue - 1.0F; float f2 = this.mScaleYValue - 1.0F; int i = this.mFrameRate; int j = this.mCurrentFrame; float f3 = 1.0F + f1 * j / i; float f4 = 1.0F + f2 * j / i; Rect localRect = getDstRectAfterScale(true); if (null == localRect) { return; } this.mFocusRect = localRect; this.mCurrentRect = localRect; if (isLastFrame()) { this.mMySelectedDrawableShadow.setBounds(localRect); this.mMySelectedDrawableShadow.draw(paramCanvas); this.mMySelectedDrawableShadow.setVisible(true, true); } else { this.mMySelectedDrawable.setBounds(localRect); this.mMySelectedDrawable.draw(paramCanvas); this.mMySelectedDrawable.setVisible(true, true); } if ((this.mSelectedView != null) && (paramCanvas != null) && ((this.mState == 0) || (isLastFrame()))) { drawChild(paramCanvas); } } private void drawDynamicFocus(Canvas paramCanvas) { Rect localRect = new Rect(); int i = this.mFrameRate; if (FOCUS_ASYNC_DRAW == this.mode) { i = this.mFocusFrameRate; } int j = this.mFocusRect.left - this.mLastFocusRect.left; int k = this.mFocusRect.right - this.mLastFocusRect.right; int m = this.mFocusRect.top - this.mLastFocusRect.top; int n = this.mFocusRect.bottom - this.mLastFocusRect.bottom; localRect.left = (this.mLastFocusRect.left + j * this.mCurrentFrame / i); localRect.right = (this.mLastFocusRect.right + k * this.mCurrentFrame / i); localRect.top = (this.mLastFocusRect.top + m * this.mCurrentFrame / i); localRect.bottom = (this.mLastFocusRect.bottom + n * this.mCurrentFrame / i); this.mCurrentRect = localRect; this.mMySelectedDrawable.setBounds(localRect); this.mMySelectedDrawable.draw(paramCanvas); this.mMySelectedDrawable.setVisible(true, true); if ((this.mSelectedView != null) && (paramCanvas != null) && ((this.mState == 0) || (isLastFrame()))) { drawChild(paramCanvas); } } public void computeScaleXY() { if ((SCALED_FIXED_X == this.mScaledMode) || (SCALED_FIXED_Y == this.mScaledMode)) { View localView = getSelectedView(); int[] arrayOfInt = new int[2]; localView.getLocationOnScreen(arrayOfInt); int i = localView.getWidth(); int j = localView.getHeight(); if (SCALED_FIXED_X == this.mScaledMode) { this.mScaleXValue = ((i + this.mFixedScaledX) / i); this.mScaleYValue = this.mScaleXValue; } else if (SCALED_FIXED_Y == this.mScaledMode) { this.mScaleXValue = ((j + this.mFixedScaledY) / j); this.mScaleYValue = this.mScaleXValue; } } } public abstract Rect getDstRectBeforeScale(boolean paramBoolean); public abstract Rect getDstRectAfterScale(boolean paramBoolean); public abstract void drawChild(Canvas paramCanvas); public static abstract interface FocusItemSelectedListener { public abstract void onItemSelected(View paramView1, int paramInt, boolean paramBoolean, View paramView2); } public static abstract interface PositionInterface { public abstract void setManualPadding(int paramInt1, int paramInt2, int paramInt3, int paramInt4); public abstract void setFrameRate(int paramInt); public abstract void setFocusResId(int paramInt); public abstract void setFocusShadowResId(int paramInt); public abstract void setItemScaleValue(float paramFloat1, float paramFloat2); public abstract void setFocusMode(int paramInt); public abstract void setFocusViewId(int paramInt); public abstract void setOnItemClickListener(AdapterView.OnItemClickListener paramOnItemClickListener); public abstract void setOnItemSelectedListener(FocusedBasePositionManager.FocusItemSelectedListener paramFocusItemSelectedListener); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/views/ApplicationInfo.java
src/com/droid/views/ApplicationInfo.java
/* * Copyright (C) 2007 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 com.droid.views; import android.content.ComponentName; import android.content.Intent; import android.graphics.drawable.Drawable; /** * Represents a launchable application. An application is made of a name (or title), an intent * and an icon. */ class ApplicationInfo { /** * The application name. */ CharSequence title; /** * The intent used to start the application. */ Intent intent; /** * The application icon. */ Drawable icon; /** * When set to true, indicates that the icon has been resized. */ boolean filtered; /** * Creates the application intent based on a component name and various launch flags. * * @param className the class name of the component representing the intent * @param launchFlags the launch flags */ final void setActivity(ComponentName className, int launchFlags) { intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setComponent(className); intent.setFlags(launchFlags); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ApplicationInfo)) { return false; } ApplicationInfo that = (ApplicationInfo) o; return title.equals(that.title) && intent.getComponent().getClassName().equals( that.intent.getComponent().getClassName()); } @Override public int hashCode() { int result; result = (title != null ? title.hashCode() : 0); final String name = intent.getComponent().getClassName(); result = 31 * result + (name != null ? name.hashCode() : 0); return result; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/bean/AppItem.java
src/com/droid/bean/AppItem.java
package com.droid.bean; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class AppItem { public RelativeLayout layout; public ImageView imageView1,imageView2,imageView3; public TextView textView; public String packageName = null; }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/bean/AppBean.java
src/com/droid/bean/AppBean.java
package com.droid.bean; import android.graphics.drawable.Drawable; public class AppBean { private String dataDir; private Drawable icon; private String id; private String name; private String launcherName; private String packageName; private int pageIndex; private int position; private boolean sysApp = false; public String getDataDir() { return this.dataDir; } public Drawable getIcon() { return this.icon; } public String getId() { return this.id; } public String getName() { return this.name; } public String getPackageName() { return this.packageName; } public int getPageIndex() { return this.pageIndex; } public int getPosition() { return this.position; } public void setDataDir(String paramString) { this.dataDir = paramString; } public void setIcon(Drawable paramDrawable) { this.icon = paramDrawable; } public void setId(String paramString) { this.id = paramString; } public void setName(String paramString) { this.name = paramString; } public void setPackageName(String paramString) { this.packageName = paramString; } public void setPageIndex(int paramInt) { this.pageIndex = paramInt; } public void setPosition(int paramInt) { this.position = paramInt; } public String toString() { return "AppBean [packageName=" + this.packageName + ", name=" + this.name + ", dataDir=" + this.dataDir + "]"; } public boolean isSysApp() { return sysApp; } public void setSysApp(boolean sysApp) { this.sysApp = sysApp; } public String getLauncherName() { return launcherName; } public void setLauncherName(String launcherName) { this.launcherName = launcherName; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/network/RequestParam.java
src/com/droid/network/RequestParam.java
package com.droid.network; import android.util.Log; import com.droid.application.ClientApplication; import org.json.JSONArray; import org.json.JSONObject; /** * 请求服务器的参数 */ public class RequestParam { public static final String USER_NAME = "userName";// 其实是手机号 public static final String PASSWORD = "password"; public static final String RANDOM_KEY = "randomKey"; public static final String REQUEST_TYPE = "requestType"; public static final String PARAMS = "params"; public static final String LOCATION_INFO = "locationInfo"; public static final String MAC_ADDRESS = "macAddress"; public static final String SEX = "sex"; public static final String ADDR = "addr"; public static final String NAME = "name"; public static final String PHOTO = "photo"; public static final String USER_PHONE = "userPhone"; public static final String DEVICE_ID = "deviceID"; public static final String UNIQUE_ID = "uniqueID"; public static final String STATUS = "loginStatus"; public static final int ONLINE = 0; public static final int OFFLINE = 1; public static final int SEND_TOPIC = 111; /** * 登录 */ public final String LOGIN = "Login"; /** * 注销 */ public static final String LOGOUT = "Logout"; /** * 定时访问服务器 */ public static final String UPDATE_INFO = "update_info"; /** * 获取用户资料 */ public static final String GET_PERSONINFO = "GetPersonInfo"; /** * 获取应用商城所有应用 */ public static final String GET_APPSTORE_APPS = "GetAllAppstoreApps"; /** * 终端认证 */ public static final String TERMINAL_AUTHENTICATION = "TerminalAuthentication"; /** *终端激活 */ public static final String REGISTER = "Register"; public static final String UPDATE_UI="UpdateUI"; /** * 注册 */ public static final String SIGNIN = "Signin"; /** * 检查更新 apk 升级 */ // public static final String UPDATE = "SoftWareUpdate"; public static final String UPDATE = "CheckAppUpdate"; /** * 登录名 */ private String userName; /** * 密码 */ private String password; /** * 随机字符串 */ private String randomKey; /** * 请求类型 */ private String requestType; /** * mac 地址 */ private String macAddress; /** * 地理位置信息 */ private String locationInfo; /** * 请求参数 */ private Object params[]; /** * 设备ID */ private String deviceID; /** * 电话 */ private String userPhone; /** * unique id */ private String uniqueID; private static final boolean d = ClientApplication.debug; public String getDeviceID() { return deviceID; } public void setDeviceID(String deviceID) { this.deviceID = deviceID; } public String getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } public String getUniqueID() { return uniqueID; } public void setUniqueID(String uniqueID) { this.uniqueID = uniqueID; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public String getLocationInfo() { return locationInfo; } public void setLocationInfo(String locationInfo) { this.locationInfo = locationInfo; } public void setUserName(String userName) { this.userName = userName; } public void setPassword(String password) { this.password = password; } public void setRandomKey(String randomKey) { this.randomKey = randomKey; } public void setParams(Object[] params) { this.params = params; } public void setRequestType(String requestType) { this.requestType = requestType; } public String getUserName() { return userName; } public String getPassword() { return password; } public String getRandomKey() { return randomKey; } public String getRequestType() { return requestType; } public String getJSON() { JSONObject object = new JSONObject(); try { object.put(RequestParam.USER_NAME, this.userName); object.put(RequestParam.PASSWORD, this.password); object.put(RequestParam.RANDOM_KEY, this.randomKey); object.put(RequestParam.REQUEST_TYPE, this.requestType); object.put(RequestParam.DEVICE_ID, this.deviceID); object.put(RequestParam.USER_PHONE, this.userPhone); object.put(RequestParam.UNIQUE_ID, this.uniqueID); object.put(RequestParam.LOCATION_INFO, this.locationInfo); object.put(RequestParam.MAC_ADDRESS, this.macAddress); JSONArray jsonArray = new JSONArray(); for (Object param : params) { jsonArray.put(param); } object.put(RequestParam.PARAMS, jsonArray); if (d) System.out.println("请求参数" + object.toString()); return object.toString(); } catch (Exception e) { Log.e("RequestParam", "构建发送请求参数出错", e); return ""; } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/network/HttpClient.java
src/com/droid/network/HttpClient.java
package com.droid.network; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import com.droid.application.ClientApplication; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; public class HttpClient { public static final String HTTP_POST = "POST"; public static final String HTTP_GET = "GET"; private static final boolean d = ClientApplication.debug; /** * 访问服务器,向服务器发送http请求。 * @param url 服务器路径 * @param method 访问方法 * @param postParam post的参数 * @param connectTimeout 连接超时时间,单位毫秒 * @param readTimeout 读取内容超时时间,单位毫秒 * @ param proxy 代理地址 * @ param property 连接的属性 * @return 读取到的字节数组 * @throws NullPointerException 传入参数为空 * @throws IOException * @throws ProtocolException */ public static byte[] connect( URL url, String method, String postParam, int connectTimeout, int readTimeout) throws NullPointerException, IOException, ProtocolException { //创建连接 HttpURLConnection connection = null; connection = (HttpURLConnection) url.openConnection(); //设置属性 connection.setConnectTimeout( connectTimeout ); connection.setReadTimeout( readTimeout ); connection.setDoInput( true ); connection.setDoOutput( true ); connection.setRequestMethod( method ); connection.setRequestProperty( "Accept-Charset", "utf-8" ); //如果是post方式传参,则处理 if( method == HttpClient.HTTP_POST && postParam != null ) { BufferedOutputStream out = new BufferedOutputStream( connection.getOutputStream(), 8192 ); if(d)System.out.println( "post参数:" + postParam ); out.write( postParam.getBytes( "utf-8" ) ); out.flush(); out.close(); } ByteArrayOutputStream outStream = new ByteArrayOutputStream(); int result = connection.getResponseCode(); if(d)System.out.println( result ); //判断是否连接成功 if ( result == 200 ) { //如果连接成功则读取内容 BufferedInputStream inStream = new BufferedInputStream( connection.getInputStream(), 8192 ); byte[] buffer = new byte[1024]; int len = -1; while( ( len = inStream.read( buffer ) ) != -1 ) { outStream.write(buffer, 0, len); } inStream.close(); } outStream.close(); connection.disconnect(); return outStream.toByteArray(); } /** * 判断网络是否连接 * @param context * @return - true 网络连接 * - false 网络连接异常 */ public static boolean isConnect( Context context ) { try { ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE ); if( connectivity != null ) { NetworkInfo info = connectivity.getActiveNetworkInfo(); if( info != null && info.isConnected() && info.isAvailable() ) { if( info.getState() == NetworkInfo.State.CONNECTED ) { return true; } } } } catch ( Exception e ) { Log.v( "error", e.toString() ); } return false; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/network/HttpResult.java
src/com/droid/network/HttpResult.java
package com.droid.network; import android.text.TextUtils; import android.util.Log; import com.droid.application.ClientApplication; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.cookie.Cookie; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Arrays; public class HttpResult { private static final String TAG = "HttpResult"; private static final boolean d = ClientApplication.debug; private Cookie[] cookies; // cookie private Header[] headers; private byte[] response; private int statuCode = -1; public Cookie[] getCookies() { return cookies; } public Header[] getHeaders() { return headers; } public Header getHeader(String name) { if (this.headers == null || this.headers.length == 0) { return null; } for (int i = 0; i < headers.length; i++) { if (headers[i].getName().equalsIgnoreCase(name)) { return headers[i]; } } return null; } public String getHtml() { //内存溢出 try { return getText(HTTP.UTF_8); } catch (Exception e) { e.printStackTrace(); } return null; } public String getHtml(String encoding) { return getText(encoding); } public byte[] getResponse() { if (this.response == null) { return null; } return Arrays.copyOf(this.response, this.response.length); } public int getStatuCode() { return this.statuCode; } public String getText(String encoding) { if (this.response == null) { return null; } if (TextUtils.isEmpty(encoding)) { encoding = "utf-8"; } try { return new String(this.response, encoding); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } return null; } public HttpResult(HttpResponse httpResponse) { new HttpResult(httpResponse, null); } public Cookie getCookie(String name) { if (cookies == null || cookies.length == 0) { return null; } for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equalsIgnoreCase(name)) { return cookie; } } return null; } public HttpResult(HttpResponse httpResponse, CookieStore cookieStore) { if (cookieStore != null) { this.cookies = cookieStore.getCookies().toArray(new Cookie[0]); } if (httpResponse != null) { this.headers = httpResponse.getAllHeaders(); this.statuCode = httpResponse.getStatusLine().getStatusCode(); if(d)System.out.println(this.statuCode); try { this.response = EntityUtils.toByteArray(httpResponse .getEntity()); } catch (IOException e) { e.printStackTrace(); } } } @Override public String toString() { return "HttpResult [cookies=" + Arrays.toString(cookies) + ", headers=" + Arrays.toString(headers) + ", response=" + getText("utf-8") + ", statuCode=" + statuCode + "]"; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/network/ResponseParam.java
src/com/droid/network/ResponseParam.java
package com.droid.network; import org.json.JSONException; import org.json.JSONObject; /** * 解析返回参数 * */ public class ResponseParam { //返回json中的标识 private static final String RESULT = "result"; private static final String RESPONSE_TYPE = "requestType"; protected static final String CONTENT = "content"; /** * 开始向服务器发送请求 */ public static final int START_REQUEST = -1; /** * 网络异常 */ public static final int NET_WORK_ERROR = -2; /** * 访问服务器失败 */ public static final int REQUEST_FAIL = -3; /** * 请求成功 */ public static final int RESULT_SUCCESS = 0; /** * 用户名错误 */ public static final int RESULT_USER_LOGIN_NAME_ERROR = 1; /** * 密码错误 */ public static final int RESULT_PASSWORD_ERROR = 2; /** * 服务器错误 */ public static final int RESULT_SERVER_ERROR = 3; protected JSONObject jsonObject; public ResponseParam( String responseJson ) throws JSONException { try { this.jsonObject = new JSONObject( responseJson ); } catch ( JSONException e ) { throw e; } } public int getResult() { try { return this.jsonObject.getInt( RESULT ); } catch (JSONException e) { e.printStackTrace(); return ResponseParam.RESULT_SERVER_ERROR; } } public String getRequestType() { try { return this.jsonObject.getString( RESPONSE_TYPE ); } catch (JSONException e) { e.printStackTrace(); return ""; } } public String getContent() { try { return this.jsonObject.getString( CONTENT ); } catch (JSONException e) { e.printStackTrace(); return ""; } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/network/Request.java
src/com/droid/network/Request.java
package com.droid.network; import android.util.Log; import com.droid.application.ClientApplication; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; public class Request { private static final int CONNECTTIMEOUT = 30000; private static final int READTIMEOUT = 20000; private static boolean d = true; public static String request( String json,String requestType ) {return "";} public static String requestIp(String MacAddress) {return "";} }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/adapter/AppAutoRunAdapter.java
src/com/droid/adapter/AppAutoRunAdapter.java
package com.droid.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.droid.R; import com.droid.bean.AppBean; import java.util.List; public class AppAutoRunAdapter extends BaseAdapter { private List<AppBean> appBeanList = null; private Context context; public static AppAutoRunHolder holder; public AppAutoRunAdapter(Context context, List<AppBean> appBeanList) { this.context = context; this.appBeanList = appBeanList; } @Override public int getCount() { return appBeanList.size(); } @Override public Object getItem(int position) { return appBeanList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { holder = new AppAutoRunHolder(); convertView = LayoutInflater.from(context).inflate( R.layout.item_app_auto_run, null); holder.name = (TextView) convertView .findViewById(R.id.item_app_auto_run_name); holder.icon = (ImageView) convertView .findViewById(R.id.item_app_auto_run_iv); holder.flag = (ImageView) convertView .findViewById(R.id.item_app_auto_run_flag); convertView.setTag(holder); } else { holder = (AppAutoRunHolder) convertView.getTag(); } AppBean appBean = appBeanList.get(position); holder.icon.setBackgroundDrawable(appBean.getIcon()); holder.name.setText(appBean.getName()); return convertView; } public class AppAutoRunHolder { private TextView name; private ImageView icon; private ImageView flag; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/adapter/DataPagerAdapter.java
src/com/droid/adapter/DataPagerAdapter.java
package com.droid.adapter; import java.util.List; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; public class DataPagerAdapter<T> extends PagerAdapter { private Context mContext; private List<T> mList = null; public DataPagerAdapter(Context context, List<T> list) { mContext = context; mList = list; } @Override public int getCount() { return mList.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public int getItemPosition(Object object) { return super.getItemPosition(object); } @Override public void destroyItem(ViewGroup container, int position, Object object) { // super.destroyItem(container, position, object); container.removeView((View) mList.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView((View) mList.get(position)); return mList.get(position); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/adapter/AppUninstallAdapter.java
src/com/droid/adapter/AppUninstallAdapter.java
package com.droid.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.droid.R; import com.droid.bean.AppBean; import java.util.List; public class AppUninstallAdapter extends BaseAdapter { private List<AppBean> appBeanList = null; private Context context; public AppUninstallAdapter(Context context, List<AppBean> appBeanList) { this.context = context; this.appBeanList = appBeanList; } @Override public int getCount() { return appBeanList.size(); } @Override public Object getItem(int position) { return appBeanList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { Holder holder; if (convertView == null) { holder = new Holder(); convertView = LayoutInflater.from(context).inflate( R.layout.item_app_uninstall, null); holder.name = (TextView) convertView .findViewById(R.id.item_app_uninstall_name); holder.icon = (ImageView) convertView .findViewById(R.id.item_app_uninstall_iv); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } AppBean appBean = appBeanList.get(position); holder.icon.setBackgroundDrawable(appBean.getIcon()); holder.name.setText(appBean.getName()); return convertView; } private class Holder { private TextView name; private ImageView icon; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/adapter/MainActivityAdapter.java
src/com/droid/adapter/MainActivityAdapter.java
package com.droid.adapter; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import java.util.ArrayList; /** * @author Droid *继承 FragmentStatePagerAdapter,fragment才会及时更新 */ public class MainActivityAdapter extends FragmentStatePagerAdapter { private ArrayList<Fragment> mFragments; private FragmentManager fm; public MainActivityAdapter(FragmentManager fm, ArrayList<Fragment> fragments) { super(fm); mFragments = fragments; this.fm=fm; } @Override public Fragment getItem(int i) { return mFragments.get(i); } @Override public int getCount() { return mFragments.size(); } @Override public Parcelable saveState() { return null; } @Override public void restoreState(Parcelable state, ClassLoader loader) { } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/adapter/MyBluetoothAdapter.java
src/com/droid/adapter/MyBluetoothAdapter.java
package com.droid.adapter; import android.bluetooth.BluetoothClass; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.droid.R; import java.util.List; import java.util.Map; /** * 蓝牙管理adapter */ public class MyBluetoothAdapter extends BaseAdapter { private List<Map<String,Object>> list; private Context context; private Holder holder; public MyBluetoothAdapter(Context context, List<Map<String, Object>> list) { this.context = context; this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { holder = new Holder(); convertView = LayoutInflater.from(context).inflate( R.layout.item_bluetooth, null); holder.name = (TextView) convertView .findViewById(R.id.item_bluetooth_name); holder.icon = (ImageView) convertView .findViewById(R.id.item_bluetooth_iv); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } Map<String,Object> map = list.get(position); String name = (String) map.get("name"); if(name != null){ holder.name.setText((String) map.get("name")); } int type = (Integer)map.get("type"); //根据设备类型 设置相应图片 if(type> BluetoothClass.Device.PHONE_UNCATEGORIZED&&type<BluetoothClass.Device.PHONE_ISDN){ holder.icon.setBackgroundResource(R.drawable.phone); }else if(type> BluetoothClass.Device.COMPUTER_UNCATEGORIZED&&type<BluetoothClass.Device.COMPUTER_WEARABLE){ holder.icon.setBackgroundResource(R.drawable.pc); }else if(type> BluetoothClass.Device.TOY_UNCATEGORIZED&&type<BluetoothClass.Device.TOY_GAME){ holder.icon.setBackgroundResource(R.drawable.handle); } return convertView; } private class Holder { private TextView name; private ImageView icon; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/test/java/com/jiang/android/zhihu_topanswer/ExampleUnitTest.java
app/src/test/java/com/jiang/android/zhihu_topanswer/ExampleUnitTest.java
package com.jiang.android.zhihu_topanswer; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/App.java
app/src/main/java/com/jiang/android/zhihu_topanswer/App.java
package com.jiang.android.zhihu_topanswer; import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.db.DbCore; /** * Created by jiang on 2016/12/24. */ public class App extends com.jiang.android.architecture.App { @Override public void onCreate() { super.onCreate(); DbCore.init(this); L.debug(true); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/MainFragment.java
app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/MainFragment.java
package com.jiang.android.zhihu_topanswer.fragment; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.jiang.android.architecture.adapter.BaseAdapter; import com.jiang.android.architecture.adapter.BaseViewHolder; import com.jiang.android.zhihu_topanswer.R; import com.jiang.android.zhihu_topanswer.model.TopicModel; import com.jiang.android.zhihu_topanswer.utils.AllTopic; import com.jiang.android.zhihu_topanswer.view.SelectPopupWindow; import com.trello.rxlifecycle.android.FragmentEvent; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by jiang on 2016/12/28. */ public class MainFragment extends BaseFragment { private List<TopicModel> mLists = new ArrayList<>(); private List<RecyclerViewFragment> mFragments = new ArrayList<>(); private TabLayout mTabLayout; private ViewPager mViewPager; private ImageView mSelectPop; private TabAdapter adapter; private SelectPopupWindow popupWindow; private View mLine; public static MainFragment newInstance() { Bundle args = new Bundle(); MainFragment fragment = new MainFragment(); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main, container, false); initTabLayout(view); return view; } private void initTabLayout(View view) { mTabLayout = (TabLayout) view.findViewById(R.id.main_tablayout); mViewPager = (ViewPager) view.findViewById(R.id.viewPager); mSelectPop = (ImageView) view.findViewById(R.id.main_arrow); mLine = view.findViewById(R.id.main_pop_line); } private void initViewPager() { if (adapter == null) { adapter = new TabAdapter(getChildFragmentManager(), mLists, mFragments); mViewPager.setAdapter(adapter); mViewPager.setOffscreenPageLimit(mLists.size()); //为TabLayout设置ViewPager mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); mTabLayout.setupWithViewPager(mViewPager); mSelectPop.setClickable(true); mSelectPop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { initPopWindow(); } }); } else { adapter.notifyDataSetChanged(); } } private static class TabAdapter extends FragmentPagerAdapter { private List<TopicModel> title; private List<RecyclerViewFragment> views; public TabAdapter(FragmentManager fm, List<TopicModel> title, List<RecyclerViewFragment> views) { super(fm); this.title = title; this.views = views; } @Override public Fragment getItem(int position) { return views.get(position); } @Override public int getCount() { return views.size(); } //配置标题的方法 @Override public CharSequence getPageTitle(int position) { return title.get(position).getName(); } } private void initView() { mLists.clear(); mFragments.clear(); mTabLayout.removeAllTabs(); mLists.addAll(AllTopic.getInstance().getAllTopics(getActivity())); Observable.from(mLists) .map(new Func1<TopicModel, TopicModel>() { @Override public TopicModel call(TopicModel topicModel) { mFragments.add(RecyclerViewFragment.newInstance(topicModel.getTopic())); return topicModel; } }).compose(this.<TopicModel>bindUntilEvent(FragmentEvent.DESTROY)) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<TopicModel>() { @Override public void onCompleted() { initViewPager(); } @Override public void onError(Throwable e) { } @Override public void onNext(TopicModel topicModel) { mTabLayout.addTab(mTabLayout.newTab().setText(topicModel.getName())); } }); } private void initPopWindow() { initPopWindowReal(); } private void initPopWindowReal() { if (popupWindow == null) { popupWindow = new SelectPopupWindow(getActivity()); popupWindow.setAdapter(new BaseAdapter() { @Override public void onBindView(BaseViewHolder holder, int position) { holder.setText(R.id.item_pop_text, mLists.get(position).getName()); } @Override public int getLayoutID(int position) { return R.layout.item_pop_t; } @Override public boolean clickable() { return true; } @Override public void onItemClick(View v, int position) { super.onItemClick(v, position); choosePosition(position); popupWindow.dismiss(); } @Override public int getItemCount() { return mLists.size(); } }); } popupWindow.showAsDropDown(mLine); } private void choosePosition(int position) { mTabLayout.setScrollPosition(position, 0, true); mViewPager.setCurrentItem(position); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/BaseFragment.java
app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/BaseFragment.java
package com.jiang.android.zhihu_topanswer.fragment; /** * Created by jiang on 2016/12/24. */ public class BaseFragment extends BaseLazyFragment{ @Override protected void onFirstUserVisible() { } @Override protected void onUserVisible() { } @Override protected void onUserInvisible() { } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/BaseLazyFragment.java
app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/BaseLazyFragment.java
package com.jiang.android.zhihu_topanswer.fragment; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import com.jiang.android.architecture.rxsupport.RxFragment; public abstract class BaseLazyFragment extends RxFragment { private boolean isFirstResume = true; private boolean isFirstVisible = true; private boolean isFirstInvisible = true; private boolean isPrepared; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initPrepare(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) @Override public void onResume() { super.onResume(); if (isFirstResume) { isFirstResume = false; return; } if (getUserVisibleHint()) { onUserVisible(); } } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) @Override public void onPause() { super.onPause(); if (getUserVisibleHint()) { onUserInvisible(); } } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { if (isFirstVisible) { isFirstVisible = false; initPrepare(); } else { onUserVisible(); } } else { if (isFirstInvisible) { isFirstInvisible = false; onFirstUserInvisible(); } else { onUserInvisible(); } } } private synchronized void initPrepare() { if (isPrepared) { onFirstUserVisible(); } else { isPrepared = true; } } /** * when fragment is visible for the first time, here we can do some initialized work or refresh data only once */ protected abstract void onFirstUserVisible(); /** * this method like the fragment's lifecycle method onResume() */ protected abstract void onUserVisible(); /** * when fragment is invisible for the first time */ private void onFirstUserInvisible() { // here we do not recommend do something } /** * this method like the fragment's lifecycle method onPause() */ protected abstract void onUserInvisible(); }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/RecyclerViewFragment.java
app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/RecyclerViewFragment.java
package com.jiang.android.zhihu_topanswer.fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.facebook.drawee.view.SimpleDraweeView; import com.jiang.android.architecture.adapter.BaseAdapter; import com.jiang.android.architecture.adapter.BaseViewHolder; import com.jiang.android.architecture.utils.L; import com.jiang.android.architecture.view.LoadMoreRecyclerView; import com.jiang.android.architecture.view.MultiStateView; import com.jiang.android.zhihu_topanswer.R; import com.jiang.android.zhihu_topanswer.activity.AnswersActivity; import com.jiang.android.zhihu_topanswer.model.TopicAnswers; import com.jiang.android.zhihu_topanswer.utils.JSoupUtils; import com.trello.rxlifecycle.android.FragmentEvent; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by jiang on 2016/12/23. */ public class RecyclerViewFragment extends BaseFragment { private static final String TAG = "RecyclerViewFragment"; public static final int PAGE_START = 1; private int mPage = PAGE_START; private static final java.lang.String BUNDLE_ID = "bundle_id"; private int mTopic; private LoadMoreRecyclerView mRecyclerView; private List<TopicAnswers> mLists = new ArrayList<>(); private SwipeRefreshLayout mRefresh; private MultiStateView mStateView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle arguments = getArguments(); if (arguments != null) { mTopic = arguments.getInt(BUNDLE_ID); } View view = inflater.inflate(R.layout.fragment_recyclerview, container, false); mRecyclerView = (LoadMoreRecyclerView) view.findViewById(R.id.fragment_rv); mRefresh = (SwipeRefreshLayout) view.findViewById(R.id.fragment_refresh); mStateView = (MultiStateView) view.findViewById(R.id.fragment_state); return view; } public static RecyclerViewFragment newInstance(int topic) { Bundle bundle = new Bundle(); bundle.putInt(BUNDLE_ID, topic); RecyclerViewFragment fragment = new RecyclerViewFragment(); fragment.setArguments(bundle); return fragment; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); } private void initView() { mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { initData(false, mPage = PAGE_START); } }); mRecyclerView.setCanLOADMORE(true); mRecyclerView.setOnLoadMoreListener(new LoadMoreRecyclerView.OnLoadMoreListener() { @Override public void onLoadMore() { L.i("onLoadMore"); initData(false, ++mPage); } }); } public void initData(final boolean needState, final int page) { if (needState) { mStateView.setViewState(MultiStateView.ViewState.LOADING); } final String url = "https://www.zhihu.com/topic/" + mTopic + "/top-answers?page=" + page; Observable.create(new Observable.OnSubscribe<Document>() { @Override public void call(Subscriber<? super Document> subscriber) { try { subscriber.onNext(Jsoup.connect(url).timeout(5000).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6").get()); subscriber.onCompleted(); } catch (IOException e) { e.printStackTrace(); subscriber.onError(e); } } }).map(new Func1<Document, List<TopicAnswers>>() { @Override public List<TopicAnswers> call(Document document) { return JSoupUtils.getTopicList(document); } }).compose(this.<List<TopicAnswers>>bindUntilEvent(FragmentEvent.DESTROY)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<List<TopicAnswers>>() { @Override public void onCompleted() { if (mStateView.getViewState() != MultiStateView.ViewState.CONTENT) { mStateView.setViewState(MultiStateView.ViewState.CONTENT); } if (page == 1) { mRefresh.setRefreshing(false); } else { mRecyclerView.setLoadmore_state(LoadMoreRecyclerView.STATE_FINISH_LOADMORE); } initRecyclerView(); } @Override public void onError(Throwable e) { if (needState) { mStateView.setViewState(MultiStateView.ViewState.ERROR); } if (page == 1) { mRefresh.setRefreshing(false); } else { mRecyclerView.setLoadmore_state(LoadMoreRecyclerView.STATE_FINISH_LOADMORE); } if (mPage > 1) { mPage--; } } @Override public void onNext(List<TopicAnswers> s) { if (page == 1) { mLists.clear(); mLists.addAll(s); } else { mLists.addAll(s); } } }); } private void initRecyclerView() { if (mRecyclerView.getAdapter() == null) { mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); mRecyclerView.setAdapter(new BaseAdapter() { @Override public void onBindView(BaseViewHolder holder, int position) { TopicAnswers answers = mLists.get(position); holder.setText(R.id.item_fr_top_title, answers.getTitle()) .setText(R.id.item_fr_top_body, answers.getBody()) .setText(R.id.item_fr_top_vote, answers.getVote() + " 赞同"); SimpleDraweeView simpleDraweeView = holder.getView(R.id.item_fr_top_desc); if (TextUtils.isEmpty(answers.getImg())) { simpleDraweeView.setVisibility(View.GONE); } else { simpleDraweeView.setVisibility(View.VISIBLE); simpleDraweeView.setImageURI(Uri.parse(answers.getImg())); } } @Override public int getLayoutID(int position) { return R.layout.item_fragment; } @Override public boolean clickable() { return true; } @Override public void onItemClick(View v, int position) { super.onItemClick(v, position); Intent intent = new Intent(getActivity(), AnswersActivity.class); intent.putExtra(AnswersActivity.QUESTION_URL, mLists.get(position ).getUrl()); startActivity(intent); } @Override public int getItemCount() { return mLists.size(); } }); } else { mRecyclerView.getAdapter().notifyDataSetChanged(); } } @Override protected void onFirstUserVisible() { super.onFirstUserVisible(); onUserVisible(); } @Override protected void onUserVisible() { super.onUserVisible(); if (getActivity() == null) return; if (mLists == null || mLists.size() == 0) { initData(true, mPage = PAGE_START); } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/CollectionFragment.java
app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/CollectionFragment.java
package com.jiang.android.zhihu_topanswer.fragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.jiang.android.architecture.adapter.BaseAdapter; import com.jiang.android.architecture.adapter.BaseViewHolder; import com.jiang.android.architecture.view.MultiStateView; import com.jiang.android.zhihu_topanswer.R; import com.jiang.android.zhihu_topanswer.activity.AnswerDetailActivity; import com.jiang.android.zhihu_topanswer.activity.AnswersActivity; import com.jiang.android.zhihu_topanswer.db.Collection; import com.jiang.android.zhihu_topanswer.utils.CollectionUtils; /** * Created by jiang on 2016/12/28. */ public class CollectionFragment extends BaseFragment { private SwipeRefreshLayout mRefresh; private MultiStateView mStateView; private RecyclerView mRecyclerView; public static CollectionFragment newInstance() { CollectionFragment fragment = new CollectionFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_collection, container, false); mRecyclerView = (RecyclerView) view.findViewById(R.id.fragment_rv); mRefresh = (SwipeRefreshLayout) view.findViewById(R.id.fragment_refresh); mStateView = (MultiStateView) view.findViewById(R.id.fragment_state); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); initData(); } private void initView() { mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { initData(); } }); } private void initData( ) { mStateView.setViewState(MultiStateView.ViewState.CONTENT); mRefresh.setRefreshing(false); initRecyclerView(); } private void initRecyclerView() { if (mRecyclerView.getAdapter() == null) { mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); mRecyclerView.setAdapter(new BaseAdapter() { @Override public void onBindView(BaseViewHolder holder, int position) { if(position == 0){ TextView tv = holder.getView(R.id.collection_clear_all); tv.setClickable(true); tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearAll(); } }); return; } position = position-1; Collection answers = CollectionUtils.getInstance().getCollection().get(position); holder.setText(R.id.item_fr_top_title, answers.getTitle()) .setText(R.id.item_fr_top_body, Html.fromHtml(answers.getDetail()).toString()) .setVisibility(R.id.item_fr_top_body, TextUtils.isEmpty(answers.getDetail())?BaseViewHolder.GONE:BaseViewHolder.VISIBLE); } @Override public int getLayoutID(int position) { if(position == 0) return R.layout.item_top_collection_fragment; return R.layout.item_collection_fragment; } @Override public boolean clickable() { return true; } @Override public void onItemClick(View v, int position) { super.onItemClick(v, position); if(position == 0) return; position = position-1; if(CollectionUtils.getInstance().getCollection().get(position).getType() == CollectionUtils.TYPE_ANSWERS){ Intent intent = new Intent(getActivity(), AnswersActivity.class); intent.putExtra(AnswersActivity.QUESTION_URL, CollectionUtils.getInstance().getCollection().get(position).getUrl()); startActivity(intent); }else{ Intent intent = new Intent(getActivity(), AnswerDetailActivity.class); intent.putExtra(AnswerDetailActivity.URL, CollectionUtils.getInstance().getCollection().get(position).getUrl()); intent.putExtra(AnswerDetailActivity.TITLE, CollectionUtils.getInstance().getCollection().get(position).getTitle()); intent.putExtra(AnswerDetailActivity.DETAIL, CollectionUtils.getInstance().getCollection().get(position).getDetail()); startActivity(intent); } } @Override public int getItemCount() { return CollectionUtils.getInstance().getCollection().size()+1; } }); } else { mRecyclerView.getAdapter().notifyDataSetChanged(); } } private void clearAll() { new AlertDialog.Builder(getActivity()) .setTitle("确定全部删除?") .setMessage("删除后将无法恢复") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { CollectionUtils.getInstance().clear(); dialog.dismiss(); initData(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/activity/MainActivity.java
app/src/main/java/com/jiang/android/zhihu_topanswer/activity/MainActivity.java
package com.jiang.android.zhihu_topanswer.activity; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.jiang.android.architecture.rxsupport.RxAppCompatActivity; import com.jiang.android.zhihu_topanswer.R; import com.jiang.android.zhihu_topanswer.fragment.BaseFragment; import com.jiang.android.zhihu_topanswer.fragment.CollectionFragment; import com.jiang.android.zhihu_topanswer.fragment.MainFragment; import com.luseen.luseenbottomnavigation.BottomNavigation.BottomNavigationItem; import com.luseen.luseenbottomnavigation.BottomNavigation.BottomNavigationView; import com.luseen.luseenbottomnavigation.BottomNavigation.OnBottomNavigationItemClickListener; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends RxAppCompatActivity { private List<BaseFragment> mFragments = new ArrayList<>(); private int mCheckPosition = 0; private int mLastCheckePosition = -1; private Toolbar mToolbar; private boolean isExit; private BottomNavigationView mBottomView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initTitle(); initFragment(); initBottomNav(); itemChecked(); } private void initBottomNav(){ mBottomView = (BottomNavigationView) findViewById(R.id.main_bottom_nav); BottomNavigationItem bottomNavigationItem = new BottomNavigationItem ("话题", ContextCompat.getColor(this, R.color.colorPrimaryDark), R.drawable.ic_topic); BottomNavigationItem bottomNavigationItem1 = new BottomNavigationItem ("收藏", ContextCompat.getColor(this, R.color.colorPrimaryDark), R.drawable.ic_collection); mBottomView.addTab(bottomNavigationItem); mBottomView.addTab(bottomNavigationItem1); mBottomView.setOnBottomNavigationItemClickListener(new OnBottomNavigationItemClickListener() { @Override public void onNavigationItemClick(int index) { if(index == mCheckPosition) return; mLastCheckePosition = mCheckPosition; mCheckPosition = index; itemChecked(); } }); } private void itemChecked() { if(mCheckPosition>=0){ switchFragment(mLastCheckePosition>=0?mFragments.get(mLastCheckePosition):null,mFragments.get(mCheckPosition)); } } private void initFragment() { mFragments.add(MainFragment.newInstance()); mFragments.add(CollectionFragment.newInstance()); } private void initTitle() { mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); mToolbar.setTitle(getString(R.string.app_name)); } @Override public void onBackPressed() { exitBy2Click(); } /** * 双击退出 */ private void exitBy2Click() { Timer tExit; if (isExit == false) { isExit = true; // 准备退出 toast("再按一次退出程序"); tExit = new Timer(); tExit.schedule(new TimerTask() { @Override public void run() { isExit = false; // 取消退出 } }, 3000); // 如果3秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务 } else { this.finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about: Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://github.com/jiang111?tab=repositories")); startActivity(intent); break; case R.id.share: shareText(item.getActionView()); break; case R.id.update: Toast.makeText(this, "当前版本:" + getVersion(), Toast.LENGTH_SHORT).show(); Intent updateIntent = new Intent(Intent.ACTION_VIEW); updateIntent.setData(Uri.parse("https://github.com/jiang111/ZhiHu-TopAnswer/releases")); startActivity(updateIntent); } return super.onOptionsItemSelected(item); } public void shareText(View view) { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, "Hi,我正在使用" + getString(R.string.app_name) + ",推荐你下载这个app一起玩吧 到应用商店或者https://github.com/jiang111/ZhiHu-TopAnswer/releases即可下载"); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, "分享到")); } public String getVersion() { try { PackageManager manager = this.getPackageManager(); PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); String version = info.versionName; return version; } catch (Exception e) { e.printStackTrace(); return "1.0"; } } public void switchFragment(BaseFragment from, BaseFragment to) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); if (from == null) { if (to != null) { transaction.replace(R.id.id_content, to); transaction.commit(); } } else { if (!to.isAdded()) { transaction.hide(from).add(R.id.id_content, to).commit(); } else { transaction.hide(from).show(to).commit(); } } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/activity/AnswersActivity.java
app/src/main/java/com/jiang/android/zhihu_topanswer/activity/AnswersActivity.java
package com.jiang.android.zhihu_topanswer.activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import com.jiang.android.architecture.adapter.BaseAdapter; import com.jiang.android.architecture.adapter.BaseViewHolder; import com.jiang.android.architecture.rxsupport.RxAppCompatActivity; import com.jiang.android.architecture.view.MultiStateView; import com.jiang.android.zhihu_topanswer.R; import com.jiang.android.zhihu_topanswer.db.Collection; import com.jiang.android.zhihu_topanswer.model.AnswersModel; import com.jiang.android.zhihu_topanswer.utils.CollectionUtils; import com.trello.rxlifecycle.android.ActivityEvent; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by jiang on 2016/12/24. */ public class AnswersActivity extends RxAppCompatActivity { public static final String QUESTION_URL = "question_url"; private String mQuestionUrl; private RecyclerView mRecyclerView; private List<AnswersModel> mLists = new ArrayList<>(); private SwipeRefreshLayout mRefresh; private MultiStateView mStateView; private String title; private String detail; private LinearLayoutManager linearLayoutManager; private Toolbar mToolBar; private boolean isSaved; //已经收藏了 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_answers); mRecyclerView = (RecyclerView) findViewById(R.id.activity_answers_rv); mRefresh = (SwipeRefreshLayout) findViewById(R.id.activity_answers_refresh); mStateView = (MultiStateView) findViewById(R.id.activity_answers_state); mToolBar = (Toolbar) findViewById(R.id.activity_answers_toolbar); mQuestionUrl = getIntent().getStringExtra(QUESTION_URL); initView(); initStateView(); } private void initView() { setTitle(false); mToolBar.setNavigationIcon(ContextCompat.getDrawable(this,R.drawable.ic_back)); setSupportActionBar(mToolBar); mToolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { initData(false); } }); initData(true); } private void setTitle(boolean show) { if (show) { mToolBar.setTitle(title); } else { mToolBar.setTitle(""); } } public void initData(final boolean needState) { if (needState) { mStateView.setViewState(MultiStateView.ViewState.LOADING); } final String url = mQuestionUrl; Observable.create(new Observable.OnSubscribe<Document>() { @Override public void call(Subscriber<? super Document> subscriber) { try { subscriber.onNext(Jsoup.connect(url + "#zh-question-collapsed-wrap").timeout(5000).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6").get()); subscriber.onCompleted(); } catch (IOException e) { e.printStackTrace(); subscriber.onError(e); } } }).map(new Func1<Document, List<AnswersModel>>() { @Override public List<AnswersModel> call(Document document) { List<AnswersModel> list = new ArrayList<>(); Element titleLink = document.getElementById("zh-question-title"); Element detailLink = document.getElementById("zh-question-detail"); String title = titleLink.select("span.zm-editable-content").text(); String detailHtml = detailLink.select("div.zm-editable-content").html(); AnswersActivity.this.title = title; detail = detailHtml; Element bodyAnswer = document.getElementById("zh-question-answer-wrap"); Elements bodys = bodyAnswer.select("div.zm-item-answer"); Element bodyWrapAnswer = document.getElementById("zh-question-collapsed-wrap"); bodys.addAll(bodyWrapAnswer.select("div.zm-item-answer.zm-item-expanded")); if (bodys.iterator().hasNext()) { Iterator iterator = bodys.iterator(); while (iterator.hasNext()) { AnswersModel answersModel = new AnswersModel(); Element element = (Element) iterator.next(); String url = element.getElementsByTag("link").attr("href"); String vote = element.select("span.count").text(); String content = element.select("div.zh-summary.summary.clearfix").text(); if (content.length() > 4) { content = content.substring(0, content.length() - 4); } String user = element.select("a.author-link").text(); answersModel.setAuthor(user); answersModel.setContent(content); answersModel.setUrl(url); answersModel.setVote(vote); list.add(answersModel); } } return list; } }).compose(this.<List<AnswersModel>>bindUntilEvent(ActivityEvent.DESTROY)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<List<AnswersModel>>() { @Override public void onCompleted() { if (mStateView.getViewState() != MultiStateView.ViewState.CONTENT) { mStateView.setViewState(MultiStateView.ViewState.CONTENT); } mRefresh.setRefreshing(false); initRecyclerView(); } @Override public void onError(Throwable e) { if (needState) { mStateView.setViewState(MultiStateView.ViewState.ERROR); } mRefresh.setRefreshing(false); } @Override public void onStart() { super.onStart(); } @Override public void onNext(List<AnswersModel> s) { mLists.clear(); mLists.addAll(s); } }); } private void initRecyclerView() { if (mRecyclerView.getAdapter() == null) { linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(linearLayoutManager); mRecyclerView.setAdapter(new BaseAdapter() { @Override public void onBindView(BaseViewHolder holder, int position) { if (position == 0) { holder.setText(R.id.item_fr_answers_top_title, title) .setVisibility(R.id.item_fr_answers_top_body, TextUtils.isEmpty(detail) ? BaseViewHolder.GONE : BaseViewHolder.VISIBLE) .setText(R.id.item_fr_answers_top_body, Html.fromHtml(detail).toString()) .setText(R.id.item_fr_answers_top_count, mLists.size() + "个回答(只抽取前" + mLists.size() + "个)"); } else { AnswersModel answers = mLists.get(position - 1); holder.setText(R.id.item_fr_answers_author, TextUtils.isEmpty(answers.getAuthor()) ? "匿名" : answers.getAuthor()) .setText(R.id.item_fr_answers_body, answers.getContent()) .setText(R.id.item_fr_answers_vote, answers.getVote() + " 赞同"); } } @Override public int getLayoutID(int position) { if (position == 0) return R.layout.item_answers_top_activity; return R.layout.item_answers_activity; } @Override public boolean clickable() { return true; } @Override public void onItemClick(View v, int position) { super.onItemClick(v, position); if (position == 0) return; Intent intent = new Intent(AnswersActivity.this, AnswerDetailActivity.class); intent.putExtra(AnswerDetailActivity.URL, mLists.get(position - 1).getUrl()); intent.putExtra(AnswerDetailActivity.TITLE, title); intent.putExtra(AnswerDetailActivity.DETAIL, detail); startActivity(intent); } @Override public int getItemCount() { return mLists.size() + 1; } }); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (linearLayoutManager.findFirstVisibleItemPosition() != 0) { setTitle(true); } else { setTitle(false); } } }); } else { mRecyclerView.getAdapter().notifyDataSetChanged(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_answer, menu); return true; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { CollectionUtils.getInstance().contailItem(mQuestionUrl).compose(this.<Collection>bindUntilEvent(ActivityEvent.DESTROY)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Collection>() { @Override public void call(Collection model) { isSaved = true; menu.findItem(R.id.save).setIcon(ContextCompat.getDrawable(AnswersActivity.this,R.drawable.ic_save)); } }); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.save: if(mLists.size()==0) return true; saveCurrentItem(); if(isSaved) { item.setIcon(ContextCompat.getDrawable(AnswersActivity.this, R.drawable.ic_save)); }else{ item.setIcon(ContextCompat.getDrawable(AnswersActivity.this, R.drawable.ic_save_normal)); } break; case R.id.web_look: Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(mQuestionUrl)); startActivity(intent); break; } return super.onOptionsItemSelected(item); } private void saveCurrentItem() { if(isSaved){ CollectionUtils.getInstance().removeItem(mQuestionUrl); toast("取消收藏成功"); isSaved = false; }else{ isSaved = true; Collection model = new Collection(); model.setId(System.currentTimeMillis()); model.setTitle(title); model.setDetail(detail); model.setType(CollectionUtils.TYPE_ANSWERS); model.setUrl(mQuestionUrl); CollectionUtils.getInstance().saveItem(model); toast("收藏成功"); } } private void initStateView() { LinearLayout error = (LinearLayout) mStateView.findViewById(R.id.error_root_layout); error.setClickable(true); error.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { initData(true); } }); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/activity/AnswerDetailActivity.java
app/src/main/java/com/jiang/android/zhihu_topanswer/activity/AnswerDetailActivity.java
package com.jiang.android.zhihu_topanswer.activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.WebView; import android.widget.LinearLayout; import android.widget.TextView; import com.jiang.android.architecture.rxsupport.RxAppCompatActivity; import com.jiang.android.architecture.view.MultiStateView; import com.jiang.android.zhihu_topanswer.R; import com.trello.rxlifecycle.android.ActivityEvent; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.Iterator; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by jiang on 2016/12/24. */ public class AnswerDetailActivity extends RxAppCompatActivity { private static final String TAG = "AnswerDetailActivity"; public static final String URL = "url"; public static final String TITLE = "title"; public static final String DETAIL = "detail"; private String mUrl; private WebView mWebView; private MultiStateView mStateView; private String title; private String bodyHtml; private TextView mDetail; private String detail; private View mPadding; private boolean isSaved; private Toolbar mToolBar; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_answers_detail); mUrl = "https://www.zhihu.com" + getIntent().getExtras().getString(URL); title = getIntent().getExtras().getString(TITLE); detail = getIntent().getExtras().getString(DETAIL); mToolBar = (Toolbar) findViewById(R.id.activity_answers_detail_toolbar); mWebView = (WebView) findViewById(R.id.activity_answers_detail_webview); mStateView = (MultiStateView) findViewById(R.id.activity_answers_detail_state); mDetail = (TextView) findViewById(R.id.activity_answers_detail_detail); mPadding = findViewById(R.id.activity_answers_detail_padding); initStateView(); initView(); } private void initStateView() { LinearLayout error = (LinearLayout) mStateView.findViewById(R.id.error_root_layout); error.setClickable(true); error.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { initData(true); } }); } private void initView() { mToolBar.setTitle(title); mToolBar.setNavigationIcon(ContextCompat.getDrawable(this,R.drawable.ic_back)); setSupportActionBar(mToolBar); mToolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); mWebView.getSettings().setDefaultTextEncodingName("UTF-8"); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); mWebView.getSettings().setSupportZoom(false); mWebView.getSettings().setBuiltInZoomControls(false); if (TextUtils.isEmpty(detail)) { mPadding.setVisibility(View.GONE); mDetail.setVisibility(View.GONE); } else { mPadding.setVisibility(View.VISIBLE); mDetail.setVisibility(View.VISIBLE); mDetail.setText(Html.fromHtml(detail).toString()); } initData(true); } private void initData(final boolean needState) { if (needState) { mStateView.setViewState(MultiStateView.ViewState.LOADING); } final String url = mUrl; Observable.create(new Observable.OnSubscribe<Document>() { @Override public void call(Subscriber<? super Document> subscriber) { try { subscriber.onNext(Jsoup.connect(url).timeout(5000).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6").get()); subscriber.onCompleted(); } catch (IOException e) { e.printStackTrace(); subscriber.onError(e); } } }).map(new Func1<Document, String>() { @Override public String call(Document document) { Element bodyAnswer = document.getElementById("zh-question-answer-wrap"); Elements bodys = bodyAnswer.select("div.zm-item-answer"); Elements headElements = document.getElementsByTag("head"); headElements.iterator().next(); String head = headElements.iterator().next().outerHtml(); String html = ""; if (bodys.iterator().hasNext()) { Iterator iterator = bodys.iterator(); if (iterator.hasNext()) { Element element = (Element) iterator.next(); String body = "<body>" + element.select("div.zm-item-rich-text.expandable.js-collapse-body").iterator().next().outerHtml() + "</body>"; html = "<html lang=\"en\" xmlns:o=\"http://www.w3.org/1999/xhtml\">" + head + body + "</html>"; Document docu = Jsoup.parse(html); Elements elements = docu.getElementsByTag("img"); Iterator iter = elements.iterator(); while (iter.hasNext()) { Element imgElement = (Element) iter.next(); String result = imgElement.attr("data-actualsrc"); if (TextUtils.isEmpty(result)) { result = imgElement.attr("data-original"); } imgElement.attr("src", result); } html = docu.outerHtml(); return html; } } return ""; } }).compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { if (mStateView.getViewState() != MultiStateView.ViewState.CONTENT) { mStateView.setViewState(MultiStateView.ViewState.CONTENT); } if(bodyHtml.length()>100000){ toast("网页加载中,请耐心等待"); } mWebView.loadDataWithBaseURL("http://www.zhihu.com", bodyHtml, "text/html", "utf-8", null); } @Override public void onError(Throwable e) { if (needState) { mStateView.setViewState(MultiStateView.ViewState.ERROR); } } @Override public void onStart() { super.onStart(); } @Override public void onNext(String s) { bodyHtml = s; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_answer_detail, menu); return true; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.web_look: Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(mUrl)); startActivity(intent); break; } return super.onOptionsItemSelected(item); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/model/TopicAnswers.java
app/src/main/java/com/jiang/android/zhihu_topanswer/model/TopicAnswers.java
package com.jiang.android.zhihu_topanswer.model; /** * Created by jiang on 2016/12/23. */ public class TopicAnswers { private String url; private String title; private String img; private String vote; private String body; public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getVote() { return vote; } public void setVote(String vote) { this.vote = vote; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } @Override public String toString() { return "url:" + url + " :title:" + title + " :img:" + img + " :vote:" + vote + " :body:" + body; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/model/TopicModel.java
app/src/main/java/com/jiang/android/zhihu_topanswer/model/TopicModel.java
package com.jiang.android.zhihu_topanswer.model; /** * Created by jiang on 2016/12/23. */ public class TopicModel { private int topic; private String name; public TopicModel(int topic, String name) { this.topic = topic; this.name = name; } public int getTopic() { return topic; } public void setTopic(int topic) { this.topic = topic; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "TopicModel{" + "topic=" + topic + ", name='" + name + '\'' + '}'; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/model/AnswersModel.java
app/src/main/java/com/jiang/android/zhihu_topanswer/model/AnswersModel.java
package com.jiang.android.zhihu_topanswer.model; /** * Created by jiang on 2016/12/24. */ public class AnswersModel { private String vote; private String content; private String author; private String url; public String getVote() { return vote; } public void setVote(String vote) { this.vote = vote; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/db/CollectionService.java
app/src/main/java/com/jiang/android/zhihu_topanswer/db/CollectionService.java
/** * created by jiang, 16/3/13 * Copyright (c) 2016, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.zhihu_topanswer.db; import de.greenrobot.dao.AbstractDao; /** * Created by jiang on 16/3/13. */ public class CollectionService extends BaseService<Collection,Integer> { public CollectionService(AbstractDao dao) { super(dao); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java
app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java
/** * created by jiang, 16/3/13 * Copyright (c) 2016, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.zhihu_topanswer.db; /** * Created by jiang on 16/3/13. */ public class DbUtil { private static CollectionService operatorsService; private static CollectionDao getOperatorsDao() { return DbCore.getDaoSession().getCollectionDao(); } public static CollectionService getOperatorsService() { if (operatorsService == null) { operatorsService = new CollectionService(getOperatorsDao()); } return operatorsService; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/db/BaseService.java
app/src/main/java/com/jiang/android/zhihu_topanswer/db/BaseService.java
/** * created by jiang, 16/3/13 * Copyright (c) 2016, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.zhihu_topanswer.db; import java.util.List; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.query.QueryBuilder; /** * Created by jiang on 16/3/13. */ public class BaseService<T, K> { private AbstractDao<T, K> mDao; public BaseService(AbstractDao dao) { mDao = dao; } public void save(T item) { mDao.insert(item); } public void save(T... items) { mDao.insertInTx(items); } public void save(List<T> items) { mDao.insertInTx(items); } public void saveOrUpdate(T item) { mDao.insertOrReplace(item); } public void saveOrUpdate(T... items) { mDao.insertOrReplaceInTx(items); } public void saveOrUpdate(List<T> items) { mDao.insertOrReplaceInTx(items); } public void deleteByKey(K key) { mDao.deleteByKey(key); } public void delete(T item) { mDao.delete(item); } public void delete(T... items) { mDao.deleteInTx(items); } public void delete(List<T> items) { mDao.deleteInTx(items); } public void deleteAll() { mDao.deleteAll(); } public void update(T item) { mDao.update(item); } public void update(T... items) { mDao.updateInTx(items); } public void update(List<T> items) { mDao.updateInTx(items); } public T query(K key) { return mDao.load(key); } public List<T> queryAll() { return mDao.loadAll(); } public List<T> query(String where, String... params) { return mDao.queryRaw(where, params); } public QueryBuilder<T> queryBuilder() { return mDao.queryBuilder(); } public long count() { return mDao.count(); } public void refresh(T item) { mDao.refresh(item); } public void detach(T item) { mDao.detach(item); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/db/collectionDao.java
app/src/main/java/com/jiang/android/zhihu_topanswer/db/collectionDao.java
package com.jiang.android.zhihu_topanswer.db; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.Property; import de.greenrobot.dao.internal.DaoConfig; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table "COLLECTION". */ public class CollectionDao extends AbstractDao<Collection, Long> { public static final String TABLENAME = "COLLECTION"; /** * Properties of entity Collection.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property Title = new Property(1, String.class, "title", false, "TITLE"); public final static Property Detail = new Property(2, String.class, "detail", false, "DETAIL"); public final static Property Url = new Property(3, String.class, "url", false, "URL"); public final static Property Type = new Property(4, Integer.class, "type", false, "TYPE"); }; public CollectionDao(DaoConfig config) { super(config); } public CollectionDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(SQLiteDatabase db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"COLLECTION\" (" + // "\"_id\" INTEGER PRIMARY KEY ," + // 0: id "\"TITLE\" TEXT," + // 1: title "\"DETAIL\" TEXT," + // 2: detail "\"URL\" TEXT," + // 3: url "\"TYPE\" INTEGER);"); // 4: type } /** Drops the underlying database table. */ public static void dropTable(SQLiteDatabase db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"COLLECTION\""; db.execSQL(sql); } /** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, Collection entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String title = entity.getTitle(); if (title != null) { stmt.bindString(2, title); } String detail = entity.getDetail(); if (detail != null) { stmt.bindString(3, detail); } String url = entity.getUrl(); if (url != null) { stmt.bindString(4, url); } Integer type = entity.getType(); if (type != null) { stmt.bindLong(5, type); } } /** @inheritdoc */ @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } /** @inheritdoc */ @Override public Collection readEntity(Cursor cursor, int offset) { Collection entity = new Collection( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // title cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // detail cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // url cursor.isNull(offset + 4) ? null : cursor.getInt(offset + 4) // type ); return entity; } /** @inheritdoc */ @Override public void readEntity(Cursor cursor, Collection entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setTitle(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setDetail(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); entity.setUrl(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3)); entity.setType(cursor.isNull(offset + 4) ? null : cursor.getInt(offset + 4)); } /** @inheritdoc */ @Override protected Long updateKeyAfterInsert(Collection entity, long rowId) { entity.setId(rowId); return rowId; } /** @inheritdoc */ @Override public Long getKey(Collection entity) { if(entity != null) { return entity.getId(); } else { return null; } } /** @inheritdoc */ @Override protected boolean isEntityUpdateable() { return true; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/db/DaoMaster.java
app/src/main/java/com/jiang/android/zhihu_topanswer/db/DaoMaster.java
package com.jiang.android.zhihu_topanswer.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import de.greenrobot.dao.AbstractDaoMaster; import de.greenrobot.dao.identityscope.IdentityScopeType; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * Master of DAO (schema version 3): knows all DAOs. */ public class DaoMaster extends AbstractDaoMaster { public static final int SCHEMA_VERSION = 3; /** Creates underlying database table using DAOs. */ public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) { CollectionDao.createTable(db, ifNotExists); } /** Drops underlying database table using DAOs. */ public static void dropAllTables(SQLiteDatabase db, boolean ifExists) { CollectionDao.dropTable(db, ifExists); } public static abstract class OpenHelper extends SQLiteOpenHelper { public OpenHelper(Context context, String name, CursorFactory factory) { super(context, name, factory, SCHEMA_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION); createAllTables(db, false); } } /** WARNING: Drops all table on Upgrade! Use only during development. */ public static class DevOpenHelper extends OpenHelper { public DevOpenHelper(Context context, String name, CursorFactory factory) { super(context, name, factory); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables"); dropAllTables(db, true); onCreate(db); } } public DaoMaster(SQLiteDatabase db) { super(db, SCHEMA_VERSION); registerDaoClass(CollectionDao.class); } public DaoSession newSession() { return new DaoSession(db, IdentityScopeType.Session, daoConfigMap); } public DaoSession newSession(IdentityScopeType type) { return new DaoSession(db, type, daoConfigMap); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/db/DaoSession.java
app/src/main/java/com/jiang/android/zhihu_topanswer/db/DaoSession.java
package com.jiang.android.zhihu_topanswer.db; import android.database.sqlite.SQLiteDatabase; import java.util.Map; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.AbstractDaoSession; import de.greenrobot.dao.identityscope.IdentityScopeType; import de.greenrobot.dao.internal.DaoConfig; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * {@inheritDoc} * * @see AbstractDaoSession */ public class DaoSession extends AbstractDaoSession { private final DaoConfig collectionDaoConfig; private final CollectionDao collectionDao; public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> daoConfigMap) { super(db); collectionDaoConfig = daoConfigMap.get(CollectionDao.class).clone(); collectionDaoConfig.initIdentityScope(type); collectionDao = new CollectionDao(collectionDaoConfig, this); registerDao(Collection.class, collectionDao); } public void clear() { collectionDaoConfig.getIdentityScope().clear(); } public CollectionDao getCollectionDao() { return collectionDao; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/db/collection.java
app/src/main/java/com/jiang/android/zhihu_topanswer/db/collection.java
package com.jiang.android.zhihu_topanswer.db; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. /** * Entity mapped to table "COLLECTION". */ public class Collection { private Long id; private String title; private String detail; private String url; private Integer type; public Collection() { } public Collection(Long id) { this.id = id; } public Collection(Long id, String title, String detail, String url, Integer type) { this.id = id; this.title = title; this.detail = detail; this.url = url; this.type = type; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbCore.java
app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbCore.java
/** * created by jiang, 16/3/13 * Copyright (c) 2016, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.zhihu_topanswer.db; import android.content.Context; /** * Created by jiang on 16/3/13. */ public class DbCore { private static final String DEFAULT_DB_NAME = "collection.db"; private static DaoMaster daoMaster; private static DaoSession daoSession; private static Context mContext; private static String DB_NAME; public static void init(Context context) { init(context, DEFAULT_DB_NAME); } public static void init(Context context, String dbName) { if (context == null) { throw new IllegalArgumentException("context can't be null"); } mContext = context.getApplicationContext(); DB_NAME = dbName; } public static DaoMaster getDaoMaster() { if (daoMaster == null) { DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null); daoMaster = new DaoMaster(helper.getWritableDatabase()); } return daoMaster; } public static DaoSession getDaoSession() { if (daoSession == null) { if (daoMaster == null) { daoMaster = getDaoMaster(); } daoSession = daoMaster.newSession(); } return daoSession; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/utils/AllTopic.java
app/src/main/java/com/jiang/android/zhihu_topanswer/utils/AllTopic.java
package com.jiang.android.zhihu_topanswer.utils; import android.content.Context; import com.jiang.android.architecture.utils.SharePrefUtil; import com.jiang.android.zhihu_topanswer.model.TopicModel; import java.util.ArrayList; import java.util.List; /** * Created by jiang on 2016/12/23. */ public class AllTopic { private static String cacheString = "19550429=电影&19551147=生活&19550453=音乐&19550517=互联网&19550937=健康&19550560=创业&19551557=设计&19556664=科技&19552266=文化&19551556=旅行&19553298=自然科学&19551404=投资&19555457=商业&19560170=经济学&19551077=历史&19552192=健身&19550780=电子商务&19550994=游戏&19550874=法律&19553528=英语&19553128=减肥&19552204=性生活&19551388=摄影&19551915=汽车&19569420=冷知识&19556423=文学&19553176=教育&19550434=艺术&19560641=职业规划&19561709=用户体验设计&19641262=服饰搭配&19591985=动漫&19550228=知乎&19552706=运动&19575422=影视评论&19643259=美容护肤&19551325=产品经理&19550547=移动互联网&19550422=风险投资&19552414=淘宝网&19565870=谷歌&19555542=养生&19552497=睡眠&19552439=NBA&19554470=微信&19551075=中国历史&19555939=理财&19558435=英语学习&19555634=Android 开发&19550638=社交网络&19551805=烹饪&19550234=创业公司&19609455=金融&19551762=苹果公司&19603145=Android&19556950=物理学&19575492=生物学&19551137=美食&19562832=篮球&19550564=阅读&19554827=体育&19562906=化学&19559052=足球&19554825=职业发展&19562033=人际交往&19555513=生活方式&19556784=电影推荐&19579266=豆瓣&19564412=恋爱&19569848=生活常识&19805970=成人内容&19550581=学习&19556421=两性关系&19564408=爱情&19551469=旅游&19551003=金融学&19604128=医学&19602470=历史人物&19550573=Photoshop&19554051=装修&19556231=交互设计&19558321=人体&19556433=生理学&19568143=心理健康&19566266=学习方法&19561827=心理咨询&19556382=平面设计&19563625=天文学&19552079=面试&19559840=股票&19550340=Facebook&19645023=法律常识&19555480=大学生&19559209=用户界面设计&19557876=职场&19556353=大学&19556758=知识管理&19592882=美国电影&19551864=古典音乐&19552330=程序员&19551174=美剧&19563107=考研&19564504=人生规划&19551625=产品设计&19586269=中国古代历史&19550588=移动应用&19552249=饮食&19550714=摇滚乐&19624277=室内设计&19557815=赚钱&19588006=工作&19553732=单机游戏&19585936=神经学&19559937=留学&19550757=腾讯&19551424=政治&19582176=建筑设计&19577774=欧洲历史&19599479=世界历史&19561180=流行音乐&19551771=求职&19550895=投资银行&19562435=食品安全&19574423=中国近代史&19570354=证券&19551577=阿里巴巴集团&19560559=宇宙学&19554091=数学&19552417=支付宝&19587288=宏观经济学&19559915=科幻电影&19551167=北京美食&19554945=心理&19605346=英雄联盟&19563451=电子竞技&19552739=跑步&19556939=吉他&19569883=摄影技术&19561223=三国&19552212=设计师&19559947=家居&19559424=数据分析&19563977=医生&19592119=天体物理学&19551296=网络游戏&19580750=健身教练&19564862=抑郁症&19550685=用户体验&19559469=律师&19580586=高效学习&19578758=招聘&19551861=钢琴&19571583=犯罪&19555678=进化论&19585985=汽车行业&19561734=环境保护"; private static AllTopic mAllTopic; public static final String MODEL_KEY = "all_topics"; private static List<TopicModel> mAllTopics; public static AllTopic getInstance() { synchronized (AllTopic.class) { if (mAllTopic == null) { mAllTopic = new AllTopic(); } } return mAllTopic; } private AllTopic() { mAllTopics = new ArrayList<>(); } public List<TopicModel> getAllTopics(Context context) { if (mAllTopics == null || mAllTopics.size() == 0) { List<TopicModel> tempModels = (List<TopicModel>) SharePrefUtil.getObj(context, MODEL_KEY); if (tempModels != null) { mAllTopics.addAll(tempModels); } else { String[] cacheStr = cacheString.split("&"); for (int i = 0; i < cacheStr.length; i++) { TopicModel model = new TopicModel(Integer.valueOf(cacheStr[i].split("=")[0]), cacheStr[i].split("=")[1]); mAllTopics.add(model); SharePrefUtil.saveObj(context, MODEL_KEY, mAllTopics); } } } return mAllTopics; } public List<TopicModel> getTopics(Context context, int fromIndex, int toIndex) { return getAllTopics(context).subList(fromIndex, toIndex); } public void clearCache(Context context) { SharePrefUtil.removeItem(context, MODEL_KEY); mAllTopics.clear(); } public void saveTopics(Context context, List<TopicModel> list) { SharePrefUtil.saveObj(context, MODEL_KEY, list); mAllTopics.clear(); mAllTopics.addAll(list); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/utils/CollectionUtils.java
app/src/main/java/com/jiang/android/zhihu_topanswer/utils/CollectionUtils.java
package com.jiang.android.zhihu_topanswer.utils; import com.jiang.android.zhihu_topanswer.db.Collection; import com.jiang.android.zhihu_topanswer.db.DbUtil; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.Func1; import static com.jiang.android.zhihu_topanswer.db.DbUtil.getOperatorsService; /** * Created by jiang on 2016/12/28. */ public class CollectionUtils { public static final int TYPE_ANSWERS = 1; public static final int TYPE_ANSWER = 2; private static CollectionUtils mCollection; private List<Collection> mLists; public static CollectionUtils getInstance() { synchronized (CollectionUtils.class) { if (mCollection == null) { synchronized (CollectionUtils.class) { mCollection = new CollectionUtils(); } } } return mCollection; } private CollectionUtils() { mLists = new ArrayList<>(); mLists.addAll(getOperatorsService().queryAll()); } public void saveItem(Collection model){ getOperatorsService().save(model); mLists.add(model); } public Observable<Collection> contailItem(final String url){ return Observable.from(mLists) .filter(new Func1<Collection, Boolean>() { @Override public Boolean call(Collection model) { return model.getUrl().equals(url); } }); } public void removeItem(String mQuestionUrl) { for (int i = 0; i < mLists.size(); i++) { if(mLists.get(i).getUrl().equals(mQuestionUrl)){ List<Collection> list = DbUtil.getOperatorsService().query(" where url=?",mLists.get(i).getUrl()); if(list!= null && list.size()>0){ DbUtil.getOperatorsService().delete(list); } mLists.remove(i); return; } } } public List<Collection> getCollection(){ return mLists; } public void clear() { getOperatorsService().deleteAll(); mLists.clear(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/utils/JSoupUtils.java
app/src/main/java/com/jiang/android/zhihu_topanswer/utils/JSoupUtils.java
package com.jiang.android.zhihu_topanswer.utils; import android.text.TextUtils; import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.model.TopicAnswers; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by jiang on 2016/12/28. */ public class JSoupUtils { private static final String TAG = "JSoupUtils"; /** * 首页获取列表信息 * @param document * @return */ public static List<TopicAnswers> getTopicList(Document document) { Elements contentLinks = document.select("div.content"); List<TopicAnswers> list = new ArrayList<>(); Iterator iterator = contentLinks.iterator(); while (iterator.hasNext()) { TopicAnswers answers = new TopicAnswers(); Element body = (Element) iterator.next(); Elements questionLinks = body.select("a.question_link"); if (questionLinks.iterator().hasNext()) { Element questionLink = questionLinks.iterator().next(); answers.setTitle(questionLink.text()); answers.setUrl("https://www.zhihu.com" + questionLink.attr("href")); } Elements votes = body.select("a.zm-item-vote-count.js-expand.js-vote-count"); if (votes.size() > 0) { if (votes.iterator().hasNext()) { Element aVotes = votes.iterator().next(); answers.setVote(aVotes.text()); } } Elements divs = body.select("div.zh-summary.summary.clearfix"); String descBody = divs.text(); if (descBody.length() > 4) { descBody = descBody.substring(0, descBody.length() - 4); } answers.setBody(descBody); if (divs.size() > 0) { if (divs.iterator().hasNext()) { Element aDiv = divs.iterator().next(); Element img = aDiv.children().first(); if (img.tagName().equals("img")) { String imgUrl = img.attr("src"); answers.setImg(imgUrl); } } } if (!TextUtils.isEmpty(answers.getTitle()) && !TextUtils.isEmpty(answers.getUrl())) { L.i(TAG, answers.toString()); list.add(answers); } } return list; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/main/java/com/jiang/android/zhihu_topanswer/view/SelectPopupWindow.java
app/src/main/java/com/jiang/android/zhihu_topanswer/view/SelectPopupWindow.java
package com.jiang.android.zhihu_topanswer.view; import android.app.Activity; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; import com.jiang.android.architecture.adapter.BaseAdapter; import com.jiang.android.zhihu_topanswer.R; /** * Created by jiang on 2016/12/24. */ public class SelectPopupWindow extends PopupWindow { private final View mMenuView; private final RecyclerView mRecyclerView; public SelectPopupWindow(Activity context) { super(context); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mMenuView = inflater.inflate(R.layout.popwindow_layout, null); mRecyclerView = (RecyclerView) mMenuView.findViewById(R.id.pop_layout1); this.setContentView(mMenuView); this.setWidth(ViewGroup.LayoutParams.FILL_PARENT); this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); this.setFocusable(true); ColorDrawable dw = new ColorDrawable(0xb0000000); this.setBackgroundDrawable(dw); setOutsideTouchable(false); } public void setAdapter(BaseAdapter adapter) { GridLayoutManager layoutManager = new GridLayoutManager(mRecyclerView.getContext(), 4); layoutManager.setAutoMeasureEnabled(true); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setAdapter(adapter); } public RecyclerView getRecyclerView() { return mRecyclerView; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/app/src/androidTest/java/com/jiang/android/zhihu_topanswer/ExampleInstrumentedTest.java
app/src/androidTest/java/com/jiang/android/zhihu_topanswer/ExampleInstrumentedTest.java
package com.jiang.android.zhihu_topanswer; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.jiang.android.zhihu_topanswer", appContext.getPackageName()); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/AppManager.java
architecture/src/main/java/com/jiang/android/architecture/AppManager.java
package com.jiang.android.architecture; import android.app.Activity; import android.content.Context; import android.text.TextUtils; import java.util.Stack; public class AppManager { private static Stack<Activity> activityStack; private static AppManager instance; private AppManager() { } /** * 单一实例 */ public static AppManager getAppManager() { if (instance == null) { instance = new AppManager(); } return instance; } /** * 添加Activity到堆栈 */ public void addActivity(Activity activity) { if (activityStack == null) { activityStack = new Stack<>(); } activityStack.add(activity); } /** * 包括包名的类 * * @param className * @return */ public boolean existClass(String className) { if (activityStack == null || activityStack.size() == 0 || TextUtils.isEmpty(className)) return false; for (int i = 0; i < activityStack.size(); i++) { String name = activityStack.get(i).getClass().getName(); if (className.equals(name)) return true; } return false; } /** * 获取当前Activity(堆栈中最后一个压入的) */ public Activity currentActivity() { Activity activity = activityStack.lastElement(); return activity; } public int size() { return (activityStack == null || activityStack.size() == 0) ? 0 : activityStack.size(); } /** * 结束当前Activity(堆栈中最后一个压入的) */ public void finishActivity() { Activity activity = activityStack.lastElement(); finishActivity(activity); } /** * 结束指定的Activity */ public void finishActivity(Activity activity) { if (activity != null) { activityStack.remove(activity); activity.finish(); } } public void removeActivity(Activity activity) { if (activity != null) { activityStack.remove(activity); } } /** * 结束指定类名的Activity */ public void finishActivity(Class<?> cls) { for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { finishActivity(activity); } } } /** * 结束所有Activity */ public void finishAllActivity() { if (activityStack == null || activityStack.size() == 0) return; for (int i = 0, size = activityStack.size(); i < size; i++) { if (null != activityStack.get(i)) { activityStack.get(i).finish(); } } activityStack.clear(); } /** * 退出应用程序 */ public void exit(Context context) { try { finishAllActivity(); } catch (Exception e) { e.printStackTrace(); } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/App.java
architecture/src/main/java/com/jiang/android/architecture/App.java
package com.jiang.android.architecture; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; import com.squareup.leakcanary.LeakCanary; /** * Created by jiang on 2016/11/23. */ public class App extends Application { @Override public void onCreate() { super.onCreate(); LeakCanary.install(this); initFresco(); } private void initFresco() { Fresco.initialize(this); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/rxsupport/RxFragment.java
architecture/src/main/java/com/jiang/android/architecture/rxsupport/RxFragment.java
package com.jiang.android.architecture.rxsupport; import android.os.Bundle; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.View; import com.trello.rxlifecycle.LifecycleProvider; import com.trello.rxlifecycle.LifecycleTransformer; import com.trello.rxlifecycle.RxLifecycle; import com.trello.rxlifecycle.android.FragmentEvent; import com.trello.rxlifecycle.android.RxLifecycleAndroid; import rx.Observable; import rx.subjects.BehaviorSubject; public class RxFragment extends Fragment implements LifecycleProvider<FragmentEvent> { private final BehaviorSubject<FragmentEvent> lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable<FragmentEvent> lifecycle() { return lifecycleSubject.asObservable(); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/rxsupport/RxFragmentActivity.java
architecture/src/main/java/com/jiang/android/architecture/rxsupport/RxFragmentActivity.java
/* * 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.jiang.android.architecture.rxsupport; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import com.trello.rxlifecycle.LifecycleProvider; import com.trello.rxlifecycle.LifecycleTransformer; import com.trello.rxlifecycle.RxLifecycle; import com.trello.rxlifecycle.android.ActivityEvent; import com.trello.rxlifecycle.android.RxLifecycleAndroid; import rx.Observable; import rx.subjects.BehaviorSubject; public abstract class RxFragmentActivity extends FragmentActivity implements LifecycleProvider<ActivityEvent> { private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable<ActivityEvent> lifecycle() { return lifecycleSubject.asObservable(); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindToLifecycle() { return RxLifecycleAndroid.bindActivity(lifecycleSubject); } @Override @CallSuper protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(ActivityEvent.CREATE); } @Override @CallSuper protected void onStart() { super.onStart(); lifecycleSubject.onNext(ActivityEvent.START); } @Override @CallSuper protected void onResume() { super.onResume(); lifecycleSubject.onNext(ActivityEvent.RESUME); } @Override @CallSuper protected void onPause() { lifecycleSubject.onNext(ActivityEvent.PAUSE); super.onPause(); } @Override @CallSuper protected void onStop() { lifecycleSubject.onNext(ActivityEvent.STOP); super.onStop(); } @Override @CallSuper protected void onDestroy() { lifecycleSubject.onNext(ActivityEvent.DESTROY); super.onDestroy(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/rxsupport/RxAppCompatActivity.java
architecture/src/main/java/com/jiang/android/architecture/rxsupport/RxAppCompatActivity.java
package com.jiang.android.architecture.rxsupport; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.jiang.android.architecture.AppManager; import com.trello.rxlifecycle.LifecycleProvider; import com.trello.rxlifecycle.LifecycleTransformer; import com.trello.rxlifecycle.RxLifecycle; import com.trello.rxlifecycle.android.ActivityEvent; import com.trello.rxlifecycle.android.RxLifecycleAndroid; import rx.Observable; import rx.subjects.BehaviorSubject; public class RxAppCompatActivity extends AppCompatActivity implements LifecycleProvider<ActivityEvent> { private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable<ActivityEvent> lifecycle() { return lifecycleSubject.asObservable(); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindToLifecycle() { return RxLifecycleAndroid.bindActivity(lifecycleSubject); } @Override @CallSuper protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); AppManager.getAppManager().addActivity(this); lifecycleSubject.onNext(ActivityEvent.CREATE); } @Override @CallSuper protected void onStart() { super.onStart(); lifecycleSubject.onNext(ActivityEvent.START); } @Override @CallSuper protected void onResume() { super.onResume(); lifecycleSubject.onNext(ActivityEvent.RESUME); } @Override @CallSuper protected void onPause() { lifecycleSubject.onNext(ActivityEvent.PAUSE); super.onPause(); } @Override @CallSuper protected void onStop() { lifecycleSubject.onNext(ActivityEvent.STOP); super.onStop(); } @Override @CallSuper protected void onDestroy() { lifecycleSubject.onNext(ActivityEvent.DESTROY); AppManager.getAppManager().removeActivity(this); super.onDestroy(); } public void toast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/L.java
architecture/src/main/java/com/jiang/android/architecture/utils/L.java
package com.jiang.android.architecture.utils; import android.util.Log; import com.apkfuns.logutils.LogUtils; /** * Created by jiang on 2016/11/23. */ public class L { private static boolean isDEBUG = true; public static void debug(boolean debug) { isDEBUG = debug; } public static void i(String value) { if (isDEBUG) { LogUtils.i(value); } } public static void i(String key, String value) { if (isDEBUG) { Log.i(key, value); } } public static void d(String value) { if (isDEBUG) { LogUtils.d(value); } } public static void e(String value) { if (isDEBUG) { LogUtils.e(value); } } public static void v(String value) { if (isDEBUG) { LogUtils.v(value); } } /** * 打印json * * @param value */ public static void json(String value) { if (isDEBUG) { LogUtils.json(value); } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/CommonUtils.java
architecture/src/main/java/com/jiang/android/architecture/utils/CommonUtils.java
package com.jiang.android.architecture.utils; import android.content.Context; import android.text.TextUtils; import android.text.format.Formatter; import java.util.Random; import java.util.UUID; /** * Created by jiang on 2016/11/23. */ public class CommonUtils { public static String getNumberRadim(int n) { if (n < 1 || n > 10) { throw new IllegalArgumentException("cannot random " + n + " bit number"); } Random ran = new Random(); if (n == 1) { return String.valueOf(ran.nextInt(10)); } int bitField = 0; char[] chs = new char[n]; for (int i = 0; i < n; i++) { while (true) { int k = ran.nextInt(10); if ((bitField & (1 << k)) == 0) { bitField |= 1 << k; chs[i] = (char) (k + '0'); break; } } } return new String(chs); } public static String getGUID() { // 创建 GUID 对象 UUID uuid = UUID.randomUUID(); // 得到对象产生的ID String a = uuid.toString(); // 转换为大写 a = a.toUpperCase(); // 替换 - a = a.replaceAll("-", ""); L.i(a); return a; } /** * 数字转换中文 */ public static String int2Chinese(int i) { String[] zh = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"}; String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十"}; String str = ""; StringBuffer sb = new StringBuffer(String.valueOf(i)); sb = sb.reverse(); int r = 0; int l = 0; for (int j = 0; j < sb.length(); j++) { /** * 当前数字 */ r = Integer.valueOf(sb.substring(j, j + 1)); if (j != 0) /** * 上一个数字 */ l = Integer.valueOf(sb.substring(j - 1, j)); if (j == 0) { if (r != 0 || sb.length() == 1) str = zh[r]; continue; } if (j == 1 || j == 2 || j == 3 || j == 5 || j == 6 || j == 7 || j == 9) { if (r != 0) str = zh[r] + unit[j] + str; else if (l != 0) str = zh[r] + str; continue; } if (j == 4 || j == 8) { str = unit[j] + str; if ((l != 0 && r == 0) || r != 0) str = zh[r] + str; continue; } } return str; } public static String byte2Common(Context context, String fsize) { if (TextUtils.isEmpty(fsize)) { return ""; } Long sizeLong = Long.parseLong(fsize); return Formatter.formatFileSize(context, sizeLong); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/LuBan.java
architecture/src/main/java/com/jiang/android/architecture/utils/LuBan.java
package com.jiang.android.architecture.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.support.annotation.NonNull; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import static com.jiang.android.architecture.utils.Preconditions.checkNotNull; /** * Created by jiang on 2016/11/18. */ public class LuBan { private static final String TAG = "LuBan"; private static String DEFAULT_DISK_CACHE_DIR = "luban_disk_cache"; private final File mCacheDir; public LuBan(Context context) { mCacheDir = getPhotoCacheDir(context); } private static synchronized File getPhotoCacheDir(Context context) { return getPhotoCacheDir(context, LuBan.DEFAULT_DISK_CACHE_DIR); } private static File getPhotoCacheDir(Context context, String cacheName) { File cacheDir = context.getCacheDir(); if (cacheDir != null) { File result = new File(cacheDir, cacheName); if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) { // File wasn't able to create a directory, or the result exists but not a directory return null; } File noMedia = new File(cacheDir + "/.nomedia"); if (!noMedia.mkdirs() && (!noMedia.exists() || !noMedia.isDirectory())) { return null; } return result; } if (Log.isLoggable(TAG, Log.ERROR)) { Log.e(TAG, "default disk cache dir is null"); } return null; } private static synchronized File getPhotoCacheDir() { return PathUtil.getInstance().getImagePath(); } public int[] getImageSize(String imagePath) { int[] res = new int[2]; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inSampleSize = 1; BitmapFactory.decodeFile(imagePath, options); res[0] = options.outWidth; res[1] = options.outHeight; return res; } public File firstCompress(@NonNull File file) { int minSize = 60; int longSide = 720; int shortSide = 1280; String filePath = file.getAbsolutePath(); String thumbFilePath = mCacheDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + "_" + CommonUtils.getNumberRadim(4) + ".jpg"; long size = 0; long maxSize = file.length() / 5; int angle = getImageSpinAngle(filePath); int[] imgSize = getImageSize(filePath); int width = 0, height = 0; if (imgSize[0] <= imgSize[1]) { double scale = (double) imgSize[0] / (double) imgSize[1]; if (scale <= 1.0 && scale > 0.5625) { width = imgSize[0] > shortSide ? shortSide : imgSize[0]; height = width * imgSize[1] / imgSize[0]; size = minSize; } else if (scale <= 0.5625) { height = imgSize[1] > longSide ? longSide : imgSize[1]; width = height * imgSize[0] / imgSize[1]; size = maxSize; } } else { double scale = (double) imgSize[1] / (double) imgSize[0]; if (scale <= 1.0 && scale > 0.5625) { height = imgSize[1] > shortSide ? shortSide : imgSize[1]; width = height * imgSize[0] / imgSize[1]; size = minSize; } else if (scale <= 0.5625) { width = imgSize[0] > longSide ? longSide : imgSize[0]; height = width * imgSize[1] / imgSize[0]; size = maxSize; } } return compress(filePath, thumbFilePath, width, height, angle, size); } public File thirdCompress(@NonNull File file) { String thumb = mCacheDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + "_" + CommonUtils.getNumberRadim(4) + ".jpg"; double size; String filePath = file.getAbsolutePath(); int angle = getImageSpinAngle(filePath); int width = getImageSize(filePath)[0]; int height = getImageSize(filePath)[1]; int thumbW = width % 2 == 1 ? width + 1 : width; int thumbH = height % 2 == 1 ? height + 1 : height; width = thumbW > thumbH ? thumbH : thumbW; height = thumbW > thumbH ? thumbW : thumbH; double scale = ((double) width / height); if (scale <= 1 && scale > 0.5625) { if (height < 1664) { if (file.length() / 1024 < 150) return file; size = (width * height) / Math.pow(1664, 2) * 150; size = size < 60 ? 60 : size; } else if (height >= 1664 && height < 4990) { thumbW = width / 2; thumbH = height / 2; size = (thumbW * thumbH) / Math.pow(2495, 2) * 300; size = size < 60 ? 60 : size; } else if (height >= 4990 && height < 10240) { thumbW = width / 4; thumbH = height / 4; size = (thumbW * thumbH) / Math.pow(2560, 2) * 300; size = size < 100 ? 100 : size; } else { int multiple = height / 1280 == 0 ? 1 : height / 1280; thumbW = width / multiple; thumbH = height / multiple; size = (thumbW * thumbH) / Math.pow(2560, 2) * 300; size = size < 100 ? 100 : size; } } else if (scale <= 0.5625 && scale > 0.5) { if (height < 1280 && file.length() / 1024 < 200) return file; int multiple = height / 1280 == 0 ? 1 : height / 1280; thumbW = width / multiple; thumbH = height / multiple; size = (thumbW * thumbH) / (1440.0 * 2560.0) * 400; size = size < 100 ? 100 : size; } else { int multiple = (int) Math.ceil(height / (1280.0 / scale)); thumbW = width / multiple; thumbH = height / multiple; size = ((thumbW * thumbH) / (1280.0 * (1280 / scale))) * 500; size = size < 100 ? 100 : size; } return compress(filePath, thumb, thumbW, thumbH, angle, (long) size); } private File compress(String largeImagePath, String thumbFilePath, int width, int height, int angle, long size) { Bitmap thbBitmap = compress(largeImagePath, width, height); thbBitmap = rotatingImage(angle, thbBitmap); return saveImage(thumbFilePath, thbBitmap, size); } private Bitmap compress(String imagePath, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, options); int outH = options.outHeight; int outW = options.outWidth; int inSampleSize = 1; if (outH > height || outW > width) { int halfH = outH / 2; int halfW = outW / 2; while ((halfH / inSampleSize) > height && (halfW / inSampleSize) > width) { inSampleSize *= 2; } } options.inSampleSize = inSampleSize; options.inJustDecodeBounds = false; int heightRatio = (int) Math.ceil(options.outHeight / (float) height); int widthRatio = (int) Math.ceil(options.outWidth / (float) width); if (heightRatio > 1 || widthRatio > 1) { if (heightRatio > widthRatio) { options.inSampleSize = heightRatio; } else { options.inSampleSize = widthRatio; } } options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(imagePath, options); } private int getImageSpinAngle(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } /** * 旋转图片 * rotate the image with specified angle * * @param angle the angle will be rotating 旋转的角度 * @param bitmap target image 目标图片 */ private static Bitmap rotatingImage(int angle, Bitmap bitmap) { //rotate image Matrix matrix = new Matrix(); matrix.postRotate(angle); //create a new image return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } /** * 保存图片到指定路径 * Save image with specified size * * @param filePath the image file save path 储存路径 * @param bitmap the image what be save 目标图片 * @param size the file size of image 期望大小 */ private File saveImage(String filePath, Bitmap bitmap, long size) { checkNotNull(bitmap, TAG + "bitmap cannot be null"); File result = new File(filePath.substring(0, filePath.lastIndexOf("/"))); if (!result.exists() && !result.mkdirs()) return null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); int options = 100; bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream); while (stream.toByteArray().length / 1024 > size && options > 6) { stream.reset(); options -= 6; bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream); } bitmap.recycle(); try { FileOutputStream fos = new FileOutputStream(filePath); fos.write(stream.toByteArray()); fos.flush(); fos.close(); stream.close(); } catch (IOException e) { e.printStackTrace(); } return new File(filePath); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/SharePrefUtil.java
architecture/src/main/java/com/jiang/android/architecture/utils/SharePrefUtil.java
/** * created by jiang, 11/9/15 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.utils; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import org.apache.commons.codec.binary.Base64; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SharePrefUtil { private static String tag = SharePrefUtil.class.getSimpleName(); private static String SP_NAME = "config"; private static SharedPreferences sp; public static void initSP_NAME(String sp_name) { SP_NAME = sp_name; } /** * 保存布尔值 * * @param context * @param key * @param value */ public static void saveBoolean(Context context, String key, boolean value) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); sp.edit().putBoolean(key, value).commit(); } /** * 保存字符串 * * @param context * @param key * @param value */ public static void saveString(Context context, String key, String value) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); sp.edit().putString(key, value).commit(); } public static void clear(Context context) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); sp.edit().clear().commit(); } public static void removeItem(Context context, String key) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); sp.edit().remove(key).commit(); } /** * 保存long型 * * @param context * @param key * @param value */ public static void saveLong(Context context, String key, long value) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); sp.edit().putLong(key, value).commit(); } /** * 保存int型 * * @param context * @param key * @param value */ public static void saveInt(Context context, String key, int value) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); sp.edit().putInt(key, value).commit(); } /** * 保存float型 * * @param context * @param key * @param value */ public static void saveFloat(Context context, String key, float value) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); sp.edit().putFloat(key, value).commit(); } /** * 获取字符值 * * @param context * @param key * @param defValue * @return */ public static String getString(Context context, String key, String defValue) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); return sp.getString(key, defValue); } /** * 获取int值 * * @param context * @param key * @param defValue * @return */ public static int getInt(Context context, String key, int defValue) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); return sp.getInt(key, defValue); } /** * 获取long值 * * @param context * @param key * @param defValue * @return */ public static long getLong(Context context, String key, long defValue) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); return sp.getLong(key, defValue); } /** * 获取float值 * * @param context * @param key * @param defValue * @return */ public static float getFloat(Context context, String key, float defValue) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); return sp.getFloat(key, defValue); } /** * 获取布尔值 * * @param context * @param key * @param defValue * @return */ public static boolean getBoolean(Context context, String key, boolean defValue) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); return sp.getBoolean(key, defValue); } /** * 将对象进行base64编码后保存到SharePref中 * * @param context * @param key * @param object */ public static void saveObj(Context context, String key, Object object) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(object); // 将对象的转为base64码 String objBase64 = new String(Base64.encodeBase64(baos.toByteArray())); sp.edit().putString(key, objBase64).commit(); oos.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 将SharePref中经过base64编码的对象读取出来 * * @return */ public static Object getObj(Context context, String key) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); String objBase64 = sp.getString(key, null); if (TextUtils.isEmpty(objBase64)) return null; // 对Base64格式的字符串进行解码 byte[] base64Bytes = Base64.decodeBase64(objBase64.getBytes()); ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes); ObjectInputStream ois; Object obj = null; try { ois = new ObjectInputStream(bais); obj = (Object) ois.readObject(); ois.close(); } catch (Exception e) { e.printStackTrace(); } return obj; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/DensityUtils.java
architecture/src/main/java/com/jiang/android/architecture/utils/DensityUtils.java
package com.jiang.android.architecture.utils; import android.app.Activity; import android.content.Context; import android.util.DisplayMetrics; /** * Created by jiang on 2016/11/23. */ public class DensityUtils { public static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** * 将sp值转换为px值,保证文字大小不变 * * @param spValue (DisplayMetrics类中属性scaledDensity) * @return */ public static int sp2px(Context context, float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } /** * @param activity * @return 获得屏幕的宽度 px */ public static int getWidthPixels(Activity activity) { DisplayMetrics dm = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(dm); return dm.widthPixels; } /** * @param activity * @return 获得屏幕的高度 px */ public static int getHeightPixels(Activity activity) { DisplayMetrics dm = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(dm); return dm.heightPixels; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/EncryptUtils.java
architecture/src/main/java/com/jiang/android/architecture/utils/EncryptUtils.java
package com.jiang.android.architecture.utils; import android.text.TextUtils; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.DigestInputStream; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/8/2 * desc : 加密解密相关的工具类 * </pre> */ public class EncryptUtils { private EncryptUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /*********************** 哈希加密相关 ***********************/ /** * MD2加密 * * @param data 明文字符串 * @return 16进制密文 */ public static String encryptMD2ToString(String data) { return encryptMD2ToString(data.getBytes()); } /** * MD2加密 * * @param data 明文字节数组 * @return 16进制密文 */ public static String encryptMD2ToString(byte[] data) { return bytes2HexString(encryptMD2(data)); } /** * MD2加密 * * @param data 明文字节数组 * @return 密文字节数组 */ public static byte[] encryptMD2(byte[] data) { return hashTemplate(data, "MD2"); } /** * MD5加密 * * @param data 明文字符串 * @return 16进制密文 */ public static String encryptMD5ToString(String data) { return encryptMD5ToString(data.getBytes()); } /** * MD5加密 * * @param data 明文字符串 * @param salt 盐 * @return 16进制加盐密文 */ public static String encryptMD5ToString(String data, String salt) { return bytes2HexString(encryptMD5((data + salt).getBytes())); } /** * MD5加密 * * @param data 明文字节数组 * @return 16进制密文 */ public static String encryptMD5ToString(byte[] data) { return bytes2HexString(encryptMD5(data)); } /** * MD5加密 * * @param data 明文字节数组 * @param salt 盐字节数组 * @return 16进制加盐密文 */ public static String encryptMD5ToString(byte[] data, byte[] salt) { if (data == null || salt == null) return null; byte[] dataSalt = new byte[data.length + salt.length]; System.arraycopy(data, 0, dataSalt, 0, data.length); System.arraycopy(salt, 0, dataSalt, data.length, salt.length); return bytes2HexString(encryptMD5(dataSalt)); } /** * MD5加密 * * @param data 明文字节数组 * @return 密文字节数组 */ public static byte[] encryptMD5(byte[] data) { return hashTemplate(data, "MD5"); } /** * MD5加密文件 * * @param filePath 文件路径 * @return 文件的16进制密文 */ public static String encryptMD5File2String(String filePath) { File file = TextUtils.isEmpty(filePath) ? null : new File(filePath); return encryptMD5File2String(file); } /** * MD5加密文件 * * @param filePath 文件路径 * @return 文件的MD5校验码 */ public static byte[] encryptMD5File(String filePath) { File file = TextUtils.isEmpty(filePath) ? null : new File(filePath); return encryptMD5File(file); } /** * MD5加密文件 * * @param file 文件 * @return 文件的16进制密文 */ public static String encryptMD5File2String(File file) { return bytes2HexString(encryptMD5File(file)); } /** * MD5加密文件 * * @param file 文件 * @return 文件的MD5校验码 */ public static byte[] encryptMD5File(File file) { if (file == null) return null; FileInputStream fis = null; DigestInputStream digestInputStream; try { fis = new FileInputStream(file); MessageDigest md = MessageDigest.getInstance("MD5"); digestInputStream = new DigestInputStream(fis, md); byte[] buffer = new byte[256 * 1024]; while (digestInputStream.read(buffer) > 0) ; md = digestInputStream.getMessageDigest(); return md.digest(); } catch (NoSuchAlgorithmException | IOException e) { e.printStackTrace(); return null; } finally { closeIO(fis); } } private static void closeIO(Closeable... closeables) { if (closeables == null) return; for (Closeable closeable : closeables) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * SHA1加密 * * @param data 明文字符串 * @return 16进制密文 */ public static String encryptSHA1ToString(String data) { return encryptSHA1ToString(data.getBytes()); } /** * SHA1加密 * * @param data 明文字节数组 * @return 16进制密文 */ public static String encryptSHA1ToString(byte[] data) { return bytes2HexString(encryptSHA1(data)); } /** * SHA1加密 * * @param data 明文字节数组 * @return 密文字节数组 */ public static byte[] encryptSHA1(byte[] data) { return hashTemplate(data, "SHA1"); } /** * SHA224加密 * * @param data 明文字符串 * @return 16进制密文 */ public static String encryptSHA224ToString(String data) { return encryptSHA224ToString(data.getBytes()); } /** * SHA224加密 * * @param data 明文字节数组 * @return 16进制密文 */ public static String encryptSHA224ToString(byte[] data) { return bytes2HexString(encryptSHA224(data)); } /** * SHA224加密 * * @param data 明文字节数组 * @return 密文字节数组 */ public static byte[] encryptSHA224(byte[] data) { return hashTemplate(data, "SHA224"); } /** * SHA256加密 * * @param data 明文字符串 * @return 16进制密文 */ public static String encryptSHA256ToString(String data) { return encryptSHA256ToString(data.getBytes()); } /** * SHA256加密 * * @param data 明文字节数组 * @return 16进制密文 */ public static String encryptSHA256ToString(byte[] data) { return bytes2HexString(encryptSHA256(data)); } /** * SHA256加密 * * @param data 明文字节数组 * @return 密文字节数组 */ public static byte[] encryptSHA256(byte[] data) { return hashTemplate(data, "SHA256"); } /** * SHA384加密 * * @param data 明文字符串 * @return 16进制密文 */ public static String encryptSHA384ToString(String data) { return encryptSHA384ToString(data.getBytes()); } /** * SHA384加密 * * @param data 明文字节数组 * @return 16进制密文 */ public static String encryptSHA384ToString(byte[] data) { return bytes2HexString(encryptSHA384(data)); } /** * SHA384加密 * * @param data 明文字节数组 * @return 密文字节数组 */ public static byte[] encryptSHA384(byte[] data) { return hashTemplate(data, "SHA384"); } /** * SHA512加密 * * @param data 明文字符串 * @return 16进制密文 */ public static String encryptSHA512ToString(String data) { return encryptSHA512ToString(data.getBytes()); } /** * SHA512加密 * * @param data 明文字节数组 * @return 16进制密文 */ public static String encryptSHA512ToString(byte[] data) { return bytes2HexString(encryptSHA512(data)); } /** * SHA512加密 * * @param data 明文字节数组 * @return 密文字节数组 */ public static byte[] encryptSHA512(byte[] data) { return hashTemplate(data, "SHA512"); } /** * hash加密模板 * * @param data 数据 * @param algorithm 加密算法 * @return 密文字节数组 */ private static byte[] hashTemplate(byte[] data, String algorithm) { if (data == null || data.length <= 0) return null; try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(data); return md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * HmacMD5加密 * * @param data 明文字符串 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacMD5ToString(String data, String key) { return encryptHmacMD5ToString(data.getBytes(), key.getBytes()); } /** * HmacMD5加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacMD5ToString(byte[] data, byte[] key) { return bytes2HexString(encryptHmacMD5(data, key)); } /** * HmacMD5加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 密文字节数组 */ public static byte[] encryptHmacMD5(byte[] data, byte[] key) { return hmacTemplate(data, key, "HmacMD5"); } /** * HmacSHA1加密 * * @param data 明文字符串 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA1ToString(String data, String key) { return encryptHmacSHA1ToString(data.getBytes(), key.getBytes()); } /** * HmacSHA1加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA1ToString(byte[] data, byte[] key) { return bytes2HexString(encryptHmacSHA1(data, key)); } /** * HmacSHA1加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 密文字节数组 */ public static byte[] encryptHmacSHA1(byte[] data, byte[] key) { return hmacTemplate(data, key, "HmacSHA1"); } /** * HmacSHA224加密 * * @param data 明文字符串 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA224ToString(String data, String key) { return encryptHmacSHA224ToString(data.getBytes(), key.getBytes()); } /** * HmacSHA224加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA224ToString(byte[] data, byte[] key) { return bytes2HexString(encryptHmacSHA224(data, key)); } /** * HmacSHA224加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 密文字节数组 */ public static byte[] encryptHmacSHA224(byte[] data, byte[] key) { return hmacTemplate(data, key, "HmacSHA224"); } /** * HmacSHA256加密 * * @param data 明文字符串 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA256ToString(String data, String key) { return encryptHmacSHA256ToString(data.getBytes(), key.getBytes()); } /** * HmacSHA256加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA256ToString(byte[] data, byte[] key) { return bytes2HexString(encryptHmacSHA256(data, key)); } /** * HmacSHA256加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 密文字节数组 */ public static byte[] encryptHmacSHA256(byte[] data, byte[] key) { return hmacTemplate(data, key, "HmacSHA256"); } /** * HmacSHA384加密 * * @param data 明文字符串 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA384ToString(String data, String key) { return encryptHmacSHA384ToString(data.getBytes(), key.getBytes()); } /** * HmacSHA384加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA384ToString(byte[] data, byte[] key) { return bytes2HexString(encryptHmacSHA384(data, key)); } /** * HmacSHA384加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 密文字节数组 */ public static byte[] encryptHmacSHA384(byte[] data, byte[] key) { return hmacTemplate(data, key, "HmacSHA384"); } /** * HmacSHA512加密 * * @param data 明文字符串 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA512ToString(String data, String key) { return encryptHmacSHA512ToString(data.getBytes(), key.getBytes()); } /** * HmacSHA512加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 16进制密文 */ public static String encryptHmacSHA512ToString(byte[] data, byte[] key) { return bytes2HexString(encryptHmacSHA512(data, key)); } /** * HmacSHA512加密 * * @param data 明文字节数组 * @param key 秘钥 * @return 密文字节数组 */ public static byte[] encryptHmacSHA512(byte[] data, byte[] key) { return hmacTemplate(data, key, "HmacSHA512"); } /** * Hmac加密模板 * * @param data 数据 * @param key 秘钥 * @param algorithm 加密算法 * @return 密文字节数组 */ private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) { if (data == null || data.length == 0 || key == null || key.length == 0) return null; try { SecretKeySpec secretKey = new SecretKeySpec(key, algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); return mac.doFinal(data); } catch (InvalidKeyException | NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /************************ DES加密相关 ***********************/ /** * DES转变 * <p>法算法名称/加密模式/填充方式</p> * <p>加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB</p> * <p>填充方式有:NoPadding、ZerosPadding、PKCS5Padding</p> */ public static String DES_Transformation = "DES/ECB/NoPadding"; private static final String DES_Algorithm = "DES"; /** * DES加密后转为Base64编码 * * @param data 明文 * @param key 8字节秘钥 * @return Base64密文 */ public static byte[] encryptDES2Base64(byte[] data, byte[] key) { return EncodeUtils.base64Encode(encryptDES(data, key)); } /** * DES加密后转为16进制 * * @param data 明文 * @param key 8字节秘钥 * @return 16进制密文 */ public static String encryptDES2HexString(byte[] data, byte[] key) { return bytes2HexString(encryptDES(data, key)); } /** * DES加密 * * @param data 明文 * @param key 8字节秘钥 * @return 密文 */ public static byte[] encryptDES(byte[] data, byte[] key) { return desTemplate(data, key, DES_Algorithm, DES_Transformation, true); } /** * DES解密Base64编码密文 * * @param data Base64编码密文 * @param key 8字节秘钥 * @return 明文 */ public static byte[] decryptBase64DES(byte[] data, byte[] key) { return decryptDES(EncodeUtils.base64Decode(data), key); } /** * DES解密16进制密文 * * @param data 16进制密文 * @param key 8字节秘钥 * @return 明文 */ public static byte[] decryptHexStringDES(String data, byte[] key) { return decryptDES(hexString2Bytes(data), key); } /** * DES解密 * * @param data 密文 * @param key 8字节秘钥 * @return 明文 */ public static byte[] decryptDES(byte[] data, byte[] key) { return desTemplate(data, key, DES_Algorithm, DES_Transformation, false); } /************************ 3DES加密相关 ***********************/ /** * 3DES转变 * <p>法算法名称/加密模式/填充方式</p> * <p>加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB</p> * <p>填充方式有:NoPadding、ZerosPadding、PKCS5Padding</p> */ public static String TripleDES_Transformation = "DESede/ECB/NoPadding"; private static final String TripleDES_Algorithm = "DESede"; /** * 3DES加密后转为Base64编码 * * @param data 明文 * @param key 24字节秘钥 * @return Base64密文 */ public static byte[] encrypt3DES2Base64(byte[] data, byte[] key) { return EncodeUtils.base64Encode(encrypt3DES(data, key)); } /** * 3DES加密后转为16进制 * * @param data 明文 * @param key 24字节秘钥 * @return 16进制密文 */ public static String encrypt3DES2HexString(byte[] data, byte[] key) { return bytes2HexString(encrypt3DES(data, key)); } /** * 3DES加密 * * @param data 明文 * @param key 24字节密钥 * @return 密文 */ public static byte[] encrypt3DES(byte[] data, byte[] key) { return desTemplate(data, key, TripleDES_Algorithm, TripleDES_Transformation, true); } /** * 3DES解密Base64编码密文 * * @param data Base64编码密文 * @param key 24字节秘钥 * @return 明文 */ public static byte[] decryptBase64_3DES(byte[] data, byte[] key) { return decrypt3DES(EncodeUtils.base64Decode(data), key); } /** * 3DES解密16进制密文 * * @param data 16进制密文 * @param key 24字节秘钥 * @return 明文 */ public static byte[] decryptHexString3DES(String data, byte[] key) { return decrypt3DES(hexString2Bytes(data), key); } /** * 3DES解密 * * @param data 密文 * @param key 24字节密钥 * @return 明文 */ public static byte[] decrypt3DES(byte[] data, byte[] key) { return desTemplate(data, key, TripleDES_Algorithm, TripleDES_Transformation, false); } /************************ AES加密相关 ***********************/ /** * AES转变 * <p>法算法名称/加密模式/填充方式</p> * <p>加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB</p> * <p>填充方式有:NoPadding、ZerosPadding、PKCS5Padding</p> */ public static String AES_Transformation = "AES/ECB/NoPadding"; private static final String AES_Algorithm = "AES"; /** * AES加密后转为Base64编码 * * @param data 明文 * @param key 16、24、32字节秘钥 * @return Base64密文 */ public static byte[] encryptAES2Base64(byte[] data, byte[] key) { return EncodeUtils.base64Encode(encryptAES(data, key)); } /** * AES加密后转为16进制 * * @param data 明文 * @param key 16、24、32字节秘钥 * @return 16进制密文 */ public static String encryptAES2HexString(byte[] data, byte[] key) { return bytes2HexString(encryptAES(data, key)); } /** * AES加密 * * @param data 明文 * @param key 16、24、32字节秘钥 * @return 密文 */ public static byte[] encryptAES(byte[] data, byte[] key) { return desTemplate(data, key, AES_Algorithm, AES_Transformation, true); } /** * AES解密Base64编码密文 * * @param data Base64编码密文 * @param key 16、24、32字节秘钥 * @return 明文 */ public static byte[] decryptBase64AES(byte[] data, byte[] key) { return decryptAES(EncodeUtils.base64Decode(data), key); } /** * AES解密16进制密文 * * @param data 16进制密文 * @param key 16、24、32字节秘钥 * @return 明文 */ public static byte[] decryptHexStringAES(String data, byte[] key) { return decryptAES(hexString2Bytes(data), key); } /** * AES解密 * * @param data 密文 * @param key 16、24、32字节秘钥 * @return 明文 */ public static byte[] decryptAES(byte[] data, byte[] key) { return desTemplate(data, key, AES_Algorithm, AES_Transformation, false); } /** * DES加密模板 * * @param data 数据 * @param key 秘钥 * @param algorithm 加密算法 * @param transformation 转变 * @param isEncrypt {@code true}: 加密 {@code false}: 解密 * @return 密文或者明文,适用于DES,3DES,AES */ public static byte[] desTemplate(byte[] data, byte[] key, String algorithm, String transformation, boolean isEncrypt) { if (data == null || data.length == 0 || key == null || key.length == 0) return null; try { SecretKeySpec keySpec = new SecretKeySpec(key, algorithm); Cipher cipher = Cipher.getInstance(transformation); SecureRandom random = new SecureRandom(); cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keySpec, random); return cipher.doFinal(data); } catch (Throwable e) { e.printStackTrace(); return null; } } private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private static String bytes2HexString(byte[] bytes) { if (bytes == null) return null; int len = bytes.length; if (len <= 0) return null; char[] ret = new char[len << 1]; for (int i = 0, j = 0; i < len; i++) { ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f]; ret[j++] = hexDigits[bytes[i] & 0x0f]; } return new String(ret); } private static byte[] hexString2Bytes(String hexString) { if (TextUtils.isEmpty(hexString)) return null; int len = hexString.length(); if (len % 2 != 0) { hexString = "0" + hexString; len = len + 1; } char[] hexBytes = hexString.toUpperCase().toCharArray(); byte[] ret = new byte[len >> 1]; for (int i = 0; i < len; i += 2) { ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1])); } return ret; } private static int hex2Dec(char hexChar) { if (hexChar >= '0' && hexChar <= '9') { return hexChar - '0'; } else if (hexChar >= 'A' && hexChar <= 'F') { return hexChar - 'A' + 10; } else { throw new IllegalArgumentException(); } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/PinyinUtils.java
architecture/src/main/java/com/jiang/android/architecture/utils/PinyinUtils.java
package com.jiang.android.architecture.utils; import java.io.UnsupportedEncodingException; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 16/11/16 * desc : 拼音相关工具类 * </pre> */ public class PinyinUtils { private PinyinUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } private static int[] pinyinValue = new int[]{-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032, -20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728, -19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261, -19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961, -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490, -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988, -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692, -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733, -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419, -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959, -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631, -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180, -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941, -14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857, -14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353, -14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094, -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831, -13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329, -13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860, -12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300, -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358, -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014, -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309, -10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254}; private static String[] pinyin = new String[]{"a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian", "biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che", "chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan", "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du", "duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang", "gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang", "hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian", "jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken", "keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng", "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai", "man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai", "nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan", "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re", "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha", "shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun", "shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao", "tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi", "yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha", "zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui", "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"}; /** * 单个汉字转成ASCII码 * * @param cc 单个汉字(Chinese character) * @return 如果字符串长度是1返回的是对应的ascii码,否则返回-1 */ private static int oneCc2ASCII(String cc) { if (cc.length() != 1) return -1; int ascii = 0; try { byte[] bytes = cc.getBytes("GB2312"); if (bytes.length == 1) { ascii = bytes[0]; } else if (bytes.length == 2) { int highByte = 256 + bytes[0]; int lowByte = 256 + bytes[1]; ascii = (256 * highByte + lowByte) - 256 * 256; } else { throw new IllegalArgumentException("Illegal resource string"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ascii; } /** * 单个汉字转成拼音 * * @param cc 单个汉字(Chinese character) * @return 如果字符串长度是1返回的是对应的拼音,否则返回{@code null} */ private static String oneCc2Pinyin(String cc) { int ascii = oneCc2ASCII(cc); if (ascii == -1) return null; String ret = null; if (0 <= ascii && ascii <= 127) { ret = String.valueOf((char) ascii); } else { for (int i = pinyinValue.length - 1; i >= 0; i--) { if (pinyinValue[i] <= ascii) { ret = pinyin[i]; break; } } } return ret; } /** * 获取第一个汉字首字母 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String getPinyinFirstLetter(String ccs) { if (ccs == null || ccs.trim().length() <= 0) return null; String firstCc, py; firstCc = ccs.substring(0, 1); py = oneCc2Pinyin(firstCc); if (py == null) return null; return py.substring(0, 1); } /** * 汉字转拼音 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String ccs2Pinyin(String ccs) { String cc, py; StringBuilder sb = new StringBuilder(); for (int i = 0; i < ccs.length(); i++) { cc = ccs.substring(i, i + 1); py = oneCc2Pinyin(cc); if (py == null) py = "?"; sb.append(py); } return sb.toString(); } /** * 汉字转拼音 * * @param ccs 汉字字符串 * @param split 汉字拼音之间的分隔符 * @return 拼音 */ public static String ccs2Pinyin(String ccs, String split) { String cc, py; StringBuilder sb = new StringBuilder(); for (int i = 0; i < ccs.length(); i++) { cc = ccs.substring(i, i + 1); py = oneCc2Pinyin(cc); if (py == null) py = "?"; sb.append(py).append(split); } return sb.toString(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/PathUtil.java
architecture/src/main/java/com/jiang/android/architecture/utils/PathUtil.java
package com.jiang.android.architecture.utils; /** * Created by guxin on 15/7/6. */ // // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // import android.content.Context; import android.os.Environment; import android.text.TextUtils; import java.io.File; public class PathUtil { private static String pathPrefix = "config/"; private static final String imagePathName = "/image/"; private static final String voicePathName = "/voice/"; private static final String cachePathName = "/cache/"; private static final String filePathName = "/file/"; private static File storageDir = null; private static PathUtil instance = null; private File voicePath = null; private File imagePath = null; private File cachePath = null; private File filePath = null; private PathUtil(String name) { if (!TextUtils.isEmpty(name)) { pathPrefix = name + "/"; } } public static PathUtil getInstance() { return getInstance(null); } public static PathUtil getInstance(String pathName) { if (instance == null) { instance = new PathUtil(pathName); } return instance; } public void initDirs(Context var3) { this.voicePath = generateVoicePath(var3); if (!this.voicePath.exists()) { this.voicePath.mkdirs(); } this.imagePath = generateImagePath(var3); if (!this.imagePath.exists()) { this.imagePath.mkdirs(); } this.cachePath = generateCachePath(var3); if (!this.cachePath.exists()) { this.cachePath.mkdirs(); } this.filePath = generateFilePath(var3); if (!this.filePath.exists()) { this.filePath.mkdirs(); } } public File getImagePath() { return this.imagePath; } public File getVoicePath() { return voicePath; } public File getFilePath() { return filePath; } private static File getStorageDir(Context var0) { if (storageDir == null) { File var1 = Environment.getExternalStorageDirectory(); if (var1.exists()) { return var1; } storageDir = var0.getFilesDir(); } return storageDir; } private static File generateImagePath(Context var2) { String var3 = pathPrefix + "/images/"; return new File(getStorageDir(var2), var3); } private static File generateVoicePath(Context var2) { String var3 = pathPrefix + "/voice/"; return new File(getStorageDir(var2), var3); } private static File generateCachePath(Context var2) { String var3 = pathPrefix + "/cache/"; return new File(getStorageDir(var2), var3); } private static File generateFilePath(Context var2) { String var3 = pathPrefix + "/file/"; return new File(getStorageDir(var2), var3); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/EncodeUtils.java
architecture/src/main/java/com/jiang/android/architecture/utils/EncodeUtils.java
package com.jiang.android.architecture.utils; import android.os.Build; import android.text.Html; import android.util.Base64; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/8/7 * desc : 编码解码相关工具类 * </pre> */ public class EncodeUtils { private EncodeUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * URL编码 * <p>若想自己指定字符集,可以使用{@link #urlEncode(String input, String charset)}方法</p> * * @param input 要编码的字符 * @return 编码为UTF-8的字符串 */ public static String urlEncode(String input) { return urlEncode(input, "UTF-8"); } /** * URL编码 * <p>若系统不支持指定的编码字符集,则直接将input原样返回</p> * * @param input 要编码的字符 * @param charset 字符集 * @return 编码为字符集的字符串 */ public static String urlEncode(String input, String charset) { try { return URLEncoder.encode(input, charset); } catch (UnsupportedEncodingException e) { return input; } } /** * URL解码 * <p>若想自己指定字符集,可以使用 {@link #urlDecode(String input, String charset)}方法</p> * * @param input 要解码的字符串 * @return URL解码后的字符串 */ public static String urlDecode(String input) { return urlDecode(input, "UTF-8"); } /** * URL解码 * <p>若系统不支持指定的解码字符集,则直接将input原样返回</p> * * @param input 要解码的字符串 * @param charset 字符集 * @return URL解码为指定字符集的字符串 */ public static String urlDecode(String input, String charset) { try { return URLDecoder.decode(input, charset); } catch (UnsupportedEncodingException e) { return input; } } /** * Base64编码 * * @param input 要编码的字符串 * @return Base64编码后的字符串 */ public static byte[] base64Encode(String input) { return base64Encode(input.getBytes()); } /** * Base64编码 * * @param input 要编码的字节数组 * @return Base64编码后的字符串 */ public static byte[] base64Encode(byte[] input) { return Base64.encode(input, Base64.NO_WRAP); } /** * Base64编码 * * @param input 要编码的字节数组 * @return Base64编码后的字符串 */ public static String base64Encode2String(byte[] input) { return Base64.encodeToString(input, Base64.NO_WRAP); } /** * Base64解码 * * @param input 要解码的字符串 * @return Base64解码后的字符串 */ public static byte[] base64Decode(String input) { return Base64.decode(input, Base64.NO_WRAP); } /** * Base64解码 * * @param input 要解码的字符串 * @return Base64解码后的字符串 */ public static byte[] base64Decode(byte[] input) { return Base64.decode(input, Base64.NO_WRAP); } /** * Base64URL安全编码 * <p>将Base64中的URL非法字符�?,/=转为其他字符, 见RFC3548</p> * * @param input 要Base64URL安全编码的字符串 * @return Base64URL安全编码后的字符串 */ public static byte[] base64UrlSafeEncode(String input) { return Base64.encode(input.getBytes(), Base64.URL_SAFE); } /** * Html编码 * * @param input 要Html编码的字符串 * @return Html编码后的字符串 */ public static String htmlEncode(String input) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return Html.escapeHtml(input); } else { // 参照Html.escapeHtml()中代码 StringBuilder out = new StringBuilder(); for (int i = 0, len = input.length(); i < len; i++) { char c = input.charAt(i); if (c == '<') { out.append("&lt;"); } else if (c == '>') { out.append("&gt;"); } else if (c == '&') { out.append("&amp;"); } else if (c >= 0xD800 && c <= 0xDFFF) { if (c < 0xDC00 && i + 1 < len) { char d = input.charAt(i + 1); if (d >= 0xDC00 && d <= 0xDFFF) { i++; int codepoint = 0x010000 | (int) c - 0xD800 << 10 | (int) d - 0xDC00; out.append("&#").append(codepoint).append(";"); } } } else if (c > 0x7E || c < ' ') { out.append("&#").append((int) c).append(";"); } else if (c == ' ') { while (i + 1 < len && input.charAt(i + 1) == ' ') { out.append("&nbsp;"); i++; } out.append(' '); } else { out.append(c); } } return out.toString(); } } /** * Html解码 * * @param input 待解码的字符串 * @return Html解码后的字符串 */ public static String htmlDecode(String input) { return Html.fromHtml(input).toString(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/ImagePipelineConfigFactory.java
architecture/src/main/java/com/jiang/android/architecture/utils/ImagePipelineConfigFactory.java
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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. */ package com.jiang.android.architecture.utils; import android.content.Context; import com.facebook.cache.disk.DiskCacheConfig; import com.facebook.common.internal.Supplier; import com.facebook.common.util.ByteConstants; import com.facebook.imagepipeline.cache.MemoryCacheParams; import com.facebook.imagepipeline.core.ImagePipelineConfig; /** * Creates ImagePipeline configuration for the sample app */ public class ImagePipelineConfigFactory { private static final String IMAGE_PIPELINE_CACHE_DIR = "imagepipeline_cache"; private static ImagePipelineConfig sImagePipelineConfig; private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; /** * Creates config using android http stack as network backend. */ public static ImagePipelineConfig getImagePipelineConfig(Context context) { if (sImagePipelineConfig == null) { ImagePipelineConfig.Builder configBuilder = ImagePipelineConfig.newBuilder(context); configureCaches(configBuilder, context); // configureLoggingListeners(configBuilder); configureOptions(configBuilder); sImagePipelineConfig = configBuilder.build(); } return sImagePipelineConfig; } /** * Configures disk and memory cache not to exceed common limits */ private static void configureCaches( ImagePipelineConfig.Builder configBuilder, Context context) { final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams( MAX_MEMORY_CACHE_SIZE, // Max total size of elements in the cache Integer.MAX_VALUE, // Max entries in the cache MAX_MEMORY_CACHE_SIZE, // Max total size of elements in eviction queue Integer.MAX_VALUE, // Max length of eviction queue Integer.MAX_VALUE); // Max cache entry size configBuilder .setBitmapMemoryCacheParamsSupplier( new Supplier<MemoryCacheParams>() { public MemoryCacheParams get() { return bitmapCacheParams; } }) .setMainDiskCacheConfig( DiskCacheConfig.newBuilder(context) .setBaseDirectoryPath(context.getApplicationContext().getCacheDir()) .setBaseDirectoryName(IMAGE_PIPELINE_CACHE_DIR) .setMaxCacheSize(MAX_DISK_CACHE_SIZE) .build()); } // private static void configureLoggingListeners(ImagePipelineConfig.Builder configBuilder) { // Set<RequestListener> requestListeners = new HashSet<>(); // requestListeners.add(new RequestLoggingListener()); // configBuilder.setRequestListeners(requestListeners); // } private static void configureOptions(ImagePipelineConfig.Builder configBuilder) { configBuilder.setDownsampleEnabled(true); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/Preconditions.java
architecture/src/main/java/com/jiang/android/architecture/utils/Preconditions.java
package com.jiang.android.architecture.utils; import android.support.annotation.Nullable; final class Preconditions { /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { if (reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } return reference; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/utils/ColorUtils.java
architecture/src/main/java/com/jiang/android/architecture/utils/ColorUtils.java
package com.jiang.android.architecture.utils; import android.content.res.ColorStateList; /** * Generate thumb and background color state list use tintColor * Created by kyle on 15/11/4. */ public class ColorUtils { private static final int ENABLE_ATTR = android.R.attr.state_enabled; private static final int CHECKED_ATTR = android.R.attr.state_checked; private static final int PRESSED_ATTR = android.R.attr.state_pressed; public static ColorStateList generateThumbColorWithTintColor(final int tintColor) { int[][] states = new int[][]{ {-ENABLE_ATTR, CHECKED_ATTR}, {-ENABLE_ATTR}, {PRESSED_ATTR, -CHECKED_ATTR}, {PRESSED_ATTR, CHECKED_ATTR}, {CHECKED_ATTR}, {-CHECKED_ATTR} }; int[] colors = new int[] { tintColor - 0xAA000000, 0xFFBABABA, tintColor - 0x99000000, tintColor - 0x99000000, tintColor | 0xFF000000, 0xFFEEEEEE }; return new ColorStateList(states, colors); } public static ColorStateList generateBackColorWithTintColor(final int tintColor) { int[][] states = new int[][]{ {-ENABLE_ATTR, CHECKED_ATTR}, {-ENABLE_ATTR}, {CHECKED_ATTR, PRESSED_ATTR}, {-CHECKED_ATTR, PRESSED_ATTR}, {CHECKED_ATTR}, {-CHECKED_ATTR} }; int[] colors = new int[] { tintColor - 0xE1000000, 0x10000000, tintColor - 0xD0000000, 0x20000000, tintColor - 0xD0000000, 0x20000000 }; return new ColorStateList(states, colors); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/view/LoadMoreRecyclerView.java
architecture/src/main/java/com/jiang/android/architecture/view/LoadMoreRecyclerView.java
package com.jiang.android.architecture.view; import android.content.Context; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.AttributeSet; /** * Created by jiang on 15/9/16. */ public class LoadMoreRecyclerView extends RecyclerView { /** * 监听到底部的接口 */ private OnLoadMoreListener onLoadMoreListener; /** * 正在加载更多 */ public static final int STATE_START_LOADMORE = 100; /** * 加载完成 */ public static final int STATE_FINISH_LOADMORE = 90; /** * 加载更多的状态开关 */ public boolean canLOADMORE = true; /** * 加载更多时候的状态 */ private int loadmore_state; /** * layoutManager的类型(枚举) */ protected LAYOUT_MANAGER_TYPE layoutManagerType; /** * 最后一个的位置 */ private int[] lastPositions; /** * 最后一个可见的item的位置 */ private int lastVisibleItemPosition; /** * 当前滑动的状态 */ private int currentScrollState = 0; public static enum LAYOUT_MANAGER_TYPE { LINEAR, GRID, STAGGERED_GRID } public LoadMoreRecyclerView(Context context) { super(context); } public LoadMoreRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); } public LoadMoreRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setOnScrollListener(OnScrollListener listener) { super.setOnScrollListener(listener); } public boolean isCanLOADMORE() { return canLOADMORE; } public void setCanLOADMORE(boolean canLOADMORE) { this.canLOADMORE = canLOADMORE; } @Override public void onScrolled(int dx, int dy) { super.onScrolled(dx, dy); LayoutManager layoutManager = getLayoutManager(); //拿到layoutmanager用来判断类型,拿到最后一个可见的view if (layoutManagerType == null) { if (layoutManager instanceof LinearLayoutManager) { layoutManagerType = LAYOUT_MANAGER_TYPE.LINEAR; } else if (layoutManager instanceof GridLayoutManager) { layoutManagerType = LAYOUT_MANAGER_TYPE.GRID; } else if (layoutManager instanceof StaggeredGridLayoutManager) { layoutManagerType = LAYOUT_MANAGER_TYPE.STAGGERED_GRID; } else { throw new RuntimeException( "不支持的LayoutManager ,目前只支持 LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager"); } } /** * 拿到最后一个可见的view */ switch (layoutManagerType) { case LINEAR: lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition(); break; case GRID: lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition(); break; case STAGGERED_GRID: StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager; if (lastPositions == null) { lastPositions = new int[staggeredGridLayoutManager.getSpanCount()]; } staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions); lastVisibleItemPosition = findMax(lastPositions); break; } } @Override public void onScrollStateChanged(int state) { super.onScrollStateChanged(state); if (!canLOADMORE) return; if (loadmore_state == STATE_START_LOADMORE) //如果正在加载更多, 则直接return return; currentScrollState = state; LayoutManager layoutManager = getLayoutManager(); int visibleItemCount = layoutManager.getChildCount(); int totalItemCount = layoutManager.getItemCount(); if ((visibleItemCount > 0 && currentScrollState == RecyclerView.SCROLL_STATE_IDLE && (lastVisibleItemPosition) >= totalItemCount - 1)) { loadmore_state = STATE_START_LOADMORE; onLoadMoreListener.onLoadMore(); } } private int findMax(int[] lastPositions) { int max = lastPositions[0]; for (int value : lastPositions) { if (value > max) { max = value; } } return max; } public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) { this.onLoadMoreListener = onLoadMoreListener; } public void setLoadmore_state(int loadmore_state) { this.loadmore_state = loadmore_state; } public interface OnLoadMoreListener { void onLoadMore(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/view/MultiStateView.java
architecture/src/main/java/com/jiang/android/architecture/view/MultiStateView.java
package com.jiang.android.architecture.view; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.jiang.android.architecture.R; public class MultiStateView extends FrameLayout { private static final int UNKNOWN_VIEW = -1; private static final int CONTENT_VIEW = 0; private static final int ERROR_VIEW = 1; private static final int EMPTY_VIEW = 2; private static final int LOADING_VIEW = 3; public enum ViewState { CONTENT, LOADING, EMPTY, ERROR } private LayoutInflater mInflater; private View mContentView; private View mLoadingView; private View mErrorView; private View mEmptyView; private ViewState mViewState = ViewState.CONTENT; public MultiStateView(Context context) { this(context, null); } public MultiStateView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public MultiStateView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs); } private void init(AttributeSet attrs) { mInflater = LayoutInflater.from(getContext()); TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MultiStateView); int loadingViewResId = a.getResourceId(R.styleable.MultiStateView_msv_loadingView, -1); if (loadingViewResId > -1) { mLoadingView = mInflater.inflate(loadingViewResId, this, false); addView(mLoadingView, mLoadingView.getLayoutParams()); } int emptyViewResId = a.getResourceId(R.styleable.MultiStateView_msv_emptyView, -1); if (emptyViewResId > -1) { mEmptyView = mInflater.inflate(emptyViewResId, this, false); addView(mEmptyView, mEmptyView.getLayoutParams()); } int errorViewResId = a.getResourceId(R.styleable.MultiStateView_msv_errorView, -1); if (errorViewResId > -1) { mErrorView = mInflater.inflate(errorViewResId, this, false); addView(mErrorView, mErrorView.getLayoutParams()); } int viewState = a.getInt(R.styleable.MultiStateView_msv_viewState, UNKNOWN_VIEW); if (viewState != UNKNOWN_VIEW) { switch (viewState) { case CONTENT_VIEW: mViewState = ViewState.CONTENT; break; case ERROR_VIEW: mViewState = ViewState.EMPTY; break; case EMPTY_VIEW: mViewState = ViewState.EMPTY; break; case LOADING_VIEW: mViewState = ViewState.LOADING; break; } } a.recycle(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mContentView == null) throw new IllegalArgumentException("Content view is not defined"); setView(); } /* All of the addView methods have been overridden so that it can obtain the content view via XML It is NOT recommended to add views into MultiStateView via the addView methods, but rather use any of the setViewForState methods to set views for their given ViewState accordingly */ @Override public void addView(View child) { if (isValidContentView(child)) mContentView = child; super.addView(child); } @Override public void addView(View child, int index) { if (isValidContentView(child)) mContentView = child; super.addView(child, index); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (isValidContentView(child)) mContentView = child; super.addView(child, index, params); } @Override public void addView(View child, ViewGroup.LayoutParams params) { if (isValidContentView(child)) mContentView = child; super.addView(child, params); } @Override public void addView(View child, int width, int height) { if (isValidContentView(child)) mContentView = child; super.addView(child, width, height); } @Override protected boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params) { if (isValidContentView(child)) mContentView = child; return super.addViewInLayout(child, index, params); } @Override protected boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout) { if (isValidContentView(child)) mContentView = child; return super.addViewInLayout(child, index, params, preventRequestLayout); } public View getView(ViewState state) { switch (state) { case LOADING: return mLoadingView; case CONTENT: return mContentView; case EMPTY: return mEmptyView; case ERROR: return mErrorView; default: return null; } } public ViewState getViewState() { return mViewState; } public void setViewState(ViewState state) { if (state != mViewState) { mViewState = state; setView(); } } private void setView() { switch (mViewState) { case LOADING: if (mLoadingView == null) { throw new NullPointerException("Loading View"); } mLoadingView.setVisibility(View.VISIBLE); if (mContentView != null) mContentView.setVisibility(View.GONE); if (mErrorView != null) mErrorView.setVisibility(View.GONE); if (mEmptyView != null) mEmptyView.setVisibility(View.GONE); break; case EMPTY: if (mEmptyView == null) { throw new NullPointerException("Empty View"); } mEmptyView.setVisibility(View.VISIBLE); if (mLoadingView != null) mLoadingView.setVisibility(View.GONE); if (mErrorView != null) mErrorView.setVisibility(View.GONE); if (mContentView != null) mContentView.setVisibility(View.GONE); break; case ERROR: if (mErrorView == null) { throw new NullPointerException("Error View"); } mErrorView.setVisibility(View.VISIBLE); if (mLoadingView != null) mLoadingView.setVisibility(View.GONE); if (mContentView != null) mContentView.setVisibility(View.GONE); if (mEmptyView != null) mEmptyView.setVisibility(View.GONE); break; case CONTENT: default: if (mContentView == null) { // Should never happen, the view should throw an exception if no content view is present upon creation throw new NullPointerException("Content View"); } mContentView.setVisibility(View.VISIBLE); if (mLoadingView != null) mLoadingView.setVisibility(View.GONE); if (mErrorView != null) mErrorView.setVisibility(View.GONE); if (mEmptyView != null) mEmptyView.setVisibility(View.GONE); break; } } /** * Checks if the given {@link View} is valid for the Content View * * @param view The {@link View} to check * @return */ private boolean isValidContentView(View view) { if (mContentView != null && mContentView != view) { return false; } return view != mLoadingView && view != mErrorView && view != mEmptyView; } public void setViewForState(View view, ViewState state, boolean switchToState) { switch (state) { case LOADING: if (mLoadingView != null) removeView(mLoadingView); mLoadingView = view; addView(mLoadingView); break; case EMPTY: if (mEmptyView != null) removeView(mEmptyView); mEmptyView = view; addView(mEmptyView); break; case ERROR: if (mErrorView != null) removeView(mErrorView); mErrorView = view; addView(mErrorView); break; case CONTENT: if (mContentView != null) removeView(mContentView); mContentView = view; addView(mContentView); break; } if (switchToState) setViewState(state); } public void setViewForState(View view, ViewState state) { setViewForState(view, state, false); } public void setViewForState(int layoutRes, ViewState state, boolean switchToState) { if (mInflater == null) mInflater = LayoutInflater.from(getContext()); View view = mInflater.inflate(layoutRes, this, false); setViewForState(view, state, switchToState); } public void setViewForState(int layoutRes, ViewState state) { setViewForState(layoutRes, state, false); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/OkHttpRequest.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/OkHttpRequest.java
/** * created by jiang, 11/9/15 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp; import android.text.TextUtils; import com.jiang.android.architecture.okhttp.callback.BaseCallBack; import com.jiang.android.architecture.okhttp.exception.NotPermissionException; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; /** * Created by jiang on 11/9/15. */ public class OkHttpRequest { /** * @param url url * @param params 需要传递的参数 get请求? 后面的参数也可以通过param传递 * @param callBack 返回的回调 * @param tag 唯一的key, 可以通过这个唯一的key来取消网络请求 * @param type 请求的类型 * @param headers 需要特殊处理的请求头 */ public static void doJob(String url, Object tag, Map<String, String> params, final BaseCallBack callBack, Map<String, String> headers, int type) { OkHttpTask.getInstance().filterData(url, tag, params, callBack, headers, type); } public static void downLoadFile(String url, String path, String fileName, BaseCallBack callBack, Object tag) { OkHttpTask.getInstance().downLoadFile(url, path, fileName, callBack, tag, null); } public static void uploadFile(String url, Map<String, String> headers, List<String> files, BaseCallBack callBack, Object tag) { OkHttpTask.getInstance().uploadFile(url, headers, files, callBack, tag); } private static void cancel(Object tag) { OkHttpTask.getInstance().cancelTask(tag); } public static class Builder { private String url; private Object tag; private Map<String, String> headers; private Map<String, String> params; private List<String> files; private String path; private String fileName; private int type; private BaseCallBack callBack; public Builder build() { return this; } public int getType() { return type; } public void setType(int type) { this.type = type; } public Builder url(String url) { this.url = url; return this; } public Builder files(List<String> files) { if (this.files == null) this.files = new ArrayList<>(); this.files.addAll(files); return this; } public Builder file(String file) { if (files == null) files = new ArrayList<>(); files.add(file); return this; } public Builder path(String path) { this.path = path; return this; } public Builder fileName(String fileName) { this.fileName = fileName; return this; } public Builder tag(Object tag) { this.tag = tag; return this; } public Builder params(Map<String, String> params) { this.params = params; return this; } public Builder addParams(String key, String val) { if (this.params == null) { params = new IdentityHashMap<>(); } params.put(key, val); return this; } public Builder headers(Map<String, String> headers) { this.headers = headers; return this; } public Builder addHeader(String key, String val) { if (this.headers == null) { headers = new IdentityHashMap<>(); } headers.put(key, val); return this; } public void get(BaseCallBack c) { this.callBack = c; type = OkHttpTask.TYPE_GET; if (validateParams()) { doJob(url, tag, params, callBack, headers, OkHttpTask.TYPE_GET); } } public void post(BaseCallBack c) { this.callBack = c; type = OkHttpTask.TYPE_POST; if (validateParams()) { doJob(url, tag, params, callBack, headers, OkHttpTask.TYPE_POST); } } public void put(BaseCallBack c) { this.callBack = c; type = OkHttpTask.TYPE_PUT; if (validateParams()) { doJob(url, tag, params, callBack, headers, OkHttpTask.TYPE_PUT); } } public void delete(BaseCallBack c) { this.callBack = c; type = OkHttpTask.TYPE_DELETE; if (validateParams()) { doJob(url, tag, params, callBack, headers, OkHttpTask.TYPE_DELETE); } } public void downLoad(BaseCallBack c) { this.callBack = c; type = OkHttpTask.TYPE_GET; if (validateParams()) { downLoadFile(url, path, fileName, callBack, tag); } } public void execute(BaseCallBack c) { this.callBack = c; if (validateParams()) { doJob(url, tag, params, callBack, headers, type); } } /** * 上传文件必传 * url,files,header(用来验证),callBack * * @param c */ public void upload(BaseCallBack c) { this.callBack = c; type = OkHttpTask.TYPE_POST; if (validateParams()) { uploadFile(url, headers, files, callBack, tag); } } private boolean validateParams() { if (TextUtils.isEmpty(url) || !url.startsWith("http")) { throw new NotPermissionException("url不合法"); } if (type != OkHttpTask.TYPE_GET && type != OkHttpTask.TYPE_POST && type != OkHttpTask.TYPE_PUT && type != OkHttpTask.TYPE_DELETE) { throw new NotPermissionException("请先设置请求类型 支持 get,post,put,delete"); } if (callBack == null) { throw new NotPermissionException("没有CallBack"); } return true; } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false