From f558954d22f90a3b74422ada03446afd2980d22f Mon Sep 17 00:00:00 2001 From: kehaoyuan Date: Fri, 9 Aug 2019 14:43:43 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=BF=AB=E4=BC=A0=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/src/main/AndroidManifest.xml | 18 - .../java/com/gh/common/util/DeviceUtils.java | 21 +- .../java/com/gh/common/util/DialogUtils.java | 170 ----- .../com/gh/gamecenter/ShareGhActivity.java | 7 - .../gh/gamecenter/ShareGhWfifActivity.java | 357 ---------- .../adapter/FileReceiverAdapter.java | 192 ----- .../gamecenter/adapter/FileSenderAdapter.java | 164 ----- .../adapter/KcSelectGameAdapter.java | 403 ----------- .../download/GameDownloadFragment.java | 8 - .../gh/gamecenter/kuaichuan/BaseTransfer.java | 30 - .../com/gh/gamecenter/kuaichuan/Constant.java | 76 -- .../kuaichuan/DownloadUriHandler.java | 93 --- .../com/gh/gamecenter/kuaichuan/FileInfo.java | 207 ------ .../gh/gamecenter/kuaichuan/FileReceiver.java | 307 -------- .../gh/gamecenter/kuaichuan/FileSender.java | 311 --------- .../gamecenter/kuaichuan/HotspotManager.java | 121 ---- .../gamecenter/kuaichuan/HtmlUriHandler.java | 109 --- .../gamecenter/kuaichuan/ImageUriHandler.java | 101 --- .../gh/gamecenter/kuaichuan/IpPortInfo.java | 64 -- .../gh/gamecenter/kuaichuan/KcUriHandler.java | 29 - .../kuaichuan/KuaichuanNotification.java | 46 -- .../gh/gamecenter/kuaichuan/Transferable.java | 30 - .../com/gh/gamecenter/kuaichuan/WifiMgr.java | 249 ------- .../gh/gamecenter/kuaichuan/WifiUtils.java | 128 ---- .../view/ChooseReceiverActivity.java | 653 ------------------ .../kuaichuan/view/FileReceiverActivity.java | 652 ----------------- .../kuaichuan/view/FileSenderActivity.java | 488 ------------- .../kuaichuan/view/FileShareActivity.java | 19 - .../kuaichuan/view/FileShareFragment.java | 83 --- .../kuaichuan/view/KcSelectGameActivity.java | 207 ------ .../view/ReceiverWaitingActivity.java | 391 ----------- app/src/main/res/layout/activity_share_gh.xml | 14 - 32 files changed, 19 insertions(+), 5729 deletions(-) delete mode 100644 app/src/main/java/com/gh/gamecenter/ShareGhWfifActivity.java delete mode 100644 app/src/main/java/com/gh/gamecenter/adapter/FileReceiverAdapter.java delete mode 100644 app/src/main/java/com/gh/gamecenter/adapter/FileSenderAdapter.java delete mode 100644 app/src/main/java/com/gh/gamecenter/adapter/KcSelectGameAdapter.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/BaseTransfer.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/Constant.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/DownloadUriHandler.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/FileInfo.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/FileReceiver.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/FileSender.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/HotspotManager.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/HtmlUriHandler.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/ImageUriHandler.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/IpPortInfo.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/KcUriHandler.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/KuaichuanNotification.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/Transferable.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/WifiMgr.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/WifiUtils.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/view/ChooseReceiverActivity.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileReceiverActivity.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileSenderActivity.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileShareActivity.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileShareFragment.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/view/KcSelectGameActivity.java delete mode 100644 app/src/main/java/com/gh/gamecenter/kuaichuan/view/ReceiverWaitingActivity.java diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3282566c27..0da0c5e591 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -124,30 +124,12 @@ - - - - - - diff --git a/app/src/main/java/com/gh/common/util/DeviceUtils.java b/app/src/main/java/com/gh/common/util/DeviceUtils.java index 3a9095ce70..56347f4b41 100644 --- a/app/src/main/java/com/gh/common/util/DeviceUtils.java +++ b/app/src/main/java/com/gh/common/util/DeviceUtils.java @@ -11,7 +11,7 @@ import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; -import com.gh.gamecenter.kuaichuan.WifiMgr; +import com.halo.assistant.HaloApp; import com.lightgame.utils.Util_System_Phone_State; import com.tencent.stat.StatConfig; @@ -164,7 +164,7 @@ public class DeviceUtils { } } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络 - return WifiMgr.getInstance(context).getCurrentIpAddress(); + return getCurrentIpAddress(); } } else { //当前无网络连接,请在设置中打开网络 @@ -266,4 +266,21 @@ public class DeviceUtils { return memInfo.totalMem / (1024 * 1024); } + + // 只能获取WiFi的IpAddress + public static String getCurrentIpAddress() { + String ipAddress; + WifiManager wifiManager = (WifiManager) HaloApp.getInstance(). + getApplication(). + getApplicationContext(). + getSystemService(Context.WIFI_SERVICE); + int address = wifiManager.getDhcpInfo().ipAddress; + ipAddress = ((address & 0xFF) + + "." + ((address >> 8) & 0xFF) + + "." + ((address >> 16) & 0xFF) + + "." + ((address >> 24) & 0xFF)); + return ipAddress; + } + + } diff --git a/app/src/main/java/com/gh/common/util/DialogUtils.java b/app/src/main/java/com/gh/common/util/DialogUtils.java index eb011c0ae8..8d4cc503be 100644 --- a/app/src/main/java/com/gh/common/util/DialogUtils.java +++ b/app/src/main/java/com/gh/common/util/DialogUtils.java @@ -5,11 +5,7 @@ import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageInfo; -import android.graphics.Bitmap; import android.graphics.Color; -import android.os.Handler; import android.text.Html; import android.text.SpannableStringBuilder; import android.text.Spanned; @@ -17,12 +13,10 @@ import android.text.TextPaint; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; -import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; -import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; @@ -35,19 +29,10 @@ import androidx.core.content.ContextCompat; import com.gh.gamecenter.AboutActivity; import com.gh.gamecenter.R; import com.gh.gamecenter.WebActivity; -import com.gh.gamecenter.kuaichuan.WifiMgr; -import com.gh.gamecenter.kuaichuan.view.KcSelectGameActivity; -import com.halo.assistant.HaloApp; import com.lightgame.utils.AppManager; import com.lightgame.utils.Utils; -import java.io.File; -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.Date; import java.util.List; -import java.util.Locale; -import java.util.Map; public class DialogUtils { @@ -65,161 +50,6 @@ public class DialogUtils { return dialog; } - // 快传成绩单 - public static void showKuaiChuanResult(final Activity activity, Handler handler, int requestCode, final String picName) { - - HaloApp.remove(KcSelectGameActivity.KEY_FILE_INFO); - - List> mapList = (List>) HaloApp.get("sendData", true); - if (mapList == null || mapList.size() == 0) return; - - WifiMgr.getInstance(activity).disconnectCurrentNetwork(); // 断开当前WiFi - - int filesCount = mapList.size(); - int filesSize = 0; - int sendTime = 0; - - View view = View.inflate(activity, R.layout.dialog_kuaichuan, null); - final LinearLayout mShareLl = view.findViewById(R.id.kuaichuan_dialog_ll); - final LinearLayout mShareBottomLl = view.findViewById(R.id.kuaichuan_dialog_share_rl); - LinearLayout shareIconLl = view.findViewById(R.id.kuaichuan_icon_ll); - ImageView qrCode = view.findViewById(R.id.kuaichuan_qrcode); - TextView dateTv = view.findViewById(R.id.kuaichuan_dialog_date); - TextView countTv = view.findViewById(R.id.kuaichuan_send_count); - TextView sizeTv = view.findViewById(R.id.kuaichuan_send_size); - TextView speedTv = view.findViewById(R.id.kuaichuan_send_speed); - TextView timeCount = view.findViewById(R.id.kuaichuan_time_count); - TextView timeTv = view.findViewById(R.id.kuaichuan_time_tv); - TextView sendCountTv = view.findViewById(R.id.dialog_send_tv); - ImageView closeIv = view.findViewById(R.id.kuaichuan_dialog_colse); - - final Dialog dialog = new Dialog(activity); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - dialog.setCanceledOnTouchOutside(false); - dialog.setContentView(view); - dialog.show(); - - Window dialogWindow = dialog.getWindow(); - WindowManager m = activity.getWindowManager(); - Display d = m.getDefaultDisplay(); - if (dialogWindow != null) { - WindowManager.LayoutParams p = dialogWindow.getAttributes(); - p.height = (int) (d.getHeight() * 0.82); - p.width = (int) (d.getWidth() * 0.80); - dialogWindow.setAttributes(p); - } - - SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault()); - dateTv.setText(format.format(new Date().getTime())); - - for (Map map : mapList) { - int size = Integer.parseInt(map.get("apkSize")); - int time = 10; - try { - time = Integer.parseInt(map.get("sendTime")); - } catch (Exception e) { - e.printStackTrace(); - } - - String apkPath = map.get("apkPath"); - filesSize = filesSize + size; - sendTime = sendTime + time; - - if (shareIconLl.getChildCount() >= 5) continue; - - android.content.pm.PackageManager pm = activity.getPackageManager(); - PackageInfo info = pm.getPackageArchiveInfo(apkPath, - android.content.pm.PackageManager.GET_ACTIVITIES); - if (info != null) { - ApplicationInfo appInfo = info.applicationInfo; - appInfo.sourceDir = apkPath; - appInfo.publicSourceDir = apkPath; - Bitmap bitmap = BitmapUtils.drawableToBitmap(appInfo.loadIcon(pm), true); - - ImageView imageView = new ImageView(activity); - imageView.setLayoutParams(new LinearLayout.LayoutParams(DisplayUtils.dip2px(activity, 25) - , DisplayUtils.dip2px(activity, 24))); - imageView.setImageBitmap(bitmap); - shareIconLl.addView(imageView); - } - } - - if (requestCode == 0x170) { // 发送 - qrCode.setImageResource(R.drawable.kc_qrcode_120); - sendCountTv.setText("成功传送游戏"); - } else { - qrCode.setImageResource(R.drawable.kc_qrcode_110); - sendCountTv.setText("成功接收游戏"); - } - - double size = (((float) filesSize / 1024) / 1024); - String sizeName; - if (size > 1024) { - DecimalFormat df = new DecimalFormat("#.0"); - sizeName = df.format(size / 1024) + "GB"; - } else { - DecimalFormat df = new DecimalFormat("#.0"); - sizeName = df.format(size) + "MB"; - } - - if (sendTime < 1000) { // 最少设置发送时间为1s(为了简易计算) - sendTime = 1000; - } - - int i = (filesSize / 1024) / (sendTime / 1000); - String speed; - if (i >= 1000) { - float mSpeed = i / 1024f; - DecimalFormat df = new DecimalFormat("#.0"); - String str = df.format(mSpeed); - if (str.length() > 4) { - str = str.substring(0, 4); - } - speed = str + "MB/s"; - } else { - speed = i + "KB/s"; - } - - if (sendTime > 60000) { - timeCount.setText(String.valueOf(sendTime / 1000 / 60)); - timeTv.setText("分钟传送完成"); - } else { - timeCount.setText(String.valueOf(sendTime / 1000)); - timeTv.setText("秒传送完成"); - } - - sizeTv.setText(sizeName); - speedTv.setText(speed); - countTv.setText(filesCount + "个"); - - // 延迟操作,等待截图部分绘制完成 - handler.postDelayed(() -> { - mShareLl.setDrawingCacheEnabled(true); - mShareLl.buildDrawingCache(); - Bitmap drawingCache = mShareLl.getDrawingCache(); - saveBitmap(drawingCache, activity, picName); - MessageShareUtils.getInstance(activity).showShareWindows(activity, mShareBottomLl, drawingCache, picName, 2); - mShareBottomLl.setVisibility(View.VISIBLE); - }, 200); - - closeIv.setOnClickListener(v -> dialog.cancel()); - } - - public static void saveBitmap(Bitmap bm, Activity activity, String picName) { - File externalCacheDir = activity.getExternalCacheDir(); - if (externalCacheDir == null) return; - - File file = new File(externalCacheDir.getPath() + "/ShareImg"); - if (!file.isDirectory()) { - file.delete(); - file.mkdirs(); - } - if (!file.exists()) { - file.mkdirs(); - } - MessageShareUtils.getInstance(activity).writeBitmap(file.getPath(), picName, bm, false); - - } public static void showInstallHintDialog(Context context, final ConfirmListener cmListener) { context = checkDialogContext(context); diff --git a/app/src/main/java/com/gh/gamecenter/ShareGhActivity.java b/app/src/main/java/com/gh/gamecenter/ShareGhActivity.java index 42baa069db..70231db02b 100644 --- a/app/src/main/java/com/gh/gamecenter/ShareGhActivity.java +++ b/app/src/main/java/com/gh/gamecenter/ShareGhActivity.java @@ -32,8 +32,6 @@ public class ShareGhActivity extends BaseActivity { ImageView mGhQrcode; @BindView(R.id.gh_address_tv) TextView mGhAddress; - @BindView(R.id.wifi_share_btn) - Button mWifiShareBtn; @BindView(R.id.content_ll) LinearLayout mContentLl; @BindView(R.id.share_rl) @@ -72,11 +70,6 @@ public class ShareGhActivity extends BaseActivity { , "绿色安全的手游加速助手", ShareUtils.ShareType.shareGh); } - @OnClick(R.id.wifi_share_btn) - public void skipWifiShare() { - startActivity(ShareGhWfifActivity.getIntent(this)); - } - @OnClick(R.id.gh_address_tv) public void copyAddress() { ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); diff --git a/app/src/main/java/com/gh/gamecenter/ShareGhWfifActivity.java b/app/src/main/java/com/gh/gamecenter/ShareGhWfifActivity.java deleted file mode 100644 index dc5e44f1a3..0000000000 --- a/app/src/main/java/com/gh/gamecenter/ShareGhWfifActivity.java +++ /dev/null @@ -1,357 +0,0 @@ -package com.gh.gamecenter; - -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import androidx.annotation.NonNull; -import androidx.core.content.ContextCompat; -import android.text.Html; -import android.text.TextUtils; -import android.view.View; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ProgressBar; -import android.widget.TextView; - -import com.gh.base.BaseActivity; -import com.gh.common.util.DialogUtils; -import com.gh.common.util.RandomUtils; -import com.gh.gamecenter.entity.KcWebRequestEntity; -import com.gh.gamecenter.kuaichuan.Constant; -import com.gh.gamecenter.kuaichuan.DownloadUriHandler; -import com.gh.gamecenter.kuaichuan.HotspotManager; -import com.gh.gamecenter.kuaichuan.HtmlUriHandler; -import com.gh.gamecenter.kuaichuan.ImageUriHandler; -import com.gh.gamecenter.kuaichuan.KcUriHandler; -import com.gh.gamecenter.kuaichuan.WifiMgr; -import com.gh.gamecenter.receiver.WifiAPBroadcastReceiver; -import com.halo.assistant.HaloApp; -import com.lightgame.utils.Utils; - -import java.io.IOException; -import java.io.InputStream; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.ArrayList; -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by khy on 2017/2/6. - */ -public class ShareGhWfifActivity extends BaseActivity { - - // @BindView(R.id.hotspot_name) TextView mHotSpotName; - @BindView(R.id.init_hotpost_pb) - ProgressBar mInitHotspostPb; - @BindView(R.id.init_status_icon) - ImageView mInitStatusIcon; - @BindView(R.id.init_status_tv) - TextView mInitStatusTv; - @BindView(R.id.init_hotpost_hint) - TextView mInitHotpostHint; - @BindView(R.id.init_success_ll) - LinearLayout mInitSuccessLl; - @BindView(R.id.init_conn_hint) - TextView initConnHint; - - private ServerSocket mServerSocket; - - private WifiAPBroadcastReceiver mWifiAPBroadcastReceiver; - - private boolean mIsInitialized = false; - - private List mUriHandlers; - - private SharedPreferences sp; - - private boolean isColseActivity; - - private boolean isOpenWifi; //记录开热点前的WiFi状态 - - private boolean initSuccess; - - private String mySsid; - - @NonNull - public static Intent getIntent(Context context) { - Intent intent = new Intent(context, ShareGhWfifActivity.class); - return intent; - } - - @Override - protected int getLayoutId() { - return R.layout.activity_share_gh_wifi; - } - - @Override - public void onBackPressed() { - DialogUtils.showWarningDialog(this, "退出分享", "退出本页面即会关闭分享热点,确定退出吗?" - , "取消", "确定" - , new DialogUtils.ConfirmListener() { - @Override - public void onConfirm() { - isColseActivity = true; - unregisterReceiver(mWifiAPBroadcastReceiver); - try { - if (mWifiAPBroadcastReceiver != null) { - unregisterReceiver(mWifiAPBroadcastReceiver); - mWifiAPBroadcastReceiver = null; - } - } catch (Exception e) { - Utils.log("网页传发送异常-关闭广播"); - e.printStackTrace(); - } - - - for (KcUriHandler uriHandler : mUriHandlers) { - uriHandler.destroy(); - } - - if (mServerSocket != null) { - try { - mServerSocket.close(); - mServerSocket = null; - } catch (IOException e) { - e.printStackTrace(); - } - } - - HotspotManager.initUserAp(getApplicationContext()); - if (isOpenWifi) { - WifiMgr.getInstance(ShareGhWfifActivity.this).openWifi(); - } - - finish(); - } - }, null); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setNavigationTitle(getString(R.string.title_share_via_wifi)); - ButterKnife.bind(this); - - mUriHandlers = new ArrayList<>(); - mUriHandlers.add(new HtmlUriHandler(this)); - mUriHandlers.add(new ImageUriHandler(this)); - mUriHandlers.add(new DownloadUriHandler(this)); - - sp = PreferenceManager.getDefaultSharedPreferences(this); - isColseActivity = false; - initSuccess = false; - - if (WifiMgr.getInstance(this).isWifiEnable()) { - isOpenWifi = true; - WifiMgr.getInstance(this).closeWifi(); - } - - HotspotManager.initApData(getApplicationContext()); // 记录原始热点信息 - - initHotSpotView(0); - initHotSpot(); - } - - /** - * 初始化创建热点View - * - * @param i i=0 初始化中, i=1 初始化成功, i=2 初始化失败 - */ - - public void initHotSpotView(int i) { - switch (i) { - case 0: - mInitHotspostPb.setVisibility(View.VISIBLE); - mInitStatusIcon.setVisibility(View.GONE); - mInitStatusTv.setText("正在创建热点..."); - mInitStatusTv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.title)); - mInitHotpostHint.setVisibility(View.VISIBLE); - mInitHotpostHint.setText("如果出现获取权限的提示,请点击允许"); - break; - case 1: - mInitStatusIcon.setVisibility(View.VISIBLE); - mInitStatusIcon.setImageResource(R.drawable.kc_checkbox_select); - mInitStatusTv.setText(Html.fromHtml(getString(R.string.create_hotspot_blue, mySsid))); - mInitHotpostHint.setVisibility(View.VISIBLE); - mInitHotpostHint.setText("为了避免消耗流量,请关闭你手机的移动网络"); - mInitHotspostPb.setVisibility(View.GONE); - - initConnHint.setText(Html.fromHtml(getString(R.string.kc_conn_hint, mySsid))); - mInitSuccessLl.setVisibility(View.VISIBLE); - initSuccess = true; - break; - case 2: - mInitStatusIcon.setVisibility(View.VISIBLE); - mInitStatusIcon.setImageResource(R.drawable.hotspot_failed_icon); - mInitStatusTv.setText("初始化失败, 请退出重试"); - mInitStatusTv.setTextColor(ContextCompat.getColor(this, R.color.red)); - mInitHotpostHint.setVisibility(View.VISIBLE); - mInitHotspostPb.setVisibility(View.GONE); - break; - } - } - - private void initHotSpot() { - - mWifiAPBroadcastReceiver = new WifiAPBroadcastReceiver() { - - @Override - public void onWifiApEnabled() { - if (!mIsInitialized) { - Utils.log("===初始化热点成功"); - HaloApp.getInstance().getMainExecutor().execute(checkHotSpot()); - mIsInitialized = true; -// mHotSpotName.setText(mySsid); - } - - } - }; - - IntentFilter filter = new IntentFilter(WifiAPBroadcastReceiver.ACTION_WIFI_AP_STATE_CHANGED); - registerReceiver(mWifiAPBroadcastReceiver, filter); - - HotspotManager.isApOn(getApplicationContext()); - - mySsid = sp.getString("hotspotName", null); - if (TextUtils.isEmpty(mySsid)) { - String chars = "abcdefghijklmnopqrstuvwxyz"; - int[] randomArray = RandomUtils.getRandomArray(2, 25); - - mySsid = "ghZS-"; - for (int i : randomArray) { - mySsid = mySsid + chars.charAt(i); - } - - int default_user_icon = sp.getInt("default_user_icon", 0); - if (default_user_icon == 0) { - default_user_icon = RandomUtils.nextInt(8) + 1; - sp.edit().putInt("default_user_icon", default_user_icon).apply(); - } - - mySsid = mySsid + default_user_icon; - sp.edit().putString("hotspotName", mySsid).apply(); - } - HotspotManager.configApState(getApplicationContext(), mySsid); // change Ap state :boolean - } - - private Runnable checkHotSpot() { - return new Runnable() { - @Override - public void run() { - try { - // 确保热点开启之后获取得到IP地址 - String hotspotIpAddr = WifiMgr.getInstance(ShareGhWfifActivity.this).getHotspotLocalIpAddress(); - int count = 0; - while (hotspotIpAddr.equals(Constant.DEFAULT_UNKOWN_IP) && count < Constant.DEFAULT_TRY_TIME) { - Thread.sleep(1000); - hotspotIpAddr = WifiMgr.getInstance(ShareGhWfifActivity.this).getIpAddressFromHotspot(); - count++; - } - - // 即使热点wifi的IP地址也是无法连接网络 所以采取此策略 -// count = 0; -// while(!WifiUtils.pingIpAddress(hotspotIpAddr) && count < Constant.DEFAULT_TRY_TIME){ -// Thread.sleep(500); -// count ++; -// } - } catch (Exception e) { - Utils.log("==热点启动异常::" + e.toString()); - } - - Utils.log("===热点可用"); - - initMicroServer(); - } - }; - } - - private void initMicroServer() { - HaloApp.getInstance().getMainExecutor().execute(new Runnable() { - @Override - public void run() { - try { - Utils.log("===准备开启微型服务器"); - if (mServerSocket == null) { - mServerSocket = new ServerSocket(); - mServerSocket.setReuseAddress(true); - mServerSocket.bind(new InetSocketAddress(Constant.DEFAULT_MICRO_SERVER_PORT)); - } - - while (!isColseActivity) { - if (!initSuccess) { - mInitStatusTv.post(new Runnable() { - @Override - public void run() { - initHotSpotView(1); - } - }); - } - - Utils.log("===循环等待客户端请求"); - Socket socket = mServerSocket.accept(); - KcWebRequestEntity requestEntity = hanlderSocket(socket); - for (KcUriHandler uriHandler : mUriHandlers) { - if (!uriHandler.matches(requestEntity.getUri())) { - continue; - } - - Utils.log("====请求处理::" + requestEntity.getUri() + "==" + uriHandler.getClass().toString()); - uriHandler.handler(requestEntity); - } - - } - - } catch (IOException e) { - Utils.log("===网页传下载出现异常" + e.toString()); - e.printStackTrace(); - - if (!e.toString().contains("Socket closed")) { - mInitStatusTv.post(new Runnable() { - @Override - public void run() { - initHotSpotView(2); - } - }); - } - } - } - }); - } - - private KcWebRequestEntity hanlderSocket(Socket socket) { - KcWebRequestEntity requestEntity = new KcWebRequestEntity(); - - requestEntity.setSocket(socket); - - try { - InputStream is = socket.getInputStream(); - StringBuilder sb = new StringBuilder(); - int a = 0, b = 0; - while ((b != -1) && !(a == '\r' && b == '\n')) { - a = b; - b = is.read(); - sb.append((char) (b)); - } - String[] split = sb.toString().split(" "); - if (split.length > 1) { - String requestUri = split[1]; - requestEntity.setUri(requestUri); - Utils.log("===客户端请求链接::" + requestUri); - } else { - requestEntity.setUri("/ERROR"); - Utils.log("===客户端请求链接异常::" + sb.toString()); - } - } catch (IOException e) { - e.printStackTrace(); - } - return requestEntity; - } - -} diff --git a/app/src/main/java/com/gh/gamecenter/adapter/FileReceiverAdapter.java b/app/src/main/java/com/gh/gamecenter/adapter/FileReceiverAdapter.java deleted file mode 100644 index 6dd4d8a269..0000000000 --- a/app/src/main/java/com/gh/gamecenter/adapter/FileReceiverAdapter.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.gh.gamecenter.adapter; - -import android.content.Context; -import android.content.Intent; -import android.graphics.Color; -import android.graphics.drawable.ColorDrawable; -import android.os.Environment; -import androidx.core.content.ContextCompat; -import android.view.View; -import android.view.ViewGroup; - -import com.lightgame.adapter.BaseRecyclerAdapter; -import com.gh.common.util.DisplayUtils; -import com.gh.common.util.PackageUtils; -import com.gh.common.util.SpeedUtils; -import com.gh.gamecenter.R; -import com.gh.gamecenter.adapter.viewholder.KcSelectGameViewHolder; -import com.gh.gamecenter.kuaichuan.FileInfo; - -import java.text.DecimalFormat; -import java.util.List; - -/** - * Created by khy on 2017/1/22. - */ -public class FileReceiverAdapter extends BaseRecyclerAdapter { - - private List mFileInfoList; - - private long mLastProgress; - - private OnReceiverCancelListener mCancelListener; - - public FileReceiverAdapter(Context context, OnReceiverCancelListener listener, List infos) { - super(context); - mContext = context; - mCancelListener = listener; - - mFileInfoList = infos; - } - - /** - * 更新数据 - */ - public void update() { -// mFileInfoList = (List) AppController.get(KcSelectGameActivity.KEY_FILE_INFO, false); - notifyItemRangeChanged(0, getItemCount()); - } - - @Override - public KcSelectGameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = mLayoutInflater.inflate(R.layout.kc_game_select_item, parent, false); - return new KcSelectGameViewHolder(view); - } - - @Override - public void onBindViewHolder(final KcSelectGameViewHolder holder, int position) { - final FileInfo fileInfo = mFileInfoList.get(position); - holder.gameNameAndSize.setText(fileInfo.getName()); - holder.downloadStatus.setVisibility(View.VISIBLE); - holder.sendOverIcon.setVisibility(View.GONE); - holder.gameProgressbar.setMax(100); - holder.gameProgressbar.setVisibility(View.VISIBLE); - holder.gameLlInfo.setVisibility(View.VISIBLE); - holder.gameSize.setVisibility(View.GONE); - holder.gameNameAndSize.setPadding(0, 0, 0, DisplayUtils.dip2px(mContext, 5)); - if (fileInfo.getBitmap() != null) { - holder.gameThumb.setImageBitmap(fileInfo.getBitmap()); - } else { - holder.gameThumb.setImageResource(R.drawable.occupy); - } - - holder.downloadSpeed.setText(R.string.kc_waiting); - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.gameProgressbar.setProgress(0); - holder.sendOverIcon.setVisibility(View.GONE); - holder.downloadStatus.setText(R.string.kc_cancel); - holder.downloadStatus.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadStatus.setBackgroundResource(R.drawable.kuaichuan_cancel_bg); - - int percent = (int) (fileInfo.getProgress() * 100 / fileInfo.getSize()); - holder.downloadPercentage.setText(percent + "%"); - - DecimalFormat df; - String sizeName; - double sizeMb; - double curSizeMb; - String curSizeName; - switch (fileInfo.getResult()) { - case FileInfo.FLAG_SUCCESS: - case FileInfo.FLAG_INSTALLED:// 传输完成... - holder.gameProgressbar.setProgress(100); - holder.downloadPercentage.setText("100%"); - if (fileInfo.getResult() == FileInfo.FLAG_SUCCESS) { - holder.downloadStatus.setText(R.string.install); - holder.downloadStatus.setTextColor(Color.WHITE); - holder.downloadStatus.setBackgroundResource(R.drawable.game_item_btn_download_style); - } else { - holder.downloadStatus.setText(R.string.installed); - holder.downloadStatus.setTextColor(ContextCompat.getColor(mContext, R.color.theme)); - holder.downloadStatus.setBackgroundDrawable(new ColorDrawable(0)); - } - - double size = (((float) fileInfo.getSize() / 1024) / 1024); - df = new DecimalFormat("0.00"); - sizeName = df.format(size) + "MB"; - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadSpeed.setText(sizeName + "/" + sizeName); - break; - case FileInfo.FLAG_FAILURE: - case FileInfo.FLAG_NO_MEMORY: // 传输失败... - sizeMb = (((float) fileInfo.getSize() / 1024) / 1024); - curSizeMb = (((float) fileInfo.getProgress() / 1024) / 1024); - df = new DecimalFormat("0.00"); - sizeName = df.format(sizeMb) + "MB"; - curSizeName = df.format(curSizeMb) + "MB"; - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadSpeed.setText(curSizeName + "/" + sizeName); - holder.downloadStatus.setTextColor(ContextCompat.getColor(mContext, R.color.type_huodong)); - holder.downloadStatus.setBackgroundDrawable(new ColorDrawable(0)); - -// holder.downloadStatus.setBackgroundColor(ContextCompat.getColor(mContext, android.R.color.transparent)); - - holder.gameProgressbar.setProgress(percent); -// viewHolder.downloadPercentage.setText(percent + "%"); - if (fileInfo.getResult() == FileInfo.FLAG_FAILURE) { - holder.downloadStatus.setText(R.string.kc_send_failuer); - } else { - holder.downloadStatus.setText("空间不足"); - } - break; - case FileInfo.FLAG_CANCEL: // 取消传输 - sizeMb = (((float) fileInfo.getSize() / 1024) / 1024); - curSizeMb = (((float) fileInfo.getProgress() / 1024) / 1024); - df = new DecimalFormat("0.00"); - sizeName = df.format(sizeMb) + "MB"; - curSizeName = df.format(curSizeMb) + "MB"; - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadSpeed.setText(curSizeName + "/" + sizeName); - holder.downloadStatus.setText(R.string.kc_canceled); - holder.downloadStatus.setBackgroundDrawable(new ColorDrawable(0)); - - holder.gameProgressbar.setProgress(percent); -// viewHolder.downloadPercentage.setText(percent + "%"); - break; - case FileInfo.FLAG_DEFAULT: // 传输中... - holder.gameProgressbar.setProgress(percent); - holder.downloadStatus.setText(R.string.kc_cancel); - holder.downloadStatus.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadStatus.setBackgroundResource(R.drawable.kuaichuan_cancel_bg); - - long speed = (fileInfo.getProgress() - mLastProgress) / 1024; - if (speed < 0) { - speed = 0; - } - -// viewHolder.downloadPercentage.setText(percent + "%"); - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.theme)); - holder.downloadSpeed.setText(String.format("%s(剩%s)", - SpeedUtils.getSpeed(speed), - SpeedUtils.getRemainTime(fileInfo.getSize(), fileInfo.getProgress(), speed * 1024))); - mLastProgress = fileInfo.getProgress(); - break; - } - - holder.downloadStatus.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - String s = holder.downloadStatus.getText().toString(); - if (mContext.getString(R.string.kc_cancel).equals(s)) { - mCancelListener.OnCancelPosition(holder.getAdapterPosition()); - } else if (mContext.getString(R.string.install).equals(s)) { - Intent installIntent = PackageUtils.getInstallIntent(mContext, - Environment.getExternalStorageDirectory() + "/GH-KC/" + fileInfo.getName() + ".apk"); - mContext.startActivity(installIntent); - } - } - }); - } - - @Override - public int getItemCount() { - if (mFileInfoList == null) { - return 0; - } - return mFileInfoList.size(); - } - - public interface OnReceiverCancelListener { - void OnCancelPosition(int position); - } -} diff --git a/app/src/main/java/com/gh/gamecenter/adapter/FileSenderAdapter.java b/app/src/main/java/com/gh/gamecenter/adapter/FileSenderAdapter.java deleted file mode 100644 index a8482c88d1..0000000000 --- a/app/src/main/java/com/gh/gamecenter/adapter/FileSenderAdapter.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.gh.gamecenter.adapter; - -import android.graphics.drawable.ColorDrawable; -import androidx.core.content.ContextCompat; -import android.view.View; -import android.view.ViewGroup; - -import com.lightgame.adapter.BaseRecyclerAdapter; -import com.gh.common.util.DisplayUtils; -import com.gh.common.util.SpeedUtils; -import com.lightgame.utils.Utils; -import com.gh.gamecenter.kuaichuan.view.FileSenderActivity; -import com.gh.gamecenter.R; -import com.gh.gamecenter.adapter.viewholder.KcSelectGameViewHolder; -import com.gh.gamecenter.kuaichuan.FileInfo; - -import java.text.DecimalFormat; -import java.util.List; - -/** - * Created by khy on 2017/1/20. - */ -public class FileSenderAdapter extends BaseRecyclerAdapter { - private List mFileInfos; - - private long mLastProgress; - - private OnCancelListener mCancelListener; - - public FileSenderAdapter(FileSenderActivity context, OnCancelListener listener, List fileInfos) { - super(context); - mCancelListener = listener; - mFileInfos = fileInfos; - mLastProgress = 0; - - } - - @Override - public KcSelectGameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = mLayoutInflater.inflate(R.layout.kc_game_select_item, parent, false); - return new KcSelectGameViewHolder(view); - } - - @Override - public void onBindViewHolder(final KcSelectGameViewHolder holder, int position) { - FileInfo fileInfo = mFileInfos.get(position); - - holder.gameNameAndSize.setText(fileInfo.getName()); - holder.downloadStatus.setVisibility(View.VISIBLE); - holder.sendOverIcon.setVisibility(View.GONE); - holder.gameProgressbar.setMax(100); - holder.gameProgressbar.setVisibility(View.VISIBLE); - holder.gameLlInfo.setVisibility(View.VISIBLE); - holder.gameSize.setVisibility(View.GONE); - holder.gameNameAndSize.setPadding(0, 0, 0, DisplayUtils.dip2px(mContext, 5)); - - holder.downloadSpeed.setText(R.string.kc_waiting); - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.gameProgressbar.setProgress(0); - holder.sendOverIcon.setVisibility(View.GONE); - holder.downloadStatus.setText(R.string.kc_cancel); - holder.downloadStatus.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadStatus.setBackgroundResource(R.drawable.kuaichuan_cancel_bg); - - int percent = (int) (fileInfo.getProgress() * 100 / fileInfo.getSize()); - holder.downloadPercentage.setText(percent + "%"); - - - if (fileInfo.getBitmap() != null) { - holder.gameThumb.setImageBitmap(fileInfo.getBitmap()); - } - - DecimalFormat df; - String sizeName; - String curSizeName; - double sizeMb; - double curSizeMb; - switch (fileInfo.getResult()) { - case FileInfo.FLAG_SUCCESS: // 传输完成... - holder.gameProgressbar.setProgress(100); - holder.downloadPercentage.setText("100%"); -// viewHolder.downloadStatus.setText("传输成功"); - holder.downloadStatus.setVisibility(View.GONE); - holder.sendOverIcon.setVisibility(View.VISIBLE); - double size = (((float) fileInfo.getSize() / 1024) / 1024); - df = new DecimalFormat("0.00"); - sizeName = df.format(size) + "MB"; - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadSpeed.setText(sizeName + "/" + sizeName); - break; - case FileInfo.FLAG_FAILURE: // 传输失败... - sizeMb = (((float) fileInfo.getSize() / 1024) / 1024); - curSizeMb = (((float) fileInfo.getProgress() / 1024) / 1024); - df = new DecimalFormat("0.00"); - sizeName = df.format(sizeMb) + "MB"; - if (curSizeMb == 0) { - curSizeName = "0.00MB"; - } else { - curSizeName = df.format(curSizeMb) + "MB"; - } - holder.gameProgressbar.setProgress(percent); - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadSpeed.setText(curSizeName + "/" + sizeName); - holder.downloadStatus.setText(R.string.kc_send_failuer); - holder.sendOverIcon.setVisibility(View.GONE); - holder.downloadStatus.setTextColor(ContextCompat.getColor(mContext, R.color.type_huodong)); - holder.downloadStatus.setBackgroundDrawable(new ColorDrawable(0)); -// viewHolder.downloadPercentage.setText(percent + "%"); - break; - case FileInfo.FLAG_CANCEL: // 取消传输 - sizeMb = (((float) fileInfo.getSize() / 1024) / 1024); - curSizeMb = (((float) fileInfo.getProgress() / 1024) / 1024); - df = new DecimalFormat("0.00"); - sizeName = df.format(sizeMb) + "MB"; - curSizeName = df.format(curSizeMb) + "MB"; - holder.sendOverIcon.setVisibility(View.GONE); - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadSpeed.setText(curSizeName + "/" + sizeName); - holder.downloadStatus.setText(R.string.kc_canceled); - holder.downloadStatus.setBackgroundDrawable(new ColorDrawable(0)); - - holder.gameProgressbar.setProgress(percent); - break; - case FileInfo.FLAG_DEFAULT: // 传输中... - holder.gameProgressbar.setProgress(percent); - holder.sendOverIcon.setVisibility(View.GONE); - holder.downloadStatus.setText(R.string.kc_cancel); - holder.downloadStatus.setTextColor(ContextCompat.getColor(mContext, R.color.content)); - holder.downloadStatus.setBackgroundResource(R.drawable.kuaichuan_cancel_bg); - - long speed = (fileInfo.getProgress() - mLastProgress) / 1024; - if (speed < 0) { - speed = 0; - } - -// viewHolder.downloadPercentage.setText(percent + "%"); - holder.downloadSpeed.setTextColor(ContextCompat.getColor(mContext, R.color.theme)); - holder.downloadSpeed.setText(String.format("%s(剩%s)", - SpeedUtils.getSpeed(speed), - SpeedUtils.getRemainTime(fileInfo.getSize(), fileInfo.getProgress(), speed * 1024))); - mLastProgress = fileInfo.getProgress(); - - holder.downloadStatus.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mCancelListener.OnCancelPosition(holder.getAdapterPosition()); - } - }); - break; - } - - } - - @Override - public int getItemCount() { - Utils.log("FileSenderActivity :: adapter" + mFileInfos.size()); - return mFileInfos.size(); - } - - public interface OnCancelListener { - void OnCancelPosition(int position); - } - -} diff --git a/app/src/main/java/com/gh/gamecenter/adapter/KcSelectGameAdapter.java b/app/src/main/java/com/gh/gamecenter/adapter/KcSelectGameAdapter.java deleted file mode 100644 index df571dfaae..0000000000 --- a/app/src/main/java/com/gh/gamecenter/adapter/KcSelectGameAdapter.java +++ /dev/null @@ -1,403 +0,0 @@ -package com.gh.gamecenter.adapter; - -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.RecyclerView; -import androidx.recyclerview.widget.RecyclerView.ViewHolder; -import android.text.Html; -import android.text.Spanned; -import android.view.Gravity; -import android.view.View; -import android.view.ViewGroup; -import android.widget.LinearLayout; -import android.widget.ProgressBar; -import android.widget.TextView; - -import com.gh.common.constant.ItemViewType; -import com.gh.common.util.BitmapUtils; -import com.gh.common.util.DisplayUtils; -import com.gh.gamecenter.kuaichuan.view.KcSelectGameActivity; -import com.gh.gamecenter.R; -import com.gh.gamecenter.adapter.viewholder.FooterViewHolder; -import com.gh.gamecenter.adapter.viewholder.KcSelectGameViewHolder; -import com.gh.gamecenter.adapter.viewholder.ReuseViewHolder; -import com.gh.gamecenter.entity.GameInstall; -import com.gh.gamecenter.entity.InstallGameEntity; -import com.gh.gamecenter.kuaichuan.FileInfo; -import com.gh.gamecenter.manager.PackagesManager; -import com.gh.gamecenter.retrofit.Response; -import com.halo.assistant.HaloApp; -import com.lightgame.adapter.BaseRecyclerAdapter; - -import java.io.File; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import io.reactivex.Observable; -import io.reactivex.ObservableEmitter; -import io.reactivex.ObservableOnSubscribe; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.schedulers.Schedulers; - -/** - * Created by khy on 2017/1/20. - */ -public class KcSelectGameAdapter extends BaseRecyclerAdapter { - - private TextView mSelectCount; - private TextView mInstallCount; - - private ProgressBar mSelectPb; - - private HashMap mSelectPosition; // 记录选择游戏的位置 - - private List mGameList; - - private List mApkList; - - private List sendOverList; //发送过的游戏 - - private boolean mIsLoadApp; - - public KcSelectGameAdapter(Context context, TextView selectCount, TextView installCount, - ProgressBar selectPb) { - super(context); - mSelectCount = selectCount; - mInstallCount = installCount; - mSelectPb = selectPb; - - mGameList = new ArrayList<>(); - mApkList = new ArrayList<>(); - mSelectPosition = new HashMap<>(); - - mIsLoadApp = false; - - sendOverList = (List) HaloApp.get(KcSelectGameActivity.KEY_FILE_INFO, false); - - - init(); - } - - //初始化 - private void init() { - - Observable.create(new ObservableOnSubscribe() { - @Override - public void subscribe(ObservableEmitter emitter) throws Exception { - ArrayList installedList = PackagesManager.filterSameApk(PackagesManager.getInstalledList()); - PackageManager pm = mContext.getPackageManager(); - List installedPackages = pm.getInstalledPackages(0); - - List game = new ArrayList<>(); // 防止数据加载时recyclerView首次刷新时造成的数据残缺 - List apk = new ArrayList<>(); - - for (PackageInfo installedPackage : installedPackages) { - if ((installedPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { - InstallGameEntity installGameEntity = new InstallGameEntity(); - installGameEntity.setGamePath(installedPackage.applicationInfo.sourceDir); - try { - Drawable drawable = installedPackage.applicationInfo.loadIcon(pm); - installGameEntity.setGameBm(BitmapUtils.drawableToBitmap(drawable, true)); - - installGameEntity.setGameVersion(installedPackage.versionName); - installGameEntity.setGameName(installedPackage.applicationInfo.loadLabel(pm).toString()); - installGameEntity.setPackageName(installedPackage.packageName); - - File file = new File(installedPackage.applicationInfo.sourceDir); - installGameEntity.setGameSize(file.length()); - boolean isAdd = false; - for (GameInstall gameInstall : installedList) { - if (installedPackage.packageName.equals(gameInstall.getPackageName())) { - game.add(installGameEntity); - isAdd = true; - break; - } - } - - if (!isAdd) { - apk.add(installGameEntity); - } - } catch (Exception e) { - - } - } - } - - mGameList.addAll(game); - mApkList.addAll(apk); - - for (int i = 0; i < (mGameList.size() + mApkList.size() + 1); i++) { - mSelectPosition.put(i, false); - } - - emitter.onComplete(); - } - }) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(new Response() { - @Override - public void onComplete() { - super.onComplete(); - mSelectPb.setVisibility(View.GONE); - mInstallCount.setText(mContext.getString(R.string.kc_installed_count, mGameList.size())); - notifyItemChanged(1, getItemCount() - 1); - } - }); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view; - switch (viewType) { - case ItemViewType.GAME_NORMAL: - view = mLayoutInflater.inflate(R.layout.kc_game_select_item, parent, false); - return new KcSelectGameViewHolder(view); - case ItemViewType.LOADING: - view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false); - return new FooterViewHolder(view); - case 101: - TextView textView = new TextView(mContext); - LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - DisplayUtils.dip2px(mContext, 40)); - if (mGameList.size() == 0) { - params.setMargins(0, DisplayUtils.dip2px(mContext, 43), 0, 0); - } - textView.setLayoutParams(params); - textView.setGravity(Gravity.CENTER_VERTICAL); - textView.setPadding(DisplayUtils.dip2px(mContext, 20), 0, 0, 0); - textView.setTextColor(ContextCompat.getColor(mContext, R.color.title)); - textView.setBackgroundColor(Color.WHITE); - textView.setText(mContext.getString(R.string.kc_installed_app_count, mApkList.size())); - return new ReuseViewHolder(textView); - default: - return null; - } - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - if (holder instanceof KcSelectGameViewHolder) { - if (mGameList.size() >= position + 1) { - initGameNormal((KcSelectGameViewHolder) holder, mGameList.get(position), position); - } else { - if (mGameList.isEmpty()) { - initGameNormal((KcSelectGameViewHolder) holder, mApkList.get(position - 1), position); - } else { - initGameNormal((KcSelectGameViewHolder) holder, mApkList.get(position - mGameList.size() - 1), position); - } - } - - } else if (holder instanceof FooterViewHolder) { - FooterViewHolder viewHolder = ((FooterViewHolder) holder); - if (position > 0) { - viewHolder.loading.setVisibility(View.GONE); - viewHolder.hint.setTextColor(ContextCompat.getColor(mContext, R.color.theme)); - viewHolder.hint.setText(R.string.kc_install_more); - holder.itemView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mIsLoadApp = true; - notifyItemRangeChanged(0, getItemCount() - 1); - } - }); - } - } - } - - @Override - public int getItemViewType(int position) { - if (mGameList.size() != 0 && position >= 0 && position < mGameList.size()) { - return ItemViewType.GAME_NORMAL; - } - - if (mGameList.isEmpty() && !mApkList.isEmpty() && position <= mApkList.size()) { - if (position == 0) { - return 101; - } - return ItemViewType.GAME_NORMAL; - } - - if (mGameList.size() == position) { - if (mIsLoadApp) { - return 101; - } else { - return ItemViewType.LOADING; - } - } - if (mIsLoadApp) { - return ItemViewType.GAME_NORMAL; - } - return ItemViewType.LOADING; - } - - @Override - public int getItemCount() { - if (mGameList.isEmpty() && mApkList.isEmpty()) { - return 1; - } - - if (mGameList.isEmpty() && !mApkList.isEmpty()) { - return mApkList.size() + 1; - } - - if (mIsLoadApp) { - return mGameList.size() + mApkList.size() + 1; - } - return mGameList.size() + 1; - } - - private void initGameNormal(final KcSelectGameViewHolder holder, final InstallGameEntity gameEntity, final int i) { - - LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - // 第一个 - if (i == 0) { - params.setMargins(0, DisplayUtils.dip2px(mContext, 49), 0, 0); - } else { - params.setMargins(0, 0, 0, 0); - } - - holder.itemView.setLayoutParams(params); - -// // 最后一个 -// if (i == mGameList.size() - 1) { -// ((CardLinearLayout) holder.itemView).setBottom(true); -// } else { -// ((CardLinearLayout) holder.itemView).setBottom(false); -// } - - double size = (((float) gameEntity.getGameSize() / 1024) / 1024); - DecimalFormat df = new DecimalFormat("0.00"); - String sizeName = df.format(size) + "MB"; - - Spanned spanned = Html.fromHtml(mContext.getString(R.string.kc_game_size, sizeName)); - holder.gameSize.setText(spanned); - holder.gameDes.setText(mContext.getString(R.string.kc_game_version, gameEntity.getGameVersion())); - - holder.gameThumb.setImageBitmap(gameEntity.getGameBm()); - - holder.gameNameAndSize.setText(gameEntity.getGameName()); - holder.gameNameAndSize.setTextColor(ContextCompat.getColor(mContext, R.color.title)); - if (sendOverList != null && sendOverList.size() > 0) { - for (FileInfo fileInfo : sendOverList) { - if (fileInfo.getFilePath().equals(gameEntity.getGamePath())) { - holder.gameNameAndSize.setTextColor(ContextCompat.getColor(mContext, R.color.hint)); - break; - } - } - } - - holder.selectCB.setVisibility(View.VISIBLE); - if (mSelectPosition.get(i) != null && mSelectPosition.get(i)) { - holder.selectCB.setChecked(true); - } else { - holder.selectCB.setChecked(false); - } - - holder.selectCB.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (mSelectPosition.get(i)) { - checkBoxControl(false, i); - holder.selectCB.setChecked(false); - } else { - checkBoxControl(true, i); - holder.selectCB.setChecked(true); - } - } - }); - - holder.checkBoxRl.setVisibility(View.VISIBLE); - holder.checkBoxRl.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - - toggleChecked(i, holder); - -// if (mSelectPosition.get(i)) { -// checkBoxControl(false, i); -// holder.selectCB.setChecked(false); -// } else { -// checkBoxControl(true, i); -// holder.selectCB.setChecked(true); -// } - - } - }); - - } - - private void toggleChecked(int i, KcSelectGameViewHolder holder) { - boolean checked = mSelectPosition.get(i); - checkBoxControl(!checked, i); - holder.selectCB.setChecked(!checked); - } - - private void checkBoxControl(boolean isChecked, int i) { - if (isChecked) { - mSelectPosition.put(i, true); - } else { - mSelectPosition.put(i, false); - } - - int count = 0; - for (Integer integer : mSelectPosition.keySet()) { - if (mSelectPosition.get(integer)) { - count++; - } - } - - if (count == 0) { - mSelectCount.setText(R.string.kc_send); - } else { - mSelectCount.setText("发送(" + count + ")"); - } - } - - public List getSelectData() { - List fileInfos = new ArrayList<>(); - long l = System.currentTimeMillis(); - for (int i = 0; i < mSelectPosition.keySet().size(); i++) { - if (mSelectPosition.get(i) != null && mSelectPosition.get(i)) { - InstallGameEntity installGameEntity; - if (i + 1 <= mGameList.size()) { - installGameEntity = mGameList.get(i); - } else { - installGameEntity = mApkList.get(i - mGameList.size() - 1); - } - FileInfo fileInfo = new FileInfo(); - fileInfo.setName(installGameEntity.getGameName()); - fileInfo.setFilePath(installGameEntity.getGamePath()); - fileInfo.setSize(installGameEntity.getGameSize()); - fileInfo.setBitmap(installGameEntity.getGameBm()); - fileInfo.setPackageName(installGameEntity.getPackageName()); - fileInfo.setFileTag(String.valueOf(l + i)); - fileInfos.add(fileInfo); - } - } - - - return fileInfos; - } - - public void setSelectPosition(HashMap selectPosition) { - this.mSelectPosition = selectPosition; - } - - public int getGameSize() { - return mGameList.size(); - } - - public int getAppSize() { - return mApkList.size(); - } - -} diff --git a/app/src/main/java/com/gh/gamecenter/download/GameDownloadFragment.java b/app/src/main/java/com/gh/gamecenter/download/GameDownloadFragment.java index bb0a9bf210..95ac37dbea 100644 --- a/app/src/main/java/com/gh/gamecenter/download/GameDownloadFragment.java +++ b/app/src/main/java/com/gh/gamecenter/download/GameDownloadFragment.java @@ -43,8 +43,6 @@ import org.greenrobot.eventbus.ThreadMode; import butterknife.BindView; import butterknife.OnClick; -import static com.gh.gamecenter.kuaichuan.KuaichuanNotification.NOTIFY_ID; - /** * 下载管理 fragment @@ -355,12 +353,6 @@ public class GameDownloadFragment extends BaseFragment implements View.OnClickLi } } } - - if ("安装".equals(busFour.getType())) { - // 取消快传完成通知栏 - NotificationManager nManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); - nManager.cancel(packageName, NOTIFY_ID); - } } @Subscribe(threadMode = ThreadMode.MAIN) diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/BaseTransfer.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/BaseTransfer.java deleted file mode 100644 index 69682f5d6a..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/BaseTransfer.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -/** - * Created by khy on 2017/1/20. - */ -public abstract class BaseTransfer implements Transferable { - - /** - * 头部分割字符 - */ - public static final String SPERATOR = "::"; - - /** - * 字节数组长度 - */ - public static final int BYTE_SIZE_HEADER = 1024 * 10; - public static final int BYTE_SIZE_SCREENSHOT = 1024 * 40; - public static final int BYTE_SIZE_DATA = 1024 * 4; - - /** - * 传输文件类型 - */ - public static final int TYPE_FILE = 1; //文件类型 - public static final int TYPE_MSG = 2; //消息类型 - - /** - * 传输字节类型 - */ - public static final String UTF_8 = "UTF-8"; -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/Constant.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/Constant.java deleted file mode 100644 index 3430885be6..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/Constant.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -/** - * 快传常量类 - */ -public class Constant { - /** - * 写文件的请求码 - */ - public static final int REQUEST_CODE_WRITE_FILE = 200; - - /** - * 读取文件的请求码 - */ - public static final int REQUEST_CODE_READ_FILE = 201; - - /** - * ServerSocket 默认IP - */ - public static final String DEFAULT_SERVER_IP = "logo.168.43.1"; - - /** - * Wifi连接上时 未分配默认的Ip地址 - */ - public static final String DEFAULT_UNKOWN_IP = "0.0.0.0"; - - /** - * 最大尝试数 - */ - public static final int DEFAULT_TRY_TIME = 10; - - /** - * 文件传输监听 默认端口 - */ - public static final int DEFAULT_SERVER_PORT = 8080; - - /** - * UDP通信服务 默认端口 - */ - public static final int DEFAULT_SERVER_COM_PORT = 8011; - - /** - * UDP通信服务 传送中的默认端口 - */ - public static final int DEFAULT_SERVER_SENDING_PORT = 8090; - - - /** - * Android微型服务器 默认端口 - */ - public static final int DEFAULT_MICRO_SERVER_PORT = 3100; - - - /** - * 数据传输端口标识 - */ - public static final String KEY_IP_PORT_INFO = "KEY_IP_PORT_INFO"; - - /** - * 数据传输apk文件数据标识 - */ - public static final String KEY_IP_FILE_INFO = "KEY_IP_FILE_INFO"; - - - /** - * 文件发送方 与 文件接收方 通信信息 - */ - public static final String MSG_FILE_RECEIVER_INIT = "MSG_FILE_RECEIVER_INIT"; - public static final String MSG_FILE_RECEIVER_INIT_SUCCESS = "MSG_FILE_RECEIVER_INIT_SUCCESS"; - public static final String MSG_FILE_SENDER_START = "MSG_FILE_SENDER_START"; - public static final String MSG_RECEIVER_CANCEL = "MSG_RECEIVER_CANCEL"; - public static final String MSG_ADD_DATA_OVER = "MSG_ADD_DATA_OVER"; // 继续发送apk列表完成标识 TAG - - -} - diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/DownloadUriHandler.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/DownloadUriHandler.java deleted file mode 100644 index dbc028d157..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/DownloadUriHandler.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.app.Activity; - -import com.lightgame.utils.Utils; -import com.gh.gamecenter.entity.KcWebRequestEntity; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.net.Socket; - -/** - * Created by khy on 2017/2/6. - * 快传 网页传下载文件处理 - */ -public class DownloadUriHandler implements KcUriHandler { - - public static final String DOWNLOAD_PREFIX = "/download/"; - private Activity mActivity; - - public DownloadUriHandler(Activity activity) { - this.mActivity = activity; - } - - @Override - public boolean matches(String uri) { - return uri.startsWith(DOWNLOAD_PREFIX); - } - - @Override - public void handler(KcWebRequestEntity request) { - String absolutePath = mActivity.getApplicationContext().getPackageResourcePath(); // 光环助手安装包路径 - Socket socket = request.getSocket(); - - File file = new File(absolutePath); - long fileSize = file.length(); - - OutputStream os; - PrintStream printStream = null; - try { - os = socket.getOutputStream(); - printStream = new PrintStream(os); - } catch (IOException e) { - e.printStackTrace(); - } - - if (printStream == null) return; - - printStream.println("HTTP/1.0 200 OK"); - printStream.println("Content-Length:" + fileSize); - printStream.println("Content-Type:application/octet-stream"); - printStream.println(); - - FileInputStream fis = null; - - try { - fis = new FileInputStream(file); - - int len = 0; - byte[] bytes = new byte[2048]; - int count = 0; - - while ((len = fis.read(bytes)) != -1) { - count = count + len; - printStream.write(bytes, 0, len); - } - Utils.log("====写入完成长度::" + count); - Thread.sleep(500); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (fis != null) { - try { - fis.close(); - fis = null; - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - printStream.flush(); - printStream.close(); - } - - @Override - public void destroy() { - this.mActivity = null; - } -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/FileInfo.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/FileInfo.java deleted file mode 100644 index b62d35679c..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/FileInfo.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.graphics.Bitmap; -import android.os.Parcel; -import android.os.Parcelable; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.Serializable; - -/** - * Created by khy on 2017/1/20. - */ -public class FileInfo implements Parcelable, Serializable { - - /** - * 文件传输的标识 - */ - // -1 失败 0 发送中 1 成功 2发送取消 3已安装 - public static final int FLAG_NO_MEMORY = 5; - public static final int FLAG_INSTALLED = 4; - public static final int FLAG_CANCEL = 3; - public static final int FLAG_SUCCESS = 2; - public static final int FLAG_DEFAULT = 1; - public static final int FLAG_FAILURE = -1; - - //必要属性 - public static final Creator CREATOR = new Creator() { - @Override - public FileInfo createFromParcel(Parcel source) { - return new FileInfo(source); - } - - @Override - public FileInfo[] newArray(int size) { - return new FileInfo[size]; - } - }; - /** - * 文件路径 - */ - private String filePath; - - //非必要属性 - /** - * 文件大小 - */ - private long size; - /** - * 文件显示名称 - */ - private String name; - /** - * 文件缩略图 - */ - private Bitmap bitmap; - /** - * 文件标识 - 时间戳 - */ - private String fileTag; - /** - * 文件传送的结果 - */ - private int result; - /** - * 下载进度 - */ - private long progress; - private String packageName; - - public FileInfo() { - - } - - public FileInfo(String filePath, long size) { - this.filePath = filePath; - this.size = size; - } - - protected FileInfo(Parcel in) { - this.filePath = in.readString(); - this.size = in.readLong(); - this.name = in.readString(); - this.bitmap = in.readParcelable(Bitmap.class.getClassLoader()); - this.fileTag = in.readString(); - this.result = in.readInt(); - this.progress = in.readLong(); - this.packageName = in.readString(); - } - - public static String toJsonStr(FileInfo fileInfo) { - JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("filePath", fileInfo.getFilePath()); - jsonObject.put("size", fileInfo.getSize()); - jsonObject.put("name", fileInfo.getName()); - jsonObject.put("packageName", fileInfo.getPackageName()); - jsonObject.put("fileTag", fileInfo.getFileTag()); - } catch (JSONException e) { - e.printStackTrace(); - } - return jsonObject.toString(); - } - - public String getFilePath() { - return filePath; - } - - public long getSize() { - return size; - } - - public void setSize(long size) { - this.size = size; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPackageName() { - return packageName; - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public String getFileTag() { - return fileTag; - } - - public void setFileTag(String fileTag) { - this.fileTag = fileTag; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - public static FileInfo toObject(String jsonStr) { - FileInfo fileInfo = new FileInfo(); - try { - JSONObject jsonObject = new JSONObject(jsonStr); - String filePath = (String) jsonObject.get("filePath"); - long size = jsonObject.getLong("size"); - String name = jsonObject.getString("name"); - String packageName = jsonObject.getString("packageName"); - String fileTag = jsonObject.getString("fileTag"); - - fileInfo.setFilePath(filePath); - fileInfo.setSize(size); - fileInfo.setName(name); - fileInfo.setPackageName(packageName); - fileInfo.setFileTag(fileTag); - } catch (JSONException e) { - e.printStackTrace(); - } - return fileInfo; - } - - public long getProgress() { - return progress; - } - - public void setProgress(long progress) { - this.progress = progress; - } - - public Bitmap getBitmap() { - return bitmap; - } - - public void setBitmap(Bitmap bitmap) { - this.bitmap = bitmap; - } - - public int getResult() { - return result; - } - - public void setResult(int result) { - this.result = result; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(this.filePath); - dest.writeLong(this.size); - dest.writeString(this.name); - dest.writeParcelable(this.bitmap, flags); - dest.writeString(this.fileTag); - dest.writeInt(this.result); - dest.writeLong(this.progress); - dest.writeString(this.packageName); - } -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/FileReceiver.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/FileReceiver.java deleted file mode 100644 index f972c0f256..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/FileReceiver.java +++ /dev/null @@ -1,307 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.os.Environment; -import android.text.TextUtils; - -import com.lightgame.download.FileUtils; -import com.gh.common.util.StringUtils; -import com.lightgame.utils.Utils; -import com.gh.gamecenter.kuaichuan.view.FileReceiverActivity; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; -import java.text.DecimalFormat; - - -/** - * 快传传输核心类 - */ -public class FileReceiver extends BaseTransfer implements Runnable { - - /** - * 控制线程暂停 恢复 - */ - private final Object LOCK = new Object(); - Context mContext; - boolean mIsPaused = false; - boolean isCancel = false; - /** - * 文件接收的监听 - */ - OnReceiveListener mOnReceiveListener; - /** - * Socket的输入输出流 - */ - private Socket mSocket; - private InputStream mInputStream; - /** - * 传送文件的信息 - */ - private FileInfo mFileInfo; - - - public FileReceiver(Socket mSocket, FileReceiverActivity activity) { - this.mSocket = mSocket; - this.mContext = activity; - } - - public void setOnReceiveListener(OnReceiveListener mOnReceiveListener) { - this.mOnReceiveListener = mOnReceiveListener; - } - - @Override - public void run() { - //初始化 - try { - if (mOnReceiveListener != null) mOnReceiveListener.onStart(); - init(); - } catch (Exception e) { - e.printStackTrace(); - Utils.log("FileReceiver init() --->>> occur expection" + e.toString()); - if (mOnReceiveListener != null) mOnReceiveListener.onFailure(e); - } - - //解析头部 - try { - parseHeader(); - } catch (Exception e) { - e.printStackTrace(); - Utils.log("FileReceiver parseHeader() --->>> occur expection" + e.toString()); - if (mOnReceiveListener != null) mOnReceiveListener.onFailure(e); - } - - - //解析主体 - try { - parseBody(); - } catch (Exception e) { - e.printStackTrace(); - Utils.log("FileReceiver parseBody() --->>> occur expection" + e.toString()); - if (mOnReceiveListener != null) mOnReceiveListener.onFailure(e); - } - - //结束 - try { - finish(); - } catch (Exception e) { - e.printStackTrace(); - Utils.log("FileReceiver finish() --->>> occur expection" + e.toString()); - if (mOnReceiveListener != null) mOnReceiveListener.onFailure(e); - } - - - } - - @Override - public void init() throws Exception { - if (this.mSocket != null) { - this.mInputStream = mSocket.getInputStream(); - } - } - - @Override - public void parseHeader() throws IOException { - Utils.log("parseHeader######>>>start"); - isCancel = false; - //Are you sure can read the 1024 byte accurately? - //读取header部分 - byte[] headerBytes = new byte[BYTE_SIZE_HEADER]; - int headTotal = 0; - int readByte = -1; - //开始读取header - while ((readByte = mInputStream.read()) != -1) { - headerBytes[headTotal] = (byte) readByte; - - headTotal++; - if (headTotal == headerBytes.length) { - break; - } - } - Utils.log("FileReceiver receive header size------>>>" + headTotal); - Utils.log("FileReceiver receive header------>>>" + new String(headerBytes, UTF_8)); - - - //读取缩略图部分 - byte[] screenshotBytes = new byte[BYTE_SIZE_SCREENSHOT]; - int screenshotTotal = 0; - int sreadByte = -1; - //开始读取缩略图 - while ((sreadByte = mInputStream.read()) != -1) { - screenshotBytes[screenshotTotal] = (byte) sreadByte; - - screenshotTotal++; - if (screenshotTotal == screenshotBytes.length) { - break; - } - } - - Bitmap bitmap = BitmapFactory.decodeByteArray(screenshotBytes, 0, screenshotBytes.length); -// Utils.log("FileReceiver receive screenshot size------>>>" + screenshotTotal); -// MLog.i(TAG, "FileReceiver receive screenshot------>>>" + new String(headerBytes, UTF_8)); - - - //解析header - String jsonStr = new String(headerBytes, UTF_8); - Utils.log("===接收到的json列表数据::" + jsonStr); - - String[] strArray = jsonStr.split(SPERATOR); - jsonStr = strArray[1].trim(); - mFileInfo = FileInfo.toObject(jsonStr); - mFileInfo.setBitmap(bitmap); - if (mOnReceiveListener != null) mOnReceiveListener.onGetFileInfo(mFileInfo); -// String fileName = getFileName(fileInfo.getFilePath()); -// int fileSize = fileInfo.getSize(); - Utils.log("parseHeader######>>>end"); - } - - @Override - public void parseBody() throws Exception { - Utils.log("parseBody######>>>start"); - - //写入文件 - long fileSize = mFileInfo.getSize(); - - // 快传存储路径 - String path = Environment.getExternalStorageDirectory() + "/GH-KC"; - - File dirFile = new File(path); - if (!dirFile.exists()) { - dirFile.mkdirs(); - } - - File file = new File(dirFile, mFileInfo.getName() + ".apk"); - - Utils.log("FileReceiver" + file.getAbsolutePath()); - OutputStream bos = new FileOutputStream(file); - - byte[] bytes = new byte[BYTE_SIZE_DATA]; - long total = 0; - int len = 0; - - long sTime = System.currentTimeMillis(); - long eTime = 0; - - double size = (((float) mFileInfo.getSize() / 1024) / 1024); - DecimalFormat df = new DecimalFormat("#.00"); - String sizeName = df.format(size) + "MB"; - - String canDownload = FileUtils.isCanDownload(mContext, sizeName); - while ((len = mInputStream.read(bytes)) != -1) { - synchronized (LOCK) { - if (mIsPaused) { - try { - LOCK.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - if (!TextUtils.isEmpty(canDownload)) break; // 内存不足 拒绝接受 - - bos.write(bytes, 0, len); - total = total + len; - eTime = System.currentTimeMillis(); - if (eTime - sTime > 500) { //大于500ms 才进行一次监听 - sTime = eTime; - if (mOnReceiveListener != null) mOnReceiveListener.onProgress(total, fileSize); - } - - if (isCancel) { - break; - } - } - -// bos.write(bytes, 0, len); -// total = total + len; -// if(mOnReceiveListener != null) mOnReceiveListener.onProgress(total, fileSize); - } - - Utils.log(StringUtils.buildString("接收完成对比 游戏总大小:", String.valueOf(fileSize), "游戏接收大小:", String.valueOf(total))); - - if (!TextUtils.isEmpty(canDownload)) { // 内存不足回调 - if (mOnReceiveListener != null) mOnReceiveListener.onNoMemory(); - return; - } - - if (total == fileSize) { - if (mOnReceiveListener != null) mOnReceiveListener.onSuccess(); - } else { - if (mOnReceiveListener != null) mOnReceiveListener.onCancel(); - } - - } - - @Override - public void finish() { - - if (mInputStream != null) { - try { - mInputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - if (mSocket != null && mSocket.isConnected()) { - try { - mSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - Utils.log("FileReceiver close socket######>>>"); - } - - /** - * 停止线程下载 - */ - public void pause() { - synchronized (LOCK) { - mIsPaused = true; - LOCK.notifyAll(); - } - } - - /** - * 重新开始线程下载 - */ - public void resume() { - synchronized (LOCK) { - mIsPaused = false; - LOCK.notifyAll(); - } - } - - public void cancel() { - isCancel = true; - } - - /** - * 文件接收的监听 - */ - public interface OnReceiveListener { - void onStart(); - - void onGetFileInfo(FileInfo fileInfo); - - void onProgress(long progress, long total); - - void onSuccess(); - - void onFailure(Throwable t); - - void onCancel(); - - void onNoMemory(); - } - -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/FileSender.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/FileSender.java deleted file mode 100644 index 6bcc4443b7..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/FileSender.java +++ /dev/null @@ -1,311 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import android.media.ThumbnailUtils; - -import com.lightgame.utils.Utils; - -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; - - -/** - * 快传发送核心类 - */ -public class FileSender extends BaseTransfer implements Runnable { - - /** - * 控制线程暂停 恢复 - */ - private final Object LOCK = new Object(); - Context mContext; - boolean mIsPaused = false; - /** - * 判断此线程是否完毕 - */ - boolean mIsFinished = false; - /** - * 取消操作 - */ - boolean mIsCancel = false; - /** - * 文件传送的监听 - */ - OnSendListener mOnSendListener; - /** - * 传送文件目标的地址以及端口 - */ - private String mServerIpAddress; - private int mPort; - /** - * 传送文件的信息 - */ - private FileInfo mFileInfo; - /** - * Socket的输入输出流 - */ - private Socket mSocket; - private OutputStream mOutputStream; - - public FileSender(Context context, FileInfo mFileInfo, String mServerIpAddress, int mPort) { - this.mContext = context; - this.mFileInfo = mFileInfo; - this.mServerIpAddress = mServerIpAddress; - this.mPort = mPort; - } - - public void setOnSendListener(OnSendListener mOnSendListener) { - this.mOnSendListener = mOnSendListener; - } - - @Override - public void run() { - - //初始化 - try { - if (mOnSendListener != null) mOnSendListener.onStart(); - init(); - } catch (Exception e) { - e.printStackTrace(); - Utils.log("nit() --->>> occur expection" + e.toString()); - if (mOnSendListener != null) mOnSendListener.onFailure(e, mFileInfo); - } - - //解析头部 - try { - parseHeader(); - } catch (Exception e) { - e.printStackTrace(); - Utils.log("parseHeader() --->>> occur expection" + e.toString()); - if (mOnSendListener != null) mOnSendListener.onFailure(e, mFileInfo); - } - - //解析主体 - try { - parseBody(); - } catch (Exception e) { - e.printStackTrace(); - Utils.log("parseBody() --->>> occur expection" + e.toString()); - if (mOnSendListener != null) mOnSendListener.onFailure(e, mFileInfo); - } - - //结束 - try { - finish(); - } catch (Exception e) { - e.printStackTrace(); - Utils.log("finish() --->>> occur expection" + e.toString()); - if (mOnSendListener != null) mOnSendListener.onFailure(e, mFileInfo); - } - - - } - - @Override - public void init() throws Exception { - Utils.log("=== init():" + mServerIpAddress + "==" + mPort); - this.mSocket = new Socket(mServerIpAddress, mPort); - OutputStream os = this.mSocket.getOutputStream(); - mOutputStream = new BufferedOutputStream(os); - } - - @Override - public void parseHeader() throws Exception { - Utils.log("parseHeader######>>>start"); - - //拼接header - StringBuilder headerSb = new StringBuilder(); - String jsonStr = FileInfo.toJsonStr(mFileInfo); - jsonStr = TYPE_FILE + SPERATOR + jsonStr; - headerSb.append(jsonStr); - int leftLen = BYTE_SIZE_HEADER - jsonStr.getBytes(UTF_8).length; //对于英文是一个字母对应一个字节,中文的情况下对应两个字节。剩余字节数不应该是字节数 - for (int i = 0; i < leftLen; i++) { - headerSb.append(" "); - } - byte[] headbytes = headerSb.toString().getBytes(UTF_8); - - Utils.log("parseHeader======" + headerSb); - //写入header - mOutputStream.write(headbytes); - - - //拼接缩略图 - StringBuilder screenshotSb = new StringBuilder(); - - int ssByteArraySize = 0; - - //缩略图的分类处理 - if (mFileInfo != null) { - Bitmap screenshot; - byte[] bytes; - - Drawable apkThumbnail = WifiUtils.getApkThumbnail(mContext, mFileInfo.getFilePath()); - Bitmap bitmap = WifiUtils.drawableToBitmap(apkThumbnail); - screenshot = ThumbnailUtils.extractThumbnail(bitmap, 96, 96); - if (screenshot != null) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - screenshot.compress(Bitmap.CompressFormat.PNG, 100, baos); - bytes = baos.toByteArray(); - ssByteArraySize = bytes.length; - mOutputStream.write(bytes); - } - } - - int ssLeftLen = BYTE_SIZE_SCREENSHOT - ssByteArraySize; //缩略图剩余的字节数 - for (int i = 0; i < ssLeftLen; i++) { - screenshotSb.append(" "); - } - byte[] screenshotBytes = screenshotSb.toString().getBytes(UTF_8); - - //写入缩略图 - mOutputStream.write(screenshotBytes); - - Utils.log("FileSender screenshot write------>>>" + (ssByteArraySize + ssLeftLen)); - - Utils.log("FileSender header write------>>>" + new String(headbytes, UTF_8)); - - Utils.log("parseHeader######>>>end"); - } - - @Override - public void parseBody() throws Exception { - Utils.log("parseBody######>>>start"); - - //写入文件 - long fileSize = mFileInfo.getSize(); - InputStream fis = new FileInputStream(new File(mFileInfo.getFilePath())); - - byte[] bytes = new byte[BYTE_SIZE_DATA]; - long total = 0; - int len = 0; - - long sTime = System.currentTimeMillis(); - long eTime = 0; - while ((len = fis.read(bytes)) != -1) { - synchronized (LOCK) { - if (mIsPaused) { - try { - LOCK.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - if (mIsCancel) { - if (mOnSendListener != null) mOnSendListener.onCancel(mFileInfo); - break; - } - - mOutputStream.write(bytes, 0, len); - total = total + len; - eTime = System.currentTimeMillis(); - if (eTime - sTime > 500) { //大于500ms 才进行一次监听 - sTime = eTime; - if (mOnSendListener != null) mOnSendListener.onProgress(total, fileSize); - } - } - - -// mOutputStream.write(bytes, 0, len); -// total = total + len; -// if(mOnSendListener != null) mOnSendListener.onProgress(total, fileSize); - } - - Utils.log("FileSender body write######>>>" + total); - - mOutputStream.flush(); - //每一次socket连接就是一个通信,如果当前OutputStream不关闭的话。FileReceiver端会阻塞在那里 - mOutputStream.close(); - Utils.log("parseBody######>>>end"); - - if (!mIsCancel) { - if (mOnSendListener != null) mOnSendListener.onSuccess(mFileInfo); - } - - mIsFinished = true; - } - - @Override - public void finish() { - - if (mOutputStream != null) { - try { - mOutputStream.close(); - } catch (Exception e) { - - } - } - - if (mSocket != null && mSocket.isConnected()) { - try { - mSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - Utils.log("FileSender close socket######>>>"); - } - - /** - * 停止线程下载 - */ - public void pause() { - synchronized (LOCK) { - mIsPaused = true; - LOCK.notifyAll(); - } - } - - /** - * 重新开始线程下载 - */ - public void resume() { - synchronized (LOCK) { - mIsPaused = false; - LOCK.notifyAll(); - } - } - - /** - * 取消操作 - */ - public void cancel() { - mIsCancel = true; - } - - - /** - * 文件是否在传送中 - * - * @return - */ - public boolean isRunning() { - return !mIsFinished; - } - - - /** - * 文件传送的监听 - */ - public interface OnSendListener { - void onStart(); - - void onProgress(long progress, long total); - - void onSuccess(FileInfo fileInfo); - - void onFailure(Throwable t, FileInfo fileInfo); - - void onCancel(FileInfo fileInfo); - } - -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/HotspotManager.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/HotspotManager.java deleted file mode 100644 index 87f05a33d8..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/HotspotManager.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.content.Context; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiManager; -import android.text.TextUtils; - -import com.lightgame.utils.Utils; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * Created by khy on 2017/1/20. - */ -public class HotspotManager { - - private static String apSSID; - private static String apKey; - private static String apKeyMgmt; - - - public static void initApData(Context context) { - try { - WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); - //拿到getWifiApConfiguration()方法 - Method method = manager.getClass().getDeclaredMethod("getWifiApConfiguration"); - //调用getWifiApConfiguration()方法,获取到 热点的WifiConfiguration - WifiConfiguration configuration = (WifiConfiguration) method.invoke(manager); - apSSID = configuration.SSID; - apKey = configuration.preSharedKey; - apKeyMgmt = configuration.allowedKeyManagement.toString(); - Utils.log("=====名称:" + apSSID); - Utils.log("=====密码:" + apKey); - Utils.log("=====安全:" + apKeyMgmt); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - - // 初始化用户热点 回退到原始状态并关闭热点 - public static void initUserAp(Context context) { - android.net.wifi.WifiManager wifimanager = (android.net.wifi.WifiManager) context.getSystemService(context.WIFI_SERVICE); - WifiConfiguration wificonfiguration; - try { - wificonfiguration = new WifiConfiguration(); - wificonfiguration.SSID = apSSID; - if (!TextUtils.isEmpty(apKey)) { - wificonfiguration.preSharedKey = apKey; - wificonfiguration.allowedKeyManagement.set(4); //WPA2_PSK - } - // if WiFi is on, turn it off - if (isApOn(context)) { - wifimanager.setWifiEnabled(false); - // if ap is on and then disable ap - disableAp(context); - } - Method method = wifimanager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class); - method.invoke(wifimanager, wificonfiguration); - } catch (Exception e) { - Utils.log("======" + e.toString()); - e.printStackTrace(); - } - } - - - //检查热点开关 - public static boolean isApOn(Context context) { - android.net.wifi.WifiManager wifimanager = (android.net.wifi.WifiManager) context.getSystemService(context.WIFI_SERVICE); - try { - Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled"); - method.setAccessible(true); - return (Boolean) method.invoke(wifimanager); - } catch (Throwable ignored) { - ignored.printStackTrace(); - } - return false; - } - - //关闭WiFi热点 - public static void disableAp(Context context) { - android.net.wifi.WifiManager wifimanager = (android.net.wifi.WifiManager) context.getSystemService(context.WIFI_SERVICE); - try { - Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); - method.invoke(wifimanager, null, false); - } catch (Throwable ignored) { - ignored.printStackTrace(); - } - } - - - // toggle wifi hotspot on or off, and specify the hotspot name - public static boolean configApState(Context context, String apName) { - if (WifiMgr.getInstance(context).isWifiEnable()) { - WifiMgr.getInstance(context).closeWifi(); - } - - android.net.wifi.WifiManager wifimanager = (android.net.wifi.WifiManager) context.getSystemService(context.WIFI_SERVICE); - WifiConfiguration wificonfiguration; - try { - wificonfiguration = new WifiConfiguration(); - wificonfiguration.SSID = apName; - // if WiFi is on, turn it off - if (isApOn(context)) { - wifimanager.setWifiEnabled(false); - // if ap is on and then disable ap - disableAp(context); - } - Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); - method.invoke(wifimanager, wificonfiguration, !isApOn(context)); - return true; - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/HtmlUriHandler.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/HtmlUriHandler.java deleted file mode 100644 index e45e34c3c4..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/HtmlUriHandler.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.app.Activity; - -import com.lightgame.utils.Utils; -import com.gh.gamecenter.entity.KcWebRequestEntity; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; - -/** - * Created by khy on 2017/2/6. - * 快传 网页传加载网页 - */ -public class HtmlUriHandler implements KcUriHandler { - private Activity mActivity; - - public HtmlUriHandler(Activity activity) { - this.mActivity = activity; - } - - @Override - public boolean matches(String uri) { - if (uri == null || uri.equals("") || uri.equals("/")) { - return true; - } - return false; - } - - @Override - public void handler(KcWebRequestEntity request) { - String homeHtml = null; - try { - InputStream is = this.mActivity.getAssets().open("Home.html"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - int len = 0; - byte[] bytes = new byte[2048]; - - while ((len = is.read(bytes)) != -1) { - baos.write(bytes, 0, len); - } - - homeHtml = baos.toString("UTF-8"); - } catch (Exception e) { - Utils.log("===加载asset HTML文件异常" + e.toString()); - e.printStackTrace(); - } - - if (request.getSocket() != null && homeHtml != null) { - OutputStream outputStream = null; - PrintStream printStream = null; - - try { - outputStream = request.getSocket().getOutputStream(); - printStream = new PrintStream(outputStream); - printStream.println("HTTP/1.0 200 OK"); - printStream.println("Content-Length:" + homeHtml.length()); - printStream.println("Content-Type:text/html"); - printStream.println("Cache-Control:no-cache"); - printStream.println("Pragma:no-cache"); - printStream.println("Expires:0"); - printStream.println(); - - - byte[] bytes = homeHtml.getBytes("UTF-8"); - printStream.write(bytes); - - Utils.log("====传输大小::" + homeHtml.length()); - } catch (IOException e) { - Utils.log("===快传网页加载异常" + e.toString()); - e.printStackTrace(); - } finally { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if (outputStream != null) { - try { - outputStream.close(); - outputStream = null; - } catch (Exception e) { - e.printStackTrace(); - } - } - if (printStream != null) { - try { - printStream.flush(); - printStream.close(); - printStream = null; - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } else { - Utils.log("===HTML 或者 Socket为空"); - } - Utils.log("===快传网页加载完成"); - } - - @Override - public void destroy() { - mActivity = null; - } -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/ImageUriHandler.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/ImageUriHandler.java deleted file mode 100644 index 5c3ad73195..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/ImageUriHandler.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.app.Activity; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; - -import com.lightgame.utils.Utils; -import com.gh.gamecenter.R; -import com.gh.gamecenter.entity.KcWebRequestEntity; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.net.Socket; - -/** - * Created by khy on 2017/2/6. - * 快传 网页传加载图片 - */ -public class ImageUriHandler implements KcUriHandler { - public static final String IMAGE_PREFIX = "/image/"; - Activity mActivity; - - public ImageUriHandler(Activity mActivity) { - this.mActivity = mActivity; - } - - @Override - public boolean matches(String uri) { - return uri.startsWith(IMAGE_PREFIX); - } - - @Override - public void handler(KcWebRequestEntity request) { - - Utils.log("====开始加载图片"); - Socket socket = request.getSocket(); - OutputStream os; - PrintStream printStream = null; - try { - os = socket.getOutputStream(); - printStream = new PrintStream(os); - } catch (IOException e) { - e.printStackTrace(); - } - - Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.logo); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); - InputStream inputimage = new ByteArrayInputStream(baos.toByteArray()); - BufferedInputStream ips = new BufferedInputStream(inputimage); - - int bitmapSize = baos.toByteArray().length; - Utils.log("====开始加载图片大小::" + bitmapSize); - - printStream.println("HTTP/1.0 200 OK"); - printStream.println("Content-Length:" + bitmapSize); - printStream.println("Content-Type:multipart/mixed,text/html,image/png,image/jpeg,image/gif,image/x-xbitmap,application/vnd.oma.dd+xml,*/*"); - printStream.println(); - - try { - int len = 0; - int i = 0; - byte[] bytes = new byte[1024]; - while ((len = ips.read(bytes)) != -1) { - i = i + len; - printStream.write(bytes, 0, len); - } - Utils.log("====图片传输大小::" + i); - } catch (IOException e) { - Utils.log("====开始加载异常::" + e.toString()); - e.printStackTrace(); - } finally { - if (ips != null) { - try { - ips.close(); - ips = null; - } catch (IOException e) { - e.printStackTrace(); - } - } - } - try { - Thread.sleep(500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - printStream.flush(); - printStream.close(); - Utils.log("====开始加载完成"); - } - - @Override - public void destroy() { - mActivity = null; - } -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/IpPortInfo.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/IpPortInfo.java deleted file mode 100644 index 680bfb72b1..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/IpPortInfo.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import java.io.Serializable; -import java.net.InetAddress; - -/** - * Ip Port 实体 - */ -public class IpPortInfo implements Serializable { - - private InetAddress inetAddress; - private int port; - private String senderName; - private int senderIcon; - private String receiverName; - - public IpPortInfo(InetAddress inetAddress, int port, String senderName, String receiverName, int senderIcon) { - this.inetAddress = inetAddress; - this.port = port; - this.senderName = senderName; - this.receiverName = receiverName; - this.senderIcon = senderIcon; - } - - public InetAddress getInetAddress() { - return inetAddress; - } - - public void setInetAddress(InetAddress inetAddress) { - this.inetAddress = inetAddress; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getSenderName() { - return senderName; - } - - public void setSenderName(String senderName) { - this.senderName = senderName; - } - - public int getSenderIcon() { - return senderIcon; - } - - public void setSenderIcon(int senderIcon) { - this.senderIcon = senderIcon; - } - - public String getReceiverName() { - return receiverName; - } - - public void setReceiverName(String receiverName) { - this.receiverName = receiverName; - } -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/KcUriHandler.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/KcUriHandler.java deleted file mode 100644 index d2eb8ec83a..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/KcUriHandler.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import com.gh.gamecenter.entity.KcWebRequestEntity; - -/** - * Created by khy on 2017/2/6. - */ -public interface KcUriHandler { - - /** - * 匹配Uri 判断返回请求结果 - * - * @param uri - * @return - */ - boolean matches(String uri); - - /** - * 请求链接和Socket对象 - * - * @param request - */ - void handler(KcWebRequestEntity request); - - /** - * 销毁 - */ - void destroy(); -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/KuaichuanNotification.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/KuaichuanNotification.java deleted file mode 100644 index d9e6de5e69..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/KuaichuanNotification.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import androidx.core.app.NotificationCompat; - -import com.gh.common.util.EntranceUtils; -import com.gh.download.DownloadNotification; -import com.gh.gamecenter.R; - -/** - * Created by LGT on 2016/10/10. - */ -public class KuaichuanNotification { - - public static final int NOTIFY_ID = 0x321; - - // 快传传输完成消息 - public static void showKuaiChuanDoneNotification(Context context, String apkPath, String apkName, String packName) { - NotificationManager manager = getNotificationManager(context); - Intent intent = new Intent(); - intent.putExtra(EntranceUtils.KEY_PATH, apkPath); - intent.setAction(DownloadNotification.ACTION_INSTALL); - PendingIntent pendingIntent = PendingIntent.getBroadcast(context, NOTIFY_ID, - intent, PendingIntent.FLAG_UPDATE_CURRENT); - String title = "接收完成,点击立即安装"; - String text = apkName; - - Notification notification = new NotificationCompat.Builder(context) - .setSmallIcon(R.mipmap.logo) - .setTicker(title) - .setContentTitle(text) - .setContentText(title) - .setContentIntent(pendingIntent).build(); - notification.flags |= Notification.FLAG_AUTO_CANCEL; // // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。 - manager.notify(packName, NOTIFY_ID, notification); - } - - private static NotificationManager getNotificationManager(Context context) { - return (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); - } - -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/Transferable.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/Transferable.java deleted file mode 100644 index 0e5cc1c96b..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/Transferable.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -/** - * Created by khy on 2017/1/20. - */ -public interface Transferable { - - /** - * @throws Exception - */ - void init() throws Exception; - - - /** - * @throws Exception - */ - void parseHeader() throws Exception; - - - /** - * @throws Exception - */ - void parseBody() throws Exception; - - - /** - * @throws Exception - */ - void finish() throws Exception; -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/WifiMgr.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/WifiMgr.java deleted file mode 100644 index 42de8efb73..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/WifiMgr.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.content.Context; -import android.net.DhcpInfo; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiInfo; - -import java.util.List; - -public class WifiMgr { - - /** - * 创建WifiConfiguration的类型 - */ - public static final int WIFICIPHER_NOPASS = 1; - public static final int WIFICIPHER_WEP = 2; - public static final int WIFICIPHER_WPA = 3; - - - private static WifiMgr mWifiMgr; - //scan the result - List mScanResultList; - List mWifiConfigurations; - //current wifi configuration info - WifiInfo mWifiInfo; - private Context mContext; - private android.net.wifi.WifiManager mWifiManager; - - private WifiMgr(Context context) { - this.mContext = context.getApplicationContext(); - this.mWifiManager = (android.net.wifi.WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); - } - - public static WifiMgr getInstance(Context context) { - if (mWifiMgr == null) { - synchronized (WifiMgr.class) { - if (mWifiMgr == null) { - mWifiMgr = new WifiMgr(context); - } - } - } - - return mWifiMgr; - } - - /** - * 创建WifiConfiguration - * - * @param ssid - * @param password - * @param type - * @return - */ - public static WifiConfiguration createWifiCfg(String ssid, String password, int type) { - WifiConfiguration config = new WifiConfiguration(); - config.allowedAuthAlgorithms.clear(); - config.allowedGroupCiphers.clear(); - config.allowedKeyManagement.clear(); - config.allowedPairwiseCiphers.clear(); - config.allowedProtocols.clear(); - - config.SSID = "\"" + ssid + "\""; - - switch (type) { - case WIFICIPHER_NOPASS: - // config.wepKeys[0] = ""; - config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); -// config.wepTxKeyIndex = 0; - -// 无密码连接WIFI时,连接不上wifi,需要注释两行代码 -// config.wepKeys[0] = ""; -// config.wepTxKeyIndex = 0; - break; - case WIFICIPHER_WEP: - config.hiddenSSID = true; - config.wepKeys[0] = "\"" + password + "\""; - config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); - config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); - config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); - config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); - config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); - config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); - config.wepTxKeyIndex = 0; - break; - case WIFICIPHER_WPA: - config.preSharedKey = "\"" + password + "\""; - config.hiddenSSID = true; - config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); - config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); - config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); - config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); - config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); - config.status = WifiConfiguration.Status.ENABLED; - break; - } - - return config; - } - - /** - * 打开wifi - */ - public void openWifi() { - if (!mWifiManager.isWifiEnabled()) { - mWifiManager.setWifiEnabled(true); - } - } - - /** - * 关闭wifi - */ - public void closeWifi() { - if (mWifiManager.isWifiEnabled()) { - mWifiManager.setWifiEnabled(false); - } - } - - /** - * 判断wifi是否开启的状态 - * - * @return - */ - public boolean isWifiEnable() { - return mWifiManager == null ? false : mWifiManager.isWifiEnabled(); - } - - /** - * wifi扫描 - */ - public void startScan() { - mWifiManager.startScan(); - mScanResultList = mWifiManager.getScanResults(); - mWifiConfigurations = mWifiManager.getConfiguredNetworks(); - } - - public List getScanResultList() { - return mScanResultList; - } - - public List getWifiConfigurations() { - return mWifiConfigurations; - } - - /** - * 添加到指定Wifi网络 /切换到指定Wifi网络 - * - * @param wf - * @return - */ - public boolean addNetwork(WifiConfiguration wf) { - //断开当前的连接 - disconnectCurrentNetwork(); - - //连接新的连接 - int netId = mWifiManager.addNetwork(wf); - boolean enable = mWifiManager.enableNetwork(netId, true); - return enable; - } - - /** - * 关闭当前的Wifi网络 - * - * @return - */ - public boolean disconnectCurrentNetwork() { - if (mWifiManager != null && mWifiManager.isWifiEnabled()) { - int netId = mWifiManager.getConnectionInfo().getNetworkId(); - mWifiManager.disableNetwork(netId); - return mWifiManager.disconnect(); - } - return false; - } - - /** - * 获取当前WifiInfo - * - * @return - */ - public WifiInfo getWifiInfo() { - mWifiInfo = mWifiManager.getConnectionInfo(); - return mWifiInfo; - } - - /** - * 获取当前Wifi所分配的Ip地址 - * - * @return - */ -// when connect the hotspot, is still returning "0.0.0.0". - public String getCurrentIpAddress() { - String ipAddress; - int address = mWifiManager.getDhcpInfo().ipAddress; - ipAddress = ((address & 0xFF) - + "." + ((address >> 8) & 0xFF) - + "." + ((address >> 16) & 0xFF) - + "." + ((address >> 24) & 0xFF)); - return ipAddress; - } - - - /** - * 设备连接Wifi之后, 设备获取Wifi热点的IP地址 - * - * @return - */ - public String getIpAddressFromHotspot() { - // WifiAP ip address is hardcoded in Android. - /* IP/netmask: logo.168.43.1/255.255.255.0 */ - String ipAddress; - DhcpInfo dhcpInfo = mWifiManager.getDhcpInfo(); - int address = dhcpInfo.gateway; - ipAddress = ((address & 0xFF) - + "." + ((address >> 8) & 0xFF) - + "." + ((address >> 16) & 0xFF) - + "." + ((address >> 24) & 0xFF)); - return ipAddress; - } - - - /** - * 开启热点之后,获取自身热点的IP地址 - * - * @return - */ - public String getHotspotLocalIpAddress() { - // WifiAP ip address is hardcoded in Android. - /* IP/netmask: 192.168.43.1/255.255.255.0 */ - String ipAddress; - DhcpInfo dhcpInfo = mWifiManager.getDhcpInfo(); - int address = dhcpInfo.serverAddress; - ipAddress = ((address & 0xFF) - + "." + ((address >> 8) & 0xFF) - + "." + ((address >> 16) & 0xFF) - + "." + ((address >> 24) & 0xFF)); - return ipAddress; - } - - - /** - * 关闭Wifi - */ - public void disableWifi() { - if (mWifiManager != null) { - mWifiManager.setWifiEnabled(false); - } - } - -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/WifiUtils.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/WifiUtils.java deleted file mode 100644 index c8b652b789..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/WifiUtils.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.gh.gamecenter.kuaichuan; - -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.PixelFormat; -import android.graphics.drawable.Drawable; -import android.net.wifi.ScanResult; -import android.text.TextUtils; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Created by khy on 2017/1/17. - */ -public class WifiUtils { - - public static final String NO_PASSWORD = "[ESS]"; - public static final String NO_PASSWORD_WPS = "[WPS][ESS]"; - - /** - * 过滤有密码的Wifi扫描结果集合 和WIFI名称为空 不包含ghZS - * - * @param scanResultList - * @return - */ - public static List filterWithNoPassword(List scanResultList) { - if (scanResultList == null || scanResultList.size() == 0) { - return scanResultList; - } - - List resultList = new ArrayList<>(); - for (ScanResult scanResult : scanResultList) { - if (!TextUtils.isEmpty(scanResult.SSID) && scanResult.capabilities != null && - scanResult.capabilities.equals(NO_PASSWORD) || scanResult.capabilities != null && - scanResult.capabilities.equals(NO_PASSWORD_WPS)) { - if (scanResult.SSID.contains("ghZS")) { - resultList.add(scanResult); - } - } - } - - return resultList; - } - - /** - * 判断指定的ipAddress是否可以ping - * - * @param ipAddress - * @return - */ - public static boolean pingIpAddress(String ipAddress) { - try { - Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 100 " + ipAddress); - int status = process.waitFor(); - if (status == 0) { - return true; - } else { - return false; - } - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 获取Apk文件的Log图标 - * - * @param context - * @param apk_path - * @return - */ - public static Drawable getApkThumbnail(Context context, String apk_path) { - if (context == null) { - return null; - } - - PackageManager pm = context.getApplicationContext().getPackageManager(); - PackageInfo packageInfo = pm.getPackageArchiveInfo(apk_path, PackageManager.GET_ACTIVITIES); - ApplicationInfo appInfo = packageInfo.applicationInfo; - /**获取apk的图标 */ - appInfo.sourceDir = apk_path; - appInfo.publicSourceDir = apk_path; - if (appInfo != null) { - Drawable apk_icon = appInfo.loadIcon(pm); - return apk_icon; - } - - return null; - } - - /** - * Drawable转Bitmap - * - * @param drawable - * @return - */ - public static Bitmap drawableToBitmap(Drawable drawable) { - if (drawable == null) { - return null; - } - - // 取 drawable 的长宽 - int w = drawable.getIntrinsicWidth(); - int h = drawable.getIntrinsicHeight(); - // 取 drawable 的颜色格式 - Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 - : Bitmap.Config.RGB_565; - //建立对应的Bitmap - Bitmap bitmap = Bitmap.createBitmap(w, h, config); - // 建立对应 bitmap 的画布 - Canvas canvas = new Canvas(bitmap); - drawable.setBounds(0, 0, w, h); - // 把 drawable 内容画到画布中 - drawable.draw(canvas); - - return bitmap; - } - -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/ChooseReceiverActivity.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/view/ChooseReceiverActivity.java deleted file mode 100644 index 86c30d2438..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/ChooseReceiverActivity.java +++ /dev/null @@ -1,653 +0,0 @@ -package com.gh.gamecenter.kuaichuan.view; - -import android.Manifest; -import android.animation.Animator; -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.wifi.ScanResult; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.preference.PreferenceManager; -import android.text.Html; -import android.view.MenuItem; -import android.view.View; -import android.view.animation.AccelerateInterpolator; -import android.view.animation.AlphaAnimation; -import android.view.animation.Animation; -import android.view.animation.ScaleAnimation; -import android.view.animation.TranslateAnimation; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import com.facebook.drawee.view.SimpleDraweeView; -import com.gh.base.BaseActivity; -import com.gh.common.util.DialogUtils; -import com.gh.common.util.DisplayUtils; -import com.gh.common.util.UserIconUtils; -import com.gh.common.view.RadarView; -import com.gh.gamecenter.R; -import com.gh.gamecenter.ShareGhActivity; -import com.gh.gamecenter.kuaichuan.BaseTransfer; -import com.gh.gamecenter.kuaichuan.Constant; -import com.gh.gamecenter.kuaichuan.FileInfo; -import com.gh.gamecenter.kuaichuan.HotspotManager; -import com.gh.gamecenter.kuaichuan.WifiMgr; -import com.gh.gamecenter.kuaichuan.WifiUtils; -import com.halo.assistant.HaloApp; -import com.lightgame.utils.Utils; - -import org.json.JSONObject; - -import java.lang.ref.WeakReference; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import androidx.annotation.NonNull; -import butterknife.BindView; -import butterknife.OnClick; -import pub.devrel.easypermissions.EasyPermissions; - -import static com.gh.gamecenter.kuaichuan.view.KcSelectGameActivity.SEND_OVER_REQUEST; - -/** - * Created by khy on 2017/1/20. - */ -public class ChooseReceiverActivity extends BaseActivity implements View.OnClickListener { - - @BindView(R.id.choosereceiver_user1_name) - TextView choosereceiver_user1_name; - @BindView(R.id.choosereceiver_user2_name) - TextView choosereceiver_user2_name; - @BindView(R.id.choosereceiver_user3_name) - TextView choosereceiver_user3_name; - @BindView(R.id.choosereceiver_user4_name) - TextView choosereceiver_user4_name; - @BindView(R.id.choosereceiver_user1) - LinearLayout choosereceiver_user1; - @BindView(R.id.choosereceiver_user2) - LinearLayout choosereceiver_user2; - @BindView(R.id.choosereceiver_user3) - LinearLayout choosereceiver_user3; - @BindView(R.id.choosereceiver_user4) - LinearLayout choosereceiver_user4; - @BindView(R.id.choosereceiver_user1_icon) - SimpleDraweeView userIcon1; - @BindView(R.id.choosereceiver_user2_icon) - SimpleDraweeView userIcon2; - @BindView(R.id.choosereceiver_user3_icon) - SimpleDraweeView userIcon3; - @BindView(R.id.choosereceiver_user4_icon) - SimpleDraweeView userIcon4; - @BindView(R.id.choosereceiver_radar) - RadarView mRadarView; - @BindView(R.id.scan_user) - TextView mScanUser; - @BindView(R.id.scan_user_des) - TextView mScanUserDes; - @BindView(R.id.scan_hint) - TextView mScanHint; - @BindView(R.id.choosereceiver_roket_anim) - RelativeLayout mRoketAnimRl; - @BindView(R.id.choosereceiver_ready_rl) - RelativeLayout mRoketRl; - @BindView(R.id.choosereceiver_roket_anim_bottom) - LinearLayout mRoketAnimBottom; - @BindView(R.id.choosereceiver_roket_anim_top) - ImageView mRoketTop; - @BindView(R.id.choosereceiver_roket_left) - ImageView mRoketAnimLeft; - @BindView(R.id.choosereceiver_roket_right) - ImageView mRoketAnimRight; - - View mToolbarContainer; - - private static final String KET_SHOWCONNHINTDIALOG = "showConnHintDialog"; - - private List mScanResultList; - - private DatagramSocket mDatagramSocket; - - private boolean isStopScan; - - private boolean isDestroy; - - private int conUserIconTag; - - private SharedPreferences sp; - - private ScaleAnimation mScaleAnimation; // 火箭喷火动画 - - private TranslateAnimation mTranslateAnimation; // 整个火箭移动页面 - - private Handler handler = new MyHandler(this); - - private String[] mPermissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}; - - @NonNull - public static Intent getIntent(Context context, boolean showConnHintDialog) { - Intent intent = new Intent(context, ChooseReceiverActivity.class); - intent.putExtra(KET_SHOWCONNHINTDIALOG, showConnHintDialog); - return intent; - } - - @Override - protected int getLayoutId() { - return R.layout.activity_receive_choose; - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setNavigationTitle(R.string.title_choose_activity); - setToolbarMenu(R.menu.menu_receive); - - mToolbarContainer = findViewById(R.id.normal_toolbar_container); - - sp = PreferenceManager.getDefaultSharedPreferences(this); - - // 检查权限 - EasyPermissions.requestPermissions(this, "传输文件需要定位权限", 0x9527, mPermissions); - } - - @Override - public void onPermissionsGranted(int requestCode, List perms) { - super.onPermissionsGranted(requestCode, perms); - - conUserIconTag = 1; - mRadarView.setSearching(true); - - mScanHint.setText(Html.fromHtml(getString(R.string.kc_scan_hint))); - - isStopScan = false; - isDestroy = false; - - if (HotspotManager.isApOn(getApplicationContext())) { - HotspotManager.disableAp(getApplicationContext()); - } - - if (!WifiMgr.getInstance(this).isWifiEnable()) { //wifi未打开的情况 - WifiMgr.getInstance(this).openWifi(); - } - - updateWifiScanResult(); - handler.sendEmptyMessageDelayed(0, 2000); - - boolean showConnHintDialog = sp.getBoolean(KET_SHOWCONNHINTDIALOG, true); - if (showConnHintDialog || (getIntent() != null && getIntent().getExtras() != null - && getIntent().getExtras().getBoolean(KET_SHOWCONNHINTDIALOG))) { - if (showConnHintDialog) { - sp.edit().putBoolean(KET_SHOWCONNHINTDIALOG, false).apply(); - } - showConnHintDialog(); - } - } - - @Override - public void onPermissionsDenied(int requestCode, List perms) { - super.onPermissionsDenied(requestCode, perms); - toast("请授予定位权限"); - finish(); - } - - @Override - public int provideNavigationIcon() { - return R.drawable.ic_filereceive_back; - } - - @Override - public boolean onMenuItemClick(MenuItem item) { - if (item.getItemId() == R.id.menu_receive_hint) showConnHintDialog(); - return super.onMenuItemClick(item); - } - - private void showConnHintDialog() { - DialogUtils.showHintDialog(ChooseReceiverActivity.this, "请告诉你的好友这样操作:", "1.打开光环助手,点击左上角“↓” " + - "\n2.点击右上方的“免流量传送” \n3.点击“我要接收”", "确定"); - } - - private void updateWifiScanResult() { - - if (mScanResultList != null && mScanResultList.size() > 0) { - mScanUser.setText("点击头像开始发送"); - mScanUserDes.setVisibility(View.GONE); - } else { - mScanUserDes.setVisibility(View.VISIBLE); - mScanUser.setText("正在寻找周围的小伙伴..."); - } - - if (mScanResultList != null) { - mScanResultList.clear(); - } - - choosereceiver_user1.setVisibility(View.GONE); - choosereceiver_user2.setVisibility(View.GONE); - choosereceiver_user3.setVisibility(View.GONE); - choosereceiver_user4.setVisibility(View.GONE); - choosereceiver_user1.setEnabled(true); - choosereceiver_user2.setEnabled(true); - choosereceiver_user3.setEnabled(true); - choosereceiver_user4.setEnabled(true); - - WifiMgr.getInstance(this).startScan(); - mScanResultList = WifiMgr.getInstance(this).getScanResultList(); - Utils.log("======WifiCount::" + mScanResultList.size()); - mScanResultList = WifiUtils.filterWithNoPassword(mScanResultList); - if (mScanResultList != null) { - for (int i = 0; i < mScanResultList.size(); i++) { - ScanResult scanResult = mScanResultList.get(i); - Utils.log(i + "=====" + scanResult.SSID); - - int icon = 1; - try { - icon = Integer.parseInt(scanResult.SSID.substring(scanResult.SSID.length() - 1)); - } catch (Exception e) { - e.printStackTrace(); - } - - switch (i) { - case 0: - choosereceiver_user1.setVisibility(View.VISIBLE); - choosereceiver_user1_name.setText(scanResult.SSID); - choosereceiver_user1.setOnClickListener(this); - userIcon1.setImageURI(UserIconUtils.getUserIcon(icon)); - break; - case 1: - choosereceiver_user2.setVisibility(View.VISIBLE); - choosereceiver_user2_name.setText(scanResult.SSID); - choosereceiver_user2.setOnClickListener(this); - userIcon2.setImageURI(UserIconUtils.getUserIcon(icon)); - break; - case 2: - choosereceiver_user3.setVisibility(View.VISIBLE); - choosereceiver_user3_name.setText(scanResult.SSID); - choosereceiver_user3.setOnClickListener(this); - userIcon3.setImageURI(UserIconUtils.getUserIcon(icon)); - break; - case 3: - choosereceiver_user4.setVisibility(View.VISIBLE); - choosereceiver_user4_name.setText(scanResult.SSID); - choosereceiver_user4.setOnClickListener(this); - userIcon4.setImageURI(UserIconUtils.getUserIcon(icon)); - break; - } - } - - } - - } - - @Override - protected void onDestroy() { - mRadarView.setSearching(false); - isDestroy = true; - isStopScan = true; - handler.removeCallbacksAndMessages(null); - super.onDestroy(); - } - - @Override - public void onClick(View v) { - if (v == choosereceiver_user1) { - connReceiverWifi(0); - } else if (v == choosereceiver_user2) { - connReceiverWifi(1); - } else if (v == choosereceiver_user3) { - connReceiverWifi(2); - } else if (v == choosereceiver_user4) { - connReceiverWifi(3); - } - } - - @OnClick(R.id.scan_hint) - public void onScanHintListener() { -// DialogUtils.showHintDialog(this, "请告诉你的好友这样操作:", "1.拿出手机,打开光环助手 " + -// "\n2.点击首页左上角,进入下载管理 \n3.点击“零流量传送”,再点击“我要接收”", -// "确定"); - - // 是否需要关闭扫描?? - - startActivity(ShareGhActivity.getIntent(this)); - } //1.连接网络 - - private void connReceiverWifi(int connPosition) { - - if (isStopScan) { - return; - } - - // 进入动画页面 - readyAnimView(); - - handler.sendEmptyMessageDelayed(2, 30000); - - Utils.log("======开始连接热点"); - mScanUser.setText("开始连接对方设备..."); - isStopScan = true; -// choosereceiver_user1.setEnabled(false); -// choosereceiver_user2.setEnabled(false); -// choosereceiver_user3.setEnabled(false); -// choosereceiver_user4.setEnabled(false); - -// handler.postAtTime(new Runnable() { // 5s后还收不到接收者的回馈消息 重新回到扫描页面 -// @Override -// public void run() { -// Utils.log("==========aa" + isConnSuccess); -// if (!isConnSuccess) { -// isStopScan = false; -// updateWifiScanResult(); -// } -// } -// }, 5000); - - String ssid = mScanResultList.get(connPosition).SSID; - WifiMgr.getInstance(this).openWifi(); - WifiMgr.getInstance(this).addNetwork(WifiMgr.createWifiCfg(ssid, null, WifiMgr.WIFICIPHER_NOPASS)); - - try { - conUserIconTag = Integer.parseInt(ssid.substring(ssid.length() - 1)); - } catch (Exception e) { - e.printStackTrace(); - } - - createSendMsgToServerRunnable(WifiMgr.getInstance(this).getIpAddressFromHotspot()); - } - - @Override - public boolean onHandleBackPressed() { - closeSocket(); - HaloApp.remove(KcSelectGameActivity.KEY_FILE_INFO); - return false; - } - - //发送UDP通知信息到 文件接收方 开启ServerSocketRunnable - private void createSendMsgToServerRunnable(final String ipAddress) { - HaloApp.getInstance().getMainExecutor().execute(new Runnable() { - @Override - public void run() { - try { - startFileSenderServer(ipAddress); - } catch (Exception e) { - isStopScan = false; - handler.sendEmptyMessage(0); - Utils.log("UDP通信异常--startFileSenderServer" + e.toString()); - e.printStackTrace(); - } - } - }); - } - - static class MyHandler extends Handler { - - private WeakReference mActivityWeakReference; - - MyHandler(Activity activity) { - mActivityWeakReference = new WeakReference<>(activity); - } - - @Override - public void handleMessage(Message msg) { - super.handleMessage(msg); - - ChooseReceiverActivity activity = (ChooseReceiverActivity) mActivityWeakReference.get(); - if (activity != null) { - if (msg.what == 0 && !activity.isStopScan) { - activity.updateWifiScanResult(); - sendEmptyMessageDelayed(0, 2000); - } else if (msg.what == 2) { - activity.isStopScan = false; - sendEmptyMessage(0); - activity.connFailedAnimView(); - } - } - } - } - - private void startFileSenderServer(String ipAddress) throws Exception { - int serverPort = Constant.DEFAULT_SERVER_COM_PORT; - - // 确保Wifi连接上之后获取得到IP地址 - int count = 0; - while (ipAddress.equals(Constant.DEFAULT_UNKOWN_IP) && count < Constant.DEFAULT_TRY_TIME) { - Thread.sleep(1000); - ipAddress = WifiMgr.getInstance(ChooseReceiverActivity.this).getIpAddressFromHotspot(); - count++; - } - - // 即使获取到连接的热点wifi的IP地址也是无法连接网络 所以采取此策略 - count = 0; - while (!WifiUtils.pingIpAddress(ipAddress) && count < Constant.DEFAULT_TRY_TIME) { - Thread.sleep(500); - count++; - } - - if (mDatagramSocket == null) { - mDatagramSocket = new DatagramSocket(null); - mDatagramSocket.setReuseAddress(true); - mDatagramSocket.bind(new InetSocketAddress(serverPort)); - } -// mDatagramSocket = new DatagramSocket(serverPort); - byte[] receiveData = new byte[1024]; - byte[] sendData; - Utils.log("=====ip::" + ipAddress); - if (!"logo.168.43.1".equals(ipAddress)) { - // 连接失败,可能是连接的热点已经关闭, 关闭动画,开启扫描 - isStopScan = false; - handler.sendEmptyMessage(0); - handler.post(new Runnable() { - @Override - public void run() { - connFailedAnimView(); - } - }); - } - InetAddress ipAddressName = InetAddress.getByName(ipAddress); // 转译 - - //发送 即将发送的文件列表 到文件接收方 - sendFileInfoListToFileReceiverWithUdp(serverPort, ipAddressName); - - //发送 文件接收方 初始化 - - JSONObject senderData = new JSONObject(); - senderData.put(Constant.MSG_FILE_RECEIVER_INIT, sp.getString("user_name", "光环用户")); - senderData.put("UserIcon", sp.getInt("default_user_icon", 1)); - - sendData = senderData.toString().getBytes(BaseTransfer.UTF_8); - DatagramPacket sendPacket = - new DatagramPacket(sendData, sendData.length, ipAddressName, serverPort); - mDatagramSocket.send(sendPacket); - - while (!isDestroy) { - DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); - mDatagramSocket.receive(receivePacket); - String response = new String(receivePacket.getData(), 0, receivePacket.getLength()).trim(); - Utils.log("ChooseReceiverActivity:: 接收UDP请求" + response); - - if (response.contains(Constant.MSG_FILE_RECEIVER_INIT_SUCCESS)) { - JSONObject jsonObject = new JSONObject(response); - Utils.log("ChooseReceiverActivity:: 收到UDP请求::SUCCESS=" + jsonObject.getString(Constant.MSG_FILE_RECEIVER_INIT_SUCCESS)); - - Map userMap = new HashMap<>(); - userMap.put("receiverName", jsonObject.getString(Constant.MSG_FILE_RECEIVER_INIT_SUCCESS)); - userMap.put("usericon", String.valueOf(conUserIconTag)); - - HaloApp.put("userMap", userMap); - - handler.post(new Runnable() { - @Override - public void run() { - mRadarView.setSearching(false); - connSuccessAnimView(); - } - }); - break; - } - } - - } - - private void sendFileInfoListToFileReceiverWithUdp(int serverPort, InetAddress ipAddress) { - List fileInfoList = (List) HaloApp.get(KcSelectGameActivity.KEY_FILE_INFO, false); - if (fileInfoList == null) { - return; - } - for (FileInfo fileInfo : fileInfoList) { - String fileInfoJson = FileInfo.toJsonStr(fileInfo); - Utils.log("ChooseReceiverActivity:: 发送的文件列表::" + fileInfoJson); - DatagramPacket sendFileInfoListPacket = - new DatagramPacket(fileInfoJson.getBytes(), fileInfoJson.getBytes().length, ipAddress, serverPort); - try { - mDatagramSocket.send(sendFileInfoListPacket); - Utils.log("ChooseReceiverActivity:: UDP通知 Success::" + ipAddress + "==" + serverPort); - } catch (Exception e) { - Utils.log("ChooseReceiverActivity:: UDP通知 Failure!"); - } - } - } - - // 连接中-动画 - private void readyAnimView() { - mToolbarContainer.setVisibility(View.GONE); - mRoketRl.setVisibility(View.VISIBLE); - mRoketRl.animate() - .alpha(1f) - .setDuration(1000) - .setListener(null); - - mScaleAnimation = new ScaleAnimation(0.5f, 0.8f, 0.5f, 0.8f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); - mScaleAnimation.setDuration(250); - mScaleAnimation.setRepeatCount(Animation.INFINITE); - mScaleAnimation.setRepeatMode(Animation.REVERSE); - - mRoketAnimLeft.startAnimation(mScaleAnimation); - mRoketAnimRight.startAnimation(mScaleAnimation); - } - - // 连接成功-动画 - private void connSuccessAnimView() { - handler.removeMessages(2); - - if (mScaleAnimation != null) { - mScaleAnimation.cancel(); - } - AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0.6f); - alphaAnimation.setDuration(250); - alphaAnimation.setRepeatCount(Animation.INFINITE); - alphaAnimation.setRepeatMode(Animation.REVERSE); - mRoketAnimLeft.startAnimation(alphaAnimation); - mRoketAnimRight.startAnimation(alphaAnimation); - - mScaleAnimation = new ScaleAnimation(0.5f, 0.8f, 0.5f, 0.8f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); - mScaleAnimation.setDuration(250); - mScaleAnimation.setRepeatCount(Animation.INFINITE); - mScaleAnimation.setRepeatMode(Animation.REVERSE); - - mRoketAnimLeft.setImageResource(R.drawable.kuaichuan_rocket_fire); - mRoketAnimRight.setImageResource(R.drawable.kuaichuan_rocket_fire); - - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mRoketAnimRight.getLayoutParams(); - layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.width = DisplayUtils.dip2px(this, 25); - - mRoketAnimRight.setLayoutParams(layoutParams); - LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) mRoketAnimLeft.getLayoutParams(); - layoutParams2.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams2.width = DisplayUtils.dip2px(this, 25); - - layoutParams2.setMargins(0, 0, DisplayUtils.dip2px(ChooseReceiverActivity.this, 14), 0); - mRoketAnimLeft.setLayoutParams(layoutParams2); - - - if (mScaleAnimation == null) { - mScaleAnimation.cancel(); - } - - mTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1000); - mTranslateAnimation.setDuration(1000); - mTranslateAnimation.setInterpolator(new AccelerateInterpolator(2.0f)); -// mTranslateAnimation.setFillAfter(true); - - mRoketAnimRl.startAnimation(mTranslateAnimation); - - mTranslateAnimation.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - - } - - @Override - public void onAnimationEnd(Animation animation) { - mRoketAnimRl.setVisibility(View.GONE); - startActivity(FileSenderActivity.getIntent(ChooseReceiverActivity.this)); - closeSocket(); - Intent resultIntent = new Intent(); - resultIntent.putExtra("isFinish", true); - setResult(SEND_OVER_REQUEST, resultIntent); - finish(); - } - - @Override - public void onAnimationRepeat(Animation animation) { - - } - }); - } - - // 连接失败-动画 - private void connFailedAnimView() { - mToolbarContainer.setVisibility(View.VISIBLE); - toast("连接失败"); - if (mScaleAnimation != null) { - mScaleAnimation.cancel(); - } - mRoketRl.animate() - .alpha(0f) - .setDuration(1000) - .setListener(new Animator.AnimatorListener() { - @Override - public void onAnimationStart(Animator animation) { - - } - - @Override - public void onAnimationEnd(Animator animation) { - mRoketRl.setVisibility(View.GONE); - } - - @Override - public void onAnimationCancel(Animator animation) { - - } - - @Override - public void onAnimationRepeat(Animator animation) { - - } - - }); - } - - - /** - * 关闭UDP Socket 流 - */ - private void closeSocket() { - isStopScan = true; - if (mDatagramSocket != null) { -// mDatagramSocket.disconnect(); - mDatagramSocket.close(); - mDatagramSocket = null; - } - } - - -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileReceiverActivity.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileReceiverActivity.java deleted file mode 100644 index 1f318c545a..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileReceiverActivity.java +++ /dev/null @@ -1,652 +0,0 @@ -package com.gh.gamecenter.kuaichuan.view; - -import android.Manifest; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import android.os.Message; -import android.os.Parcelable; -import android.preference.PreferenceManager; -import android.text.TextUtils; -import android.view.View; -import android.widget.LinearLayout; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import com.facebook.drawee.view.SimpleDraweeView; -import com.gh.base.BaseActivity; -import com.gh.common.util.DialogUtils; -import com.gh.common.util.PackageUtils; -import com.gh.common.util.StringUtils; -import com.gh.common.util.UserIconUtils; -import com.gh.common.view.VerticalItemDecoration; -import com.gh.gamecenter.CleanApkActivity; -import com.gh.gamecenter.R; -import com.gh.gamecenter.adapter.FileReceiverAdapter; -import com.gh.gamecenter.adapter.FileReceiverAdapter.OnReceiverCancelListener; -import com.gh.gamecenter.eventbus.EBDownloadChanged; -import com.gh.gamecenter.eventbus.EBDownloadStatus; -import com.gh.gamecenter.eventbus.EBPackage; -import com.gh.gamecenter.kuaichuan.BaseTransfer; -import com.gh.gamecenter.kuaichuan.Constant; -import com.gh.gamecenter.kuaichuan.FileInfo; -import com.gh.gamecenter.kuaichuan.FileReceiver; -import com.gh.gamecenter.kuaichuan.HotspotManager; -import com.gh.gamecenter.kuaichuan.IpPortInfo; -import com.gh.gamecenter.kuaichuan.KuaichuanNotification; -import com.gh.gamecenter.kuaichuan.WifiMgr; -import com.gh.gamecenter.manager.DataCollectionManager; -import com.halo.assistant.HaloApp; -import com.lightgame.download.DownloadDao; -import com.lightgame.download.DownloadEntity; -import com.lightgame.download.DownloadStatus; -import com.lightgame.utils.Utils; - -import org.greenrobot.eventbus.EventBus; -import org.greenrobot.eventbus.Subscribe; -import org.greenrobot.eventbus.ThreadMode; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.ServerSocket; -import java.net.Socket; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.OnClick; - -/** - * Created by khy on 2017/1/20. - */ -public class FileReceiverActivity extends BaseActivity implements OnReceiverCancelListener { - - @BindView(R.id.sender_rv) - RecyclerView mReceiverRv; - @BindView(R.id.sender_user_icon) - SimpleDraweeView mSenderUserIcon; - @BindView(R.id.sender_user_name) - TextView mSenderUserName; - @BindView(R.id.sender_user_send_des) - TextView mSenderUserDes; - @BindView(R.id.sender_hint) - TextView mSenderHint; - @BindView(R.id.sender_bottom) - LinearLayout mReceiverBottom; - @BindView(R.id.sender_keep_send) - RelativeLayout mKeepReceiver; - @BindView(R.id.sender_keep_send_tv) - TextView mKeepReceiverTv; - @BindView(R.id.sender_bottom_hint) - TextView mReceiverBottomHint; - @BindView(R.id.sender_bottom_control) - LinearLayout mReceiverControl; - - private FileReceiverAdapter mFileReceiverAdapter; - - private FileInfo mCurFileInfo; - - private List mFileInfos; - - private List> sendData; // 传送成绩单数据 - - private IpPortInfo mIpPortInfo; - - private ServerRunnable mReceiverServer; - - private FileReceiver mFileReceiver; - - private DatagramSocket mDatagramSocket; - - private SharedPreferences sp; - - private boolean isReceivesOver; - private boolean isOpenWifi; //记录开热点前的WiFi状态 - Handler handler = new Handler() { - @Override - public void handleMessage(Message msg) { - super.handleMessage(msg); - if (mFileInfos == null) { - Utils.log("接收器出现异常"); - return; - } - - int index = getCurrentFileInfoIndex(); - if (index == -100) { - Utils.toast(FileReceiverActivity.this, "接收失败"); - closePage(); - return; - } - - if (index == -1) { -// Utils.toast(FileReceiverActivity.this, " 获取刷新位置异常"); - return; - } - FileInfo fileInfo = mFileInfos.get(index); - - switch (msg.what) { - case FileInfo.FLAG_DEFAULT:// 传输中更新界面 - long progress = (long) msg.obj; - fileInfo.setProgress(progress); - fileInfo.setResult(FileInfo.FLAG_DEFAULT); - break; - case FileInfo.FLAG_SUCCESS:// 传输成功更新界面 - fileInfo.setResult(FileInfo.FLAG_SUCCESS); - if (index == mFileInfos.size() - 1) initSenderHint(false); - break; - case FileInfo.FLAG_FAILURE: // 传输失败更新界面 - fileInfo.setResult(FileInfo.FLAG_FAILURE); - if (index == mFileInfos.size() - 1) initSenderHint(false); - break; - case FileInfo.FLAG_CANCEL: // 传输取消更新界面 - fileInfo.setResult(FileInfo.FLAG_CANCEL); - if (index == mFileInfos.size() - 1) initSenderHint(false); - break; - case FileInfo.FLAG_NO_MEMORY: - Utils.toast(FileReceiverActivity.this, "手机空间不足"); - fileInfo.setResult(FileInfo.FLAG_NO_MEMORY); // 接收方内存不足 - if (index == mFileInfos.size() - 1) initSenderHint(true); - break; - } - - Utils.log("FileReceiverActivity:: 刷新位置::" + index + "刷新状态::" + msg.what); - mFileReceiverAdapter.notifyItemChanged(index); - } - }; - private boolean isDestroy; - - private int getCurrentFileInfoIndex() { - for (int i = 0; i < mFileInfos.size(); i++) { - FileInfo fileInfo = mFileInfos.get(i); - if (mCurFileInfo == null) { - return -100; - } - if (fileInfo.getFileTag().equals(mCurFileInfo.getFileTag())) { - return i; - } - } - Utils.log("FileReceiverActivity:: 获取刷新位置异常" + mFileInfos.size()); - mFileInfos.add(mCurFileInfo); - - return mFileInfos.size() - 1; - } - - @Override - protected int getLayoutId() { - return R.layout.activity_receive_send; - } - - @Override - public void onBackPressed() { - backHint(); - } - - private void backHint() { - if (isReceivesOver) { - closePage(); - } else { - DialogUtils.showWarningDialog(FileReceiverActivity.this, "退出传送", "文件正在传送中,确定退出吗?" - , "点错了", "坚决退出" - , new DialogUtils.ConfirmListener() { - @Override - public void onConfirm() { - closePage(); - } - }, null); - } - } - - private void closePage() { - - if (mDatagramSocket != null) { -// mDatagramSocket.disconnect(); - mDatagramSocket.close(); - mDatagramSocket = null; - } - - //关闭热点 - HotspotManager.initUserAp(getApplicationContext()); - - if (isOpenWifi) { - WifiMgr.getInstance(this).openWifi(); - } - - for (FileInfo fileInfo : mFileInfos) { - if (fileInfo.getResult() == FileInfo.FLAG_SUCCESS) { - DownloadEntity entry = new DownloadEntity(); - entry.setName(fileInfo.getName()); - entry.setSize(fileInfo.getSize()); - entry.setPackageName(fileInfo.getPackageName()); - entry.setPath(Environment.getExternalStorageDirectory() + "/GH-KC/" + fileInfo.getName() + ".apk"); - entry.setPercent(100.0); - entry.setUrl(fileInfo.getFilePath()); //url拿 路径替代 - entry.setStatus(DownloadStatus.done); - JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("KuaiChuanIcon", Environment.getExternalStorageDirectory() + "/GH-KC/" + fileInfo.getName() + ".apk"); - } catch (JSONException e) { - e.printStackTrace(); - } - entry.setIcon(jsonObject.toString()); - DownloadDao.getInstance(this).newOrUpdate(entry); - } - } - List all = DownloadDao.getInstance(this).getAll(); - if (all.size() > 0) { - EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE, all.size())); - } - EventBus.getDefault().post(new EBDownloadStatus("download")); - - mReceiverServer.close(); -// HaloApp.remove(KcSelectGameActivity.KEY_FILE_INFO); - mFileInfos.clear(); - - HaloApp.put("sendData", sendData); - - finish(); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setNavigationTitle(R.string.title_file_receive); - - isDestroy = false; - -// mFileInfos = (List) HaloApp.get(KcSelectGameActivity.KEY_FILE_INFO, false); - - sendData = new ArrayList<>(); - - mIpPortInfo = (IpPortInfo) getIntent().getSerializableExtra(Constant.KEY_IP_PORT_INFO); - isOpenWifi = getIntent().getBooleanExtra("isOpenWifi", false); - ArrayList list = getIntent().getParcelableArrayListExtra(Constant.KEY_IP_FILE_INFO); - mFileInfos = (List) list.get(0); - - mFileReceiverAdapter = new FileReceiverAdapter(this, this, mFileInfos); - mReceiverRv.setLayoutManager(new LinearLayoutManager(this)); - mReceiverRv.addItemDecoration(new VerticalItemDecoration(this, 8, true)); - mReceiverRv.setAdapter(mFileReceiverAdapter); - - mKeepReceiverTv.setText("继续接收"); - - sp = PreferenceManager.getDefaultSharedPreferences(this); - - initUserData(); - - if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200); - } else { - initServer(); //启动接收服务 - } - - } - - private void initUserData() { - isReceivesOver = false; - - long allGameSize = 0; - for (FileInfo mFileInfo : mFileInfos) { - allGameSize = allGameSize + mFileInfo.getSize(); - } - - double size = (((float) allGameSize / 1024) / 1024); - DecimalFormat df = new DecimalFormat("#.00"); - String sizeName = df.format(size) + "MB"; - - mSenderUserDes.setText(mFileInfos.size() + "个游戏,共" + sizeName); - mSenderUserName.setText(StringUtils.buildString("来自 ", mIpPortInfo.getSenderName())); - mSenderUserIcon.setImageURI(UserIconUtils.getUserIcon(mIpPortInfo.getSenderIcon())); - - mReceiverBottom.setVisibility(View.GONE); - - mSenderHint.setText("已连接"); - } - - /** - * 开启文件接收端服务 - */ - private void initServer() { - mReceiverServer = new ServerRunnable(Constant.DEFAULT_SERVER_PORT); - HaloApp.getInstance().getMainExecutor().execute(mReceiverServer); - - HaloApp.getInstance().getMainExecutor().execute(new Runnable() { - @Override - public void run() { - try { - receiverData(); - } catch (Exception e) { - Utils.log("FileReceiverActivity:: UDP请求异常" + e.toString()); - e.printStackTrace(); - } - } - }); - } - - private void receiverData() throws Exception { - if (mDatagramSocket == null) { - mDatagramSocket = new DatagramSocket(Constant.DEFAULT_SERVER_SENDING_PORT); - mDatagramSocket.setBroadcast(true); - } - - byte[] receiveData = new byte[1024]; - - Utils.log("FileReceiverActivity:: 开始接收UDP请求::" + Constant.DEFAULT_SERVER_SENDING_PORT + "::" + mDatagramSocket.getInetAddress()); - while (!isDestroy) { - Utils.log("FileReceiverActivity:: 开始接收UDP请求"); - DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); - mDatagramSocket.receive(receivePacket); - String response = new String(receivePacket.getData(), 0, receivePacket.getLength()).trim(); - Utils.log("FileReceiverActivity:: 接收UDP请求" + response); - if (response != null && response.equals(Constant.MSG_ADD_DATA_OVER)) { - handler.post(new Runnable() { - @Override - public void run() { - mFileReceiverAdapter.update(); - initUserData(); - } - }); - - sendMessageToSender(Constant.MSG_ADD_DATA_OVER); - Utils.log("FileReceiverActivity:: 回复信息" + Constant.MSG_ADD_DATA_OVER); - } else if (response != null) { - parseFileInfo(response); - } - - } - - } - - private void sendMessageToSender(final String sendData) throws Exception { - HaloApp.getInstance().getMainExecutor().execute(new Runnable() { - @Override - public void run() { - try { - byte[] bytes = sendData.getBytes(BaseTransfer.UTF_8); - DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, mIpPortInfo.getInetAddress(), Constant.DEFAULT_SERVER_SENDING_PORT); - mDatagramSocket.send(sendPacket); - - Utils.log("接收方消息已发送至接收方:" + sendData + "==" + mIpPortInfo.getInetAddress() + "==" + Constant.DEFAULT_SERVER_SENDING_PORT); - } catch (Exception e) { - Utils.log("接收方发送消息异常。。" + e.toString()); - e.printStackTrace(); - } - } - }); - } - - /** - * 解析FileInfo - * - * @param msg - */ - private void parseFileInfo(String msg) { -// mFileInfos = (List) HaloApp.get(KcSelectGameActivity.KEY_FILE_INFO, false); // mFileInfos 数据异常 需要重新获取 - FileInfo fileInfo = FileInfo.toObject(msg); - if (fileInfo != null && fileInfo.getFilePath() != null) { - mFileInfos.add(fileInfo); - Utils.log("FileReceiverActivity 添加一条数据::" + msg); -// HaloApp.put(KcSelectGameActivity.KEY_FILE_INFO, mFileInfos); - - } - } - - @Override - protected void onDestroy() { - super.onDestroy(); - isDestroy = true; - handler.removeCallbacksAndMessages(null); - } - - @Override - public void OnCancelPosition(final int position) { -// if (position == getCurrentFileInfoIndex()) { -// mFileReceiver.cancel(); -// } else { -// Utils.toast(this, "在传送中的游戏才可以取消"); -// } - - - Utils.log("接收方发送取消消息 让发送方取消"); - - - try { - // 接收方更改界面 - FileInfo fileInfo = mFileInfos.get(position); - fileInfo.setResult(FileInfo.FLAG_CANCEL); - mFileReceiverAdapter.notifyItemChanged(position); - - // 发消息让发送方取消 - JSONObject jsonObject = new JSONObject(); - jsonObject.put("controlStatus", Constant.MSG_RECEIVER_CANCEL); - jsonObject.put("controlTag", position); - - sendMessageToSender(jsonObject.toString()); - } catch (Exception e) { - e.printStackTrace(); - } - - - } - - //安装事件 - @Subscribe(threadMode = ThreadMode.MAIN) - public void onEventMainThread(EBPackage busFour) { - if ("安装".equals(busFour.getType())) { - for (int i = 0; i < mFileInfos.size(); i++) { - FileInfo fileInfo = mFileInfos.get(i); - if (fileInfo.getResult() == FileInfo.FLAG_SUCCESS && - fileInfo.getPackageName().equals(busFour.getPackageName())) { - fileInfo.setResult(FileInfo.FLAG_INSTALLED); - mFileReceiverAdapter.notifyItemChanged(i); - } - } - - } - } - - private void initSenderHint(boolean isNoMemory) { - for (FileInfo mFileInfo : mFileInfos) { - if (mFileInfo.getResult() == 0 || mFileInfo.getResult() == 1) { // 还有没完成的任务 - return; - } - } - - mReceiverBottom.setVisibility(View.VISIBLE); - mReceiverControl.setVisibility(View.VISIBLE); - - - isReceivesOver = true; - int sendSuccess = 0; - for (FileInfo mFileInfo : mFileInfos) { - if (mFileInfo.getResult() == FileInfo.FLAG_SUCCESS) { - sendSuccess++; - } - } - - if (isNoMemory) { - mKeepReceiverTv.setText("手机空间清理"); - } - - if (sendSuccess > 0) { - mSenderHint.setVisibility(View.VISIBLE); - mSenderHint.setText("传输结束,成功接收" + sendSuccess + "个游戏"); - } else { - if (mFileInfos.get(mFileInfos.size() - 1).getResult() == FileInfo.FLAG_CANCEL) { - mSenderHint.setVisibility(View.VISIBLE); - mSenderHint.setText("传输已取消"); - } else if (mFileInfos.get(mFileInfos.size() - 1).getResult() == FileInfo.FLAG_FAILURE) { - mSenderHint.setVisibility(View.VISIBLE); - mSenderHint.setText("传输失败"); - } - } - - } - - @OnClick({R.id.sender_keep_send, R.id.sender_back}) - public void back(View view) { - switch (view.getId()) { - case R.id.sender_back: - backHint(); - break; - case R.id.sender_keep_send: - if ("继续接收".equals(mKeepReceiverTv.getText())) { -// mReceiverControl.setVisibility(View.GONE); - mKeepReceiverTv.setBackgroundResource(R.drawable.game_item_btn_pause_style); - Utils.toast(FileReceiverActivity.this, "无需操作,请让对方继续发送即可"); - } else { // 跳转安装包清理 - startActivity(CleanApkActivity.getIntent(this)); - } - break; - - } - } - - /** - * ServerSocket启动线程 - */ - class ServerRunnable implements Runnable { - ServerSocket serverSocket; - private int port; - - public ServerRunnable(int port) { - this.port = port; - } - - /** - * 关闭Socket 通信 - */ - public void close() { - if (serverSocket != null) { - try { - serverSocket.close(); - serverSocket = null; - } catch (IOException e) { - } - } - } - - @Override - public void run() { - Utils.log("接收线程:Socket已经开启"); - try { - serverSocket = new ServerSocket(Constant.DEFAULT_SERVER_PORT); - - while (!Thread.currentThread().isInterrupted()) { - Socket socket = serverSocket.accept(); - - mFileReceiver = new FileReceiver(socket, FileReceiverActivity.this); - mFileReceiver.setOnReceiveListener(new FileReceiver.OnReceiveListener() { - private long mStartTime; - private long mNormalStartTime; - - @Override - public void onStart() { - Utils.log("快传文件接收::onStart"); - mStartTime = Utils.getTime(FileReceiverActivity.this); - mNormalStartTime = System.currentTimeMillis(); - } - - @Override - public void onGetFileInfo(FileInfo fileInfo) { // 获取FileInfo - mCurFileInfo = fileInfo; - for (int i = 0; i < mFileInfos.size(); i++) { - FileInfo info = mFileInfos.get(i); - if (info.getName(). //NullPointerException - equals(mCurFileInfo.getName())) { - info.setBitmap(fileInfo.getBitmap()); - } - } - } - - @Override - public void onProgress(long progress, long total) { // 获取传输进度 -// Utils.log("快传文件接收中..." + progress + "==" + total); - Message message = new Message(); - message.what = FileInfo.FLAG_DEFAULT; - message.obj = progress; - handler.sendMessage(message); - } - - @Override - public void onSuccess() { // 获取传输成功 - handler.sendEmptyMessage(FileInfo.FLAG_SUCCESS); - - String ghVersion = (String) PackageUtils.getMetaData(FileReceiverActivity.this - , mCurFileInfo.getPackageName(), "gh_version"); - if (TextUtils.isEmpty(ghVersion)) { - ghVersion = ""; - } - - long sendTime = Utils.getTime(FileReceiverActivity.this) - mStartTime; - - Map hashMap = new HashMap<>(); - hashMap.put("send_time", mStartTime); - hashMap.put("receive_time", Utils.getTime(FileReceiverActivity.this)); - hashMap.put("game_name", mCurFileInfo.getName()); - hashMap.put("package_name", mCurFileInfo.getPackageName()); - hashMap.put("package_size", mCurFileInfo.getSize()); - hashMap.put("expend_time", sendTime); - hashMap.put("send_nickname", mIpPortInfo.getSenderName()); - hashMap.put("receive_nickname", mIpPortInfo.getReceiverName()); - hashMap.put("receive_token", sp.getString("token", null)); - hashMap.put("package_gh_version", ghVersion); - DataCollectionManager.onEvent(FileReceiverActivity.this, "transfer", hashMap, false); - - - Utils.log("快传文件接收成功::onSuccess:: 发送事件::" + sendTime); - - long sendNormalTime = System.currentTimeMillis() - mNormalStartTime; - Map map = new HashMap<>(); - map.put("sendTime", String.valueOf(sendNormalTime)); - map.put("apkPath", Environment.getExternalStorageDirectory() + "/GH-KC/" + mCurFileInfo.getName() + ".apk"); - map.put("apkSize", String.valueOf(mCurFileInfo.getSize())); - sendData.add(map); - - KuaichuanNotification.showKuaiChuanDoneNotification(FileReceiverActivity.this, - Environment.getExternalStorageDirectory() + "/GH-KC/" + mCurFileInfo.getName() + ".apk", - mCurFileInfo.getName(), mCurFileInfo.getPackageName()); - - } - - @Override - public void onFailure(Throwable t) { // 获取传输失败 - Utils.log("快传文件接收失败::onFailure"); - handler.sendEmptyMessage(FileInfo.FLAG_FAILURE); - } - - @Override - public void onCancel() { // 获取传输取消 - Utils.log("快传文件接收取消::onCancel"); - handler.sendEmptyMessage(FileInfo.FLAG_CANCEL); - } - - @Override - public void onNoMemory() { - handler.sendEmptyMessage(FileInfo.FLAG_NO_MEMORY); - } - }); - - HaloApp.getInstance().getMainExecutor().execute(mFileReceiver); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - - - } -} \ No newline at end of file diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileSenderActivity.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileSenderActivity.java deleted file mode 100644 index 2791f7429b..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileSenderActivity.java +++ /dev/null @@ -1,488 +0,0 @@ -package com.gh.gamecenter.kuaichuan.view; - -import android.Manifest; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.view.View; -import android.widget.LinearLayout; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import com.facebook.drawee.view.SimpleDraweeView; -import com.gh.base.BaseActivity; -import com.gh.common.util.DialogUtils; -import com.gh.common.util.UserIconUtils; -import com.gh.common.view.VerticalItemDecoration; -import com.gh.gamecenter.R; -import com.gh.gamecenter.adapter.FileSenderAdapter; -import com.gh.gamecenter.kuaichuan.Constant; -import com.gh.gamecenter.kuaichuan.FileInfo; -import com.gh.gamecenter.kuaichuan.FileSender; -import com.gh.gamecenter.kuaichuan.WifiMgr; -import com.halo.assistant.HaloApp; -import com.lightgame.utils.Utils; - -import org.json.JSONObject; - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; - -import androidx.annotation.NonNull; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.OnClick; - -/** - * Created by khy on 2017/1/20. - */ -public class FileSenderActivity extends BaseActivity implements FileSenderAdapter.OnCancelListener { - - @BindView(R.id.sender_rv) - RecyclerView mSenderRv; - @BindView(R.id.sender_user_icon) - SimpleDraweeView mSenderUserIcon; - @BindView(R.id.sender_user_name) - TextView mSenderUserName; - @BindView(R.id.sender_user_send_des) - TextView mSenderUserDes; - @BindView(R.id.sender_hint) - TextView mSenderHint; - @BindView(R.id.sender_keep_send) - RelativeLayout mKeepSend; - @BindView(R.id.sender_bottom) - LinearLayout mSenderBottom; - - private FileSenderAdapter mSenderAdapter; - - private DatagramSocket mDatagramSocket; - - private List mFileInfos; - private List> sendData; // 传送成绩单数据 - private List mFileSenderList; - - public final static int KC_REPEAT_RESULT = 15; // 快传继续发送获取APK信息回调 - - private boolean isSendOver; - private boolean isDestroy; - - private long mStartTime; - - // 快传文件发送单线程 - private Executor SINGLE_EXECUTOR = Executors.newSingleThreadExecutor(); - - private Handler handler = new Handler() { - @Override - public void handleMessage(Message msg) { - super.handleMessage(msg); - int position = (int) msg.obj; - switch (msg.what) { - case FileInfo.FLAG_DEFAULT: - mFileInfos.get(position).setResult(FileInfo.FLAG_DEFAULT); - mSenderAdapter.notifyItemChanged(position); - break; - case FileInfo.FLAG_SUCCESS: - mFileInfos.get(position).setResult(FileInfo.FLAG_SUCCESS); - mSenderAdapter.notifyItemChanged(position); - if (position == mFileInfos.size() - 1) initSenderHint(); - break; - case FileInfo.FLAG_FAILURE: - mFileInfos.get(position).setResult(FileInfo.FLAG_FAILURE); - mSenderAdapter.notifyItemChanged(position); - if (position == mFileInfos.size() - 1) initSenderHint(); - break; - case FileInfo.FLAG_CANCEL: - mFileInfos.get(position).setResult(FileInfo.FLAG_CANCEL); - mSenderAdapter.notifyItemChanged(position); - if (position == mFileInfos.size() - 1) initSenderHint(); - break; - } - } - }; - - @NonNull - public static Intent getIntent(Context context) { - Intent intent = new Intent(context, FileSenderActivity.class); - return intent; - } - - @Override - protected int getLayoutId() { - return R.layout.activity_receive_send; - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (resultCode == KC_REPEAT_RESULT && requestCode == KC_REPEAT_RESULT) { - mSenderAdapter.notifyDataSetChanged(); - initUserData(); - HaloApp.getInstance().getMainExecutor().execute(new Runnable() { - @Override - public void run() { - try { - sendFileInfo(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - } - - private void sendFileInfo() throws Exception { - if (mDatagramSocket == null) { - mDatagramSocket = new DatagramSocket(null); - mDatagramSocket.setReuseAddress(true); - mDatagramSocket.bind(new InetSocketAddress(Constant.DEFAULT_SERVER_SENDING_PORT)); - } - String ipAddress = WifiMgr.getInstance(this).getIpAddressFromHotspot(); - InetAddress ipAddressName = InetAddress.getByName(ipAddress); // 转译 - //发送apk列表 - for (FileInfo fileInfo : mFileInfos) { - if (fileInfo.getResult() == 0) { // 过滤已发送过的列表 - String fileInfoJson = FileInfo.toJsonStr(fileInfo); - Utils.log("FileSenderActivity:: 发送的文件列表::" + fileInfoJson); - DatagramPacket sendFileInfoListPacket = new DatagramPacket(fileInfoJson.getBytes() - , fileInfoJson.getBytes().length, ipAddressName, Constant.DEFAULT_SERVER_SENDING_PORT); - mDatagramSocket.send(sendFileInfoListPacket); - Utils.log("FileSenderActivity:: 发送的文件列表完成::" + ipAddressName + "==" + Constant.DEFAULT_SERVER_SENDING_PORT); - } - } - - DatagramPacket sendFileInfoListPacket = new DatagramPacket(Constant.MSG_ADD_DATA_OVER.getBytes() - , Constant.MSG_ADD_DATA_OVER.getBytes().length, ipAddressName, Constant.DEFAULT_SERVER_SENDING_PORT); - mDatagramSocket.send(sendFileInfoListPacket); - Utils.log("FileSenderActivity:: 发送结束请求完成"); - } - - @Override - public void onBackPressed() { - backHint(); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setNavigationTitle(R.string.title_file_sender); - - mFileInfos = (List) HaloApp.get(KcSelectGameActivity.KEY_FILE_INFO, false); - - isDestroy = false; - - sendData = new ArrayList<>(); - mFileSenderList = new ArrayList<>(); - mSenderAdapter = new FileSenderAdapter(this, this, mFileInfos); - mSenderRv.setLayoutManager(new LinearLayoutManager(this)); - mSenderRv.addItemDecoration(new VerticalItemDecoration(this, 8, true)); - mSenderRv.setAdapter(mSenderAdapter); - - init(); - - } - - private void init() { - - Utils.log("FileSenderActivity == init()"); - - initUserData(); - - if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constant.REQUEST_CODE_WRITE_FILE); - } else { - Utils.log("FileSenderActivity == initSendServer()" + mFileInfos.size()); - try { - initSendServer();//开启传送文件 - startReceiver(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private void backHint() { - if (!isSendOver) { - DialogUtils.showWarningDialog(FileSenderActivity.this, - "退出传送", "文件正在传送中,确定退出吗?", "点错了", "坚决退出", new DialogUtils.ConfirmListener() { - @Override - public void onConfirm() { - closePage(); - } - }, null); - } else { - closePage(); - } - - } - - //初始化用户数据 - private void initUserData() { - isSendOver = false; - - Map map = (Map) HaloApp.get("userMap", false); - - long allGameSize = 0; - for (FileInfo mFileInfo : mFileInfos) { - allGameSize = allGameSize + mFileInfo.getSize(); - } - - double size = (((float) allGameSize / 1024) / 1024); - DecimalFormat df = new DecimalFormat("#.00"); - String sizeName = df.format(size) + "MB"; - - mSenderUserDes.setText(mFileInfos.size() + "个游戏,共" + sizeName); - mSenderUserName.setText("发给 " + map.get("receiverName")); - mSenderUserIcon.setImageURI(UserIconUtils.getUserIcon(Integer.parseInt(map.get("usericon")))); - - mSenderBottom.setVisibility(View.GONE); - - mSenderHint.setText("已连接"); - } - - private void initSendServer() throws Exception { - String serverIp = WifiMgr.getInstance(this).getIpAddressFromHotspot(); - - Utils.log("====FileSenderActivity传送个数::" + mFileInfos.size()); - - - //发送的首个游戏 socket被拒绝的概率较大 延迟0.5秒发送试试 - Thread.sleep(500); //test - - for (final FileInfo fileInfo : mFileInfos) { - Utils.log("FileSenderActivity == initSendServer()===" + fileInfo.getName() + "==" + fileInfo.getResult()); - - if (fileInfo.getResult() != 0) continue; // result != 0 是已经传送过的apk - - FileSender fileSender = new FileSender(this, fileInfo, serverIp, Constant.DEFAULT_SERVER_PORT); - fileSender.setOnSendListener(new FileSender.OnSendListener() { - @Override - public void onStart() { - mStartTime = System.currentTimeMillis(); - Utils.log("快传文件发送::onStart" + "==" + fileInfo.getName()); - - } - - @Override - public void onProgress(long progress, long total) { -// Utils.log("快传文件发送中..." + progress + "==" + total + "==" + fileInfo.getName()); - fileInfo.setProgress(progress); - Message message = new Message(); - message.what = FileInfo.FLAG_DEFAULT; - message.obj = getCurrentFileInfoIndex(fileInfo); - handler.sendMessage(message); - } - - @Override - public void onSuccess(FileInfo fileInfo) { - Utils.log("快传文件发送成功::onSuccess" + "==" + fileInfo.getName()); - Message message = new Message(); - message.what = FileInfo.FLAG_SUCCESS; - message.obj = getCurrentFileInfoIndex(fileInfo); - handler.sendMessage(message); - - long sendTime = System.currentTimeMillis() - mStartTime; - Map map = new HashMap<>(); - map.put("sendTime", String.valueOf(sendTime)); - map.put("apkPath", fileInfo.getFilePath()); - map.put("apkSize", String.valueOf(fileInfo.getSize())); - sendData.add(map); - } - - @Override - public void onFailure(Throwable t, FileInfo fileInfo) { - Utils.log("快传文件发送失败::onFailure" + "==" + fileInfo.getName()); - Message message = new Message(); - message.what = FileInfo.FLAG_FAILURE; - message.obj = getCurrentFileInfoIndex(fileInfo); - handler.sendMessage(message); - } - - @Override - public void onCancel(FileInfo fileInfo) { - Utils.log("快传文件用户主动取消::onCancel" + "==" + fileInfo.getName()); - Message message = new Message(); - message.what = FileInfo.FLAG_CANCEL; - message.obj = getCurrentFileInfoIndex(fileInfo); - handler.sendMessage(message); - } - - }); - mFileSenderList.add(fileSender); - SINGLE_EXECUTOR.execute(fileSender); - } - } - - private void startReceiver() { - HaloApp.getInstance().getMainExecutor().execute(new Runnable() { - @Override - public void run() { - try { - initTestReceiverData(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - - public void closePage() { - if (mDatagramSocket != null) { -// mDatagramSocket.disconnect(); - mDatagramSocket.close(); - mDatagramSocket = null; - } - - stopAllFileSendingTask(); - HaloApp.remove(KcSelectGameActivity.KEY_FILE_INFO); - HaloApp.put("sendData", sendData); - - finish(); - } - - private int getCurrentFileInfoIndex(FileInfo curFileInfo) { - for (int i = 0; i < mFileInfos.size(); i++) { - FileInfo fileInfo = mFileInfos.get(i); - if (curFileInfo == null) { - return -100; - } - if (fileInfo.getFileTag().equals(curFileInfo.getFileTag())) { - Utils.log("FileSenderActivity === index::" + i); - return i; - } - } - Utils.log("FileReceiverActivity:: 获取刷新位置异常"); - return -1; - } - - private void initTestReceiverData() throws Exception { - if (mDatagramSocket == null) { - mDatagramSocket = new DatagramSocket(null); - mDatagramSocket.setReuseAddress(true); - mDatagramSocket.bind(new InetSocketAddress(Constant.DEFAULT_SERVER_SENDING_PORT)); - } - Utils.log("接收方取消Socket端口" + Constant.DEFAULT_SERVER_SENDING_PORT); - byte[] receiveData = new byte[1024]; - // 主要接收 接收方取消操作 - while (!isDestroy) { - DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); - mDatagramSocket.receive(receivePacket); - String response = new String(receivePacket.getData(), 0, receivePacket.getLength()).trim(); - Utils.log("====接收取消消息中。。。" + response); - if (response != null && response.contains(Constant.MSG_RECEIVER_CANCEL)) { - Utils.log("====接收取消消息完毕。。。" + response); - - // 进入文件发送列表界面 (并且通知文件接收方进入文件接收列表界面) - JSONObject jsonObject = new JSONObject(response); - int cancelPosition = (int) jsonObject.get("controlTag"); - FileSender fileSender = mFileSenderList.get(cancelPosition); - Message message = new Message(); - message.what = FileInfo.FLAG_CANCEL; - message.obj = cancelPosition; - handler.sendMessage(message); - if (fileSender != null && fileSender.isRunning()) { - Utils.log("接收方取消发送"); - fileSender.cancel(); - } - } else if (response != null && response.contains(Constant.MSG_ADD_DATA_OVER)) { - try { - Utils.log("====收到UDP结束请求 开始传送文件"); - initSendServer();//开启传送文件 - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - - /** - * 停止所有的文件发送任务 - */ - private void stopAllFileSendingTask() { - for (FileSender fileSender : mFileSenderList) { - if (fileSender != null) { - fileSender.cancel(); - fileSender.finish(); - } - } - } - - @Override - protected void onDestroy() { - super.onDestroy(); - isDestroy = true; - handler.removeCallbacksAndMessages(null); - } - - private void initSenderHint() { - for (FileInfo mFileInfo : mFileInfos) { - if (mFileInfo.getResult() == 0 || mFileInfo.getResult() == 1) { // 还有没完成的任务 - return; - } - } - - mSenderBottom.setVisibility(View.VISIBLE); - - int sendSuccess = 0; - isSendOver = true; - for (FileInfo mFileInfo : mFileInfos) { - if (mFileInfo.getResult() == FileInfo.FLAG_SUCCESS) { - sendSuccess++; - } - } - - if (sendSuccess > 0) { - mSenderHint.setVisibility(View.VISIBLE); - mSenderHint.setText("传输结束,成功分享" + sendSuccess + "个游戏"); - } else { - if (mFileInfos.get(mFileInfos.size() - 1).getResult() == FileInfo.FLAG_CANCEL) { - mSenderHint.setVisibility(View.VISIBLE); - mSenderHint.setText("传输已取消"); - } else if (mFileInfos.get(mFileInfos.size() - 1).getResult() == FileInfo.FLAG_FAILURE) { - mSenderHint.setVisibility(View.VISIBLE); - mSenderHint.setText("传输失败"); - } - } - - } - - @Override - public void OnCancelPosition(int position) { - if (position >= mFileSenderList.size()) return; - FileSender fileSender = mFileSenderList.get(position); - Utils.log("发送方准备取消发送" + position); - if (fileSender != null && fileSender.isRunning()) { - Utils.log("发送方取消发送"); - fileSender.cancel(); - } - } - - @OnClick({R.id.sender_keep_send, R.id.sender_back}) - public void onClick(View view) { - switch (view.getId()) { - case R.id.sender_back: - backHint(); - break; - case R.id.sender_keep_send: - startActivityForResult(KcSelectGameActivity.getIntent(this, true), KC_REPEAT_RESULT); - break; - default: - break; - } - } -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileShareActivity.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileShareActivity.java deleted file mode 100644 index 31ea3d3718..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileShareActivity.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.gh.gamecenter.kuaichuan.view; - -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; - -import com.gh.common.util.EntranceUtils; -import com.gh.gamecenter.NormalActivity; - -import androidx.annotation.NonNull; - -public class FileShareActivity extends NormalActivity { - @NonNull - public static Intent getIntent(Context context, String entrance) { - Bundle args = new Bundle(); - args.putString(EntranceUtils.KEY_ENTRANCE, entrance); - return getTargetIntent(context, FileShareActivity.class, FileShareFragment.class, args); - } -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileShareFragment.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileShareFragment.java deleted file mode 100644 index 4d5be7ee8f..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/FileShareFragment.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.gh.gamecenter.kuaichuan.view; - -import android.Manifest; -import android.content.Intent; -import android.os.Bundle; -import android.os.Handler; -import android.text.Html; -import android.view.View; -import android.widget.TextView; - -import com.gh.common.util.DialogUtils; -import com.gh.common.util.MtaHelper; -import com.gh.gamecenter.CleanApkActivity; -import com.gh.gamecenter.R; -import com.gh.gamecenter.ShareGhActivity; -import com.gh.gamecenter.normal.NormalFragment; - -import androidx.annotation.Nullable; - -/** - * Created by khy on 2017/1/20. - */ -public class FileShareFragment extends NormalFragment { - - private String[] permissions = {Manifest.permission.ACCESS_WIFI_STATE}; - - public final static int KC_REQUEST = 2; // 快传传输完成成绩单 - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - // 分享成绩单 - if (requestCode == KC_REQUEST) { - DialogUtils.showKuaiChuanResult(getActivity(), new Handler(), requestCode, "shareKc.jpg"); - } - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setNavigationTitle(R.string.download_send_traffic_free); - } - - @Override - protected int getLayoutId() { - return R.layout.fragment_file_send; - } - - @Override - protected void initView(View view) { - super.initView(view); - view.findViewById(R.id.file_send_btn).setOnClickListener(v -> { - MtaHelper.onEvent("下载管理", "免流量传送", "我要发送"); - - startActivityForResult(KcSelectGameActivity.getIntent(getContext(), false), KC_REQUEST); - }); - - view.findViewById(R.id.file_receiver_btn).setOnClickListener(v -> { - MtaHelper.onEvent("下载管理", "免流量传送", "我要接收"); - - startActivityForResult(ReceiverWaitingActivity.getIntent(getContext()), KC_REQUEST); - }); - - TextView shareGh = view.findViewById(R.id.share_gh); - shareGh.setText(Html.fromHtml(getString(R.string.kc_share_gh_hint))); - shareGh.setOnClickListener(v -> { - MtaHelper.onEvent("下载管理", "免流量传送", "好友还没安装光环助手"); - - Intent intent = ShareGhActivity.getIntent(getContext()); - getActivity().startActivity(intent); - }); - - TextView cleanApk = view.findViewById(R.id.clean_apk_tv); - cleanApk.setText(Html.fromHtml(getString(R.string.kc_clean_apk_hint))); - - cleanApk.setOnClickListener(v -> { - MtaHelper.onEvent("下载管理", "免流量传送", "安装包清理"); - - Intent intent = CleanApkActivity.getIntent(getContext()); - getActivity().startActivity(intent); - }); - } - -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/KcSelectGameActivity.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/view/KcSelectGameActivity.java deleted file mode 100644 index 912e08027e..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/KcSelectGameActivity.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.gh.gamecenter.kuaichuan.view; - -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.view.View; -import android.view.ViewGroup; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.ProgressBar; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import com.gh.base.BaseActivity; -import com.gh.common.util.DisplayUtils; -import com.gh.common.view.VerticalItemDecoration; -import com.gh.gamecenter.R; -import com.gh.gamecenter.adapter.KcSelectGameAdapter; -import com.gh.gamecenter.kuaichuan.FileInfo; -import com.halo.assistant.HaloApp; -import com.lightgame.utils.Utils; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; - -import static com.gh.gamecenter.kuaichuan.view.FileSenderActivity.KC_REPEAT_RESULT; - -/** - * Created by khy on 2017/1/20. - * 快传-选择游戏 - */ -public class KcSelectGameActivity extends BaseActivity { - - public static final String KEY_FILE_INFO = "FileInfo"; - @BindView(R.id.select_game_rv) - RecyclerView mSelectRv; - @BindView(R.id.select_game_send) - TextView mSelectSend; - @BindView(R.id.select_game_all) - CheckBox selectAll; - @BindView(R.id.install_count) - TextView installCount; - @BindView(R.id.select_game_installed_ll) - RelativeLayout installRl; - @BindView(R.id.select_game_pb) - ProgressBar mSelectPb; - - private KcSelectGameAdapter mAdapter; - - public final static String KEY_ISCONN = "isConn"; - public final static int SEND_OVER_REQUEST = 16; // 快传 传输完成后直接退出选择游戏(当前)页面 - - private boolean mIsConn; - private LinearLayoutManager layoutManager; - private RelativeLayout.LayoutParams rparams; - - @NonNull - public static Intent getIntent(Context context, boolean isConn) { - Intent intent = new Intent(context, KcSelectGameActivity.class); - intent.putExtra(KEY_ISCONN, isConn); - return intent; - } - - @Override - protected int getLayoutId() { - return R.layout.activity_kc_select_game; - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (requestCode == SEND_OVER_REQUEST) { - if (data != null && data.getExtras() != null && data.getExtras().getBoolean("isFinish")) { - finish(); - } - } - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setNavigationTitle(getString(R.string.title_select_game)); - - if (getIntent() != null && getIntent().getExtras() != null) { - mIsConn = getIntent().getExtras().getBoolean(KEY_ISCONN); - } else { - mIsConn = false; - } - - selectAll.setVisibility(View.GONE); - - mAdapter = new KcSelectGameAdapter(this, mSelectSend, installCount, mSelectPb); - layoutManager = new LinearLayoutManager(this); - mSelectRv.setLayoutManager(layoutManager); - mSelectRv.addItemDecoration(new VerticalItemDecoration(this, 8, false)); - mSelectRv.setAdapter(mAdapter); - - rparams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - DisplayUtils.dip2px(this, 40)); - - mSelectSend.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - List selectData = mAdapter.getSelectData(); - if (selectData.size() == 0) { - Utils.toast(KcSelectGameActivity.this, "请选择要发送的游戏"); - return; - } - - if (mIsConn) { - List oldInfo = (List) HaloApp.get(KcSelectGameActivity.KEY_FILE_INFO, false); - if (oldInfo == null) { - oldInfo = new ArrayList<>(); - } - for (FileInfo fileInfo : selectData) { - oldInfo.add(fileInfo); - } - setResult(KC_REPEAT_RESULT); - finish(); - } else { - HaloApp.put(KcSelectGameActivity.KEY_FILE_INFO, selectData); - startActivityForResult(ChooseReceiverActivity.getIntent(KcSelectGameActivity.this, false), SEND_OVER_REQUEST); - } - - } - }); - - selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - HashMap selectPosition = new HashMap<>(); - int itemCount = mAdapter.getItemCount(); - if (isChecked) { - for (int i = 0; i < itemCount; i++) { - selectPosition.put(i, true); - } - } else { - for (int i = 0; i < itemCount; i++) { - selectPosition.put(i, false); - } - } - - mAdapter.setSelectPosition(selectPosition); - mAdapter.notifyItemRangeChanged(0, itemCount); - } - }); - - mSelectRv.addOnScrollListener(new RecyclerView.OnScrollListener() { - @Override - public void onScrolled(RecyclerView recyclerView, int dx, int dy) { - super.onScrolled(recyclerView, dx, dy); - if (dy == 0) return; - - int position = layoutManager.findFirstVisibleItemPosition(); - int gameSize = mAdapter.getGameSize(); - - if (gameSize == 0) { // 游戏列表为空 - if (position == gameSize) { - int buttom = layoutManager.findViewByPosition(position).getBottom(); - int i = installRl.getHeight() + DisplayUtils.dip2px(KcSelectGameActivity.this, 43); - if (buttom <= i && i / 2 < buttom) { - rparams.topMargin = buttom - installRl.getHeight() - DisplayUtils.dip2px(KcSelectGameActivity.this, 43); - installRl.setLayoutParams(rparams); - installCount.setText("已安装的游戏(" + gameSize + ")"); - } else { - installCount.setText("已安装的应用(" + mAdapter.getAppSize() + ")"); - rparams.topMargin = 0; - installRl.setLayoutParams(rparams); - } - } else { - installCount.setText("已安装的应用(" + mAdapter.getAppSize() + ")"); - rparams.topMargin = 0; - installRl.setLayoutParams(rparams); - } - } else { - if (position >= gameSize) { - installCount.setText("已安装的应用(" + mAdapter.getAppSize() + ")"); - } else { - installCount.setText("已安装的游戏(" + mAdapter.getGameSize() + ")"); - } - - if (position == gameSize - 1) { - int buttom = layoutManager.findViewByPosition(position).getBottom(); - if (buttom <= installRl.getHeight()) { - rparams.topMargin = buttom - installRl.getHeight(); - installRl.setLayoutParams(rparams); - } else { - rparams.topMargin = 0; - installRl.setLayoutParams(rparams); - } - } else { - rparams.topMargin = 0; - installRl.setLayoutParams(rparams); - } - } - - } - }); - - } -} diff --git a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/ReceiverWaitingActivity.java b/app/src/main/java/com/gh/gamecenter/kuaichuan/view/ReceiverWaitingActivity.java deleted file mode 100644 index 8a7d7603fd..0000000000 --- a/app/src/main/java/com/gh/gamecenter/kuaichuan/view/ReceiverWaitingActivity.java +++ /dev/null @@ -1,391 +0,0 @@ -package com.gh.gamecenter.kuaichuan.view; - -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.graphics.Color; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.preference.PreferenceManager; -import android.text.Html; -import android.text.TextUtils; -import android.view.MenuItem; -import android.view.View; -import android.widget.TextView; - -import com.facebook.drawee.view.SimpleDraweeView; -import com.gh.base.BaseActivity; -import com.gh.common.util.DialogUtils; -import com.gh.common.util.RandomUtils; -import com.gh.common.util.UserIconUtils; -import com.gh.common.view.RadarLayout; -import com.gh.gamecenter.R; -import com.gh.gamecenter.kuaichuan.BaseTransfer; -import com.gh.gamecenter.kuaichuan.Constant; -import com.gh.gamecenter.kuaichuan.FileInfo; -import com.gh.gamecenter.kuaichuan.HotspotManager; -import com.gh.gamecenter.kuaichuan.IpPortInfo; -import com.gh.gamecenter.kuaichuan.WifiMgr; -import com.gh.gamecenter.receiver.WifiAPBroadcastReceiver; -import com.halo.assistant.HaloApp; -import com.lightgame.utils.Utils; - -import org.json.JSONObject; - -import java.lang.ref.WeakReference; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.List; - -import androidx.annotation.NonNull; -import butterknife.BindView; - -/** - * Created by khy on 2017/1/20. - */ -public class ReceiverWaitingActivity extends BaseActivity { - - @BindView(R.id.waiting_user_icon) - SimpleDraweeView mUserIcon; - @BindView(R.id.waiting_user_name) - TextView mUserName; - @BindView(R.id.waiting_user_status) - TextView mUserStatus; - @BindView(R.id.waiting_conn) - TextView mWaitingConn; - @BindView(R.id.waiting_radar_layout) - RadarLayout mRadarLayout; - @BindView(R.id.waiting_hint) - TextView mWaitingHint; - @BindView(R.id.waiting_gprs_hint) - TextView mGPRSHint; - @BindView(R.id.waiting_no_conn_hint) - TextView mNoConnHint; - /** - * 开启 文件接收方 通信服务 (必须在子线程执行) - * - * @param serverPort - * @throws Exception - */ - DatagramSocket mDatagramSocket; - private WifiAPBroadcastReceiver mWifiAPBroadcastReceiver; - private List mFileInfos; // 接收到的文件列表 - private SharedPreferences mSharedPreferences; - private boolean mIsInitialized; - private boolean isOpenWifi; //记录开热点前的WiFi状态 - private boolean isDestroy; - private String mySsid; - /** - * 与 文件发送方 通信的 线程 - */ - private Runnable mUdpServerRunnable; - private Handler mHandler = new MyHandler(this); - - @NonNull - public static Intent getIntent(Context context) { - return new Intent(context, ReceiverWaitingActivity.class); - } - - @Override - protected int getLayoutId() { - return R.layout.activity_receive_waiting; - } - - @Override - public void onBackPressed() { - Utils.log("============onBackPressed"); - - unregisterReceiver(mWifiAPBroadcastReceiver); - - closePage(); - //关闭热点 - HotspotManager.initUserAp(getApplicationContext()); - - if (isOpenWifi) { - WifiMgr.getInstance(this).openWifi(); - } - } - @Override - public boolean onMenuItemClick(MenuItem item) { - if (item.getItemId() == R.id.menu_receive_hint) showConnHintDialog(); - return super.onMenuItemClick(item); - } - - @Override - public int provideNavigationIcon() { - return R.drawable.ic_filereceive_back; - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setNavigationTitle(R.string.title_receive_waiting); - - setToolbarMenu(R.menu.menu_receive); - - mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); - mIsInitialized = false; - isDestroy = false; - isOpenWifi = WifiMgr.getInstance(this).isWifiEnable(); - - mUserName.setText(mSharedPreferences.getString("user_name", "光环用户")); - - if (isOpenWifi) { - WifiMgr.getInstance(this).closeWifi(); - } - - mUserStatus.setText("正在初始化..."); - mRadarLayout.setUseRing(true); - mRadarLayout.setColor(Color.WHITE); - mRadarLayout.setCount(4); - mRadarLayout.start(); - - mFileInfos = new ArrayList<>(); - - HotspotManager.initApData(getApplicationContext()); // 记录原始热点信息 - - //初始化热点 - if (HotspotManager.isApOn(getApplicationContext())) { - HotspotManager.disableAp(getApplicationContext()); - } - - mWifiAPBroadcastReceiver = new WifiAPBroadcastReceiver() { - @Override - public void onWifiApEnabled() { - if (!mIsInitialized) { - mUdpServerRunnable = createSendMsgToFileSenderRunnable(); - HaloApp.getInstance().getMainExecutor().execute(mUdpServerRunnable); - mIsInitialized = true; - - mWaitingConn.setVisibility(View.VISIBLE); - mUserStatus.setText(Html.fromHtml(getString(R.string.create_hotspot, mySsid))); - mWaitingHint.setVisibility(View.GONE); - mUserName.setVisibility(View.GONE); - mGPRSHint.setVisibility(View.VISIBLE); - } - - } - }; - - IntentFilter filter = new IntentFilter(WifiAPBroadcastReceiver.ACTION_WIFI_AP_STATE_CHANGED); - registerReceiver(mWifiAPBroadcastReceiver, filter); - - HotspotManager.isApOn(getApplicationContext()); - - mySsid = mSharedPreferences.getString("hotspotName", null); - if (TextUtils.isEmpty(mySsid)) { - String chars = "abcdefghijklmnopqrstuvwxyz"; - int[] randomArray = RandomUtils.getRandomArray(2, 25); - - mySsid = "ghZS-"; - for (int i : randomArray) { - mySsid = mySsid + chars.charAt(i); - } - - int default_user_icon = mSharedPreferences.getInt("default_user_icon", 0); - if (default_user_icon == 0) { - default_user_icon = RandomUtils.nextInt(8) + 1; - mSharedPreferences.edit().putInt("default_user_icon", default_user_icon).apply(); - } - - mySsid = mySsid + default_user_icon; - mSharedPreferences.edit().putString("hotspotName", mySsid).apply(); - } - mUserIcon.setImageURI(UserIconUtils.getUserIcon(mSharedPreferences.getInt("default_user_icon", 1))); - - HotspotManager.configApState(getApplicationContext(), mySsid); // change Ap state :boolean - - mHandler.sendEmptyMessageDelayed(1, 300000); - - boolean showConnHintReceiver = mSharedPreferences.getBoolean("showConnHintReceiver", true); - - if (showConnHintReceiver) { - showConnHintDialog(); - mSharedPreferences.edit().putBoolean("showConnHintReceiver", false).apply(); - } - } - - /** - * 创建发送UDP消息到 文件发送方 的服务线程 - */ - private Runnable createSendMsgToFileSenderRunnable() { - return new Runnable() { - @Override - public void run() { - try { - startFileReceiverServer(Constant.DEFAULT_SERVER_COM_PORT); - } catch (Exception e) { - Utils.log("发送UDP消息到 文件发送方 异常" + e.toString()); - e.printStackTrace(); - } - } - }; - } - - /** - * 关闭广播并关闭Socket流 - */ - private void closePage() { - mRadarLayout.stop(); - - mHandler.removeMessages(1); // 取消无人连接消息 - - try { - if (mWifiAPBroadcastReceiver != null) { - unregisterReceiver(mWifiAPBroadcastReceiver); - mWifiAPBroadcastReceiver = null; - } - } catch (Exception e) { - Utils.log("接收方d等待连接异常-关闭广播"); - e.printStackTrace(); - } - - closeSocket(); - finish(); - } - - private void showConnHintDialog() { - DialogUtils.showHintDialog(ReceiverWaitingActivity.this, "请告诉你的好友这样操作:", "1.打开光环助手,点击左上角“↓”" + - "\n2.点击右上方的“免流量传送” \n3.点击“我要发送”", "确定"); - } - - private void startFileReceiverServer(int serverPort) throws Exception { - //网络连接上,无法获取IP的问题 - int count = 0; - String localAddress = WifiMgr.getInstance(ReceiverWaitingActivity.this).getHotspotLocalIpAddress(); - Utils.log("开启 文件接收方 通信服务 " + localAddress); - - //ip地址无效 重新获取 - while (localAddress.equals(Constant.DEFAULT_UNKOWN_IP) && count < Constant.DEFAULT_TRY_TIME) { - Thread.sleep(1000); - localAddress = WifiMgr.getInstance(ReceiverWaitingActivity.this).getHotspotLocalIpAddress(); - count++; - } - - if (mDatagramSocket == null) { - mDatagramSocket = new DatagramSocket(null); - mDatagramSocket.setReuseAddress(true); - mDatagramSocket.bind(new InetSocketAddress(serverPort)); - } - - byte[] receiveData = new byte[1024]; - byte[] sendData; - Utils.log("接收接受信息 "); - while (!isDestroy) { - //接收 文件发送方的消息 - DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); - mDatagramSocket.receive(receivePacket); - String msg = new String(receivePacket.getData(), 0, receivePacket.getLength()).trim(); - InetAddress inetAddress = receivePacket.getAddress(); - - int port = receivePacket.getPort(); - Utils.log("接收信息中。。。" + msg); - if (msg != null && msg.contains(Constant.MSG_FILE_RECEIVER_INIT)) { - Utils.log("接收方初始化完毕准备进去传输页面 并回馈消息给发送者" + inetAddress); - -// HaloApp.put(KcSelectGameActivity.KEY_FILE_INFO, mFileInfos); //保存数据列表 启用改为Intent传输 - - // 反馈 文件发送方的消息 -// sendData = Constant.MSG_FILE_RECEIVER_INIT_SUCCESS.getBytes(BaseTransfer.UTF_8); - JSONObject receiverData = new JSONObject(); - receiverData.put(Constant.MSG_FILE_RECEIVER_INIT_SUCCESS, mSharedPreferences.getString("user_name", "光环用户")); - sendData = receiverData.toString().getBytes(BaseTransfer.UTF_8); - - DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, inetAddress, port); - mDatagramSocket.send(sendPacket); - - Message message = new Message(); - message.what = 0; - JSONObject jsonObject = new JSONObject(msg); - message.obj = new IpPortInfo(inetAddress, port, jsonObject.getString(Constant.MSG_FILE_RECEIVER_INIT), - mSharedPreferences.getString("user_name", "光环用户"), jsonObject.getInt("UserIcon")); - mHandler.sendMessage(message); - - } else { - if (msg != null) { - Utils.log("保存文件列表数据" + msg); - parseFileInfo(msg); - } - } - } - } - - /** - * 关闭UDP Socket 流 - */ - private void closeSocket() { - if (mDatagramSocket != null) { -// mDatagramSocket.disconnect(); - mDatagramSocket.close(); - mDatagramSocket = null; - } - } - - - /** - * 解析FileInfo - * - * @param msg - */ - private void parseFileInfo(String msg) { - FileInfo fileInfo = FileInfo.toObject(msg); - if (fileInfo != null && fileInfo.getFilePath() != null) { - mFileInfos.add(fileInfo); - } - } - - @Override - protected void onDestroy() { - super.onDestroy(); - isDestroy = true; - mHandler.removeCallbacksAndMessages(null); - } - - static class MyHandler extends Handler { - private WeakReference mActivityWeakReference; - - MyHandler(Activity activity) { - mActivityWeakReference = new WeakReference<>(activity); - } - - @Override - public void handleMessage(Message msg) { - super.handleMessage(msg); - - ReceiverWaitingActivity activity = (ReceiverWaitingActivity) mActivityWeakReference.get(); - if (activity != null) { - if (msg.what == 0) { - if (activity.mFileInfos.size() == 0) { - Utils.toast(activity, "接收异常::ReceiverWaitingActivity"); - return; - } - ArrayList list = new ArrayList(); - list.add(activity.mFileInfos); // 把真个list集合塞进parentList(0)里, List 无法进行序列化 - - IpPortInfo ipPortInfo = (IpPortInfo) msg.obj; - Bundle bundle = new Bundle(); - bundle.putSerializable(Constant.KEY_IP_PORT_INFO, ipPortInfo); -// bundle.putSerializable(Constant.KEY_IP_FILE_INFO, (Serializable) activity.mFileInfos); - bundle.putParcelableArrayList(Constant.KEY_IP_FILE_INFO, list); - bundle.putBoolean("isOpenWifi", activity.isOpenWifi); - - Intent intent = new Intent(activity, FileReceiverActivity.class); - intent.putExtras(bundle); - activity.startActivity(intent); - - activity.closePage(); - } else if (msg.what == 1) { - activity.mNoConnHint.setVisibility(View.VISIBLE); - } - } - } - } - - -} diff --git a/app/src/main/res/layout/activity_share_gh.xml b/app/src/main/res/layout/activity_share_gh.xml index 2d360616d4..6cacc69df7 100644 --- a/app/src/main/res/layout/activity_share_gh.xml +++ b/app/src/main/res/layout/activity_share_gh.xml @@ -42,20 +42,6 @@ android:textSize = "12sp" android:textStyle = "bold" /> -