package com.gh.gamecenter; import android.animation.Animator; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.wifi.ScanResult; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.text.Html; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; 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.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 butterknife.BindView; import butterknife.OnClick; import static com.gh.gamecenter.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.reuse_actionbar) RelativeLayout mActionbar; @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; @BindView(R.id.actionbar_iv_back) ImageView mBackIv; @BindView(R.id.actionbar_tv_title) TextView mTitleTv; 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); @NonNull public static Intent getIntent(Context context, boolean showConnHintDialog) { Intent intent = new Intent(context, ChooseReceiverActivity.class); intent.putExtra("showConnHintDialog", showConnHintDialog); return intent; } @Override protected int getLayoutId() { return R.layout.activity_choosereceiver; } @Override public void onBackPressed() { super.onBackPressed(); closeSocket(); HaloApp.remove("FileInfo"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initTitle(getString(R.string.title_choose_activity)); mTitleTv.setTextColor(Color.WHITE); mBackIv.setImageResource(R.drawable.reuse_kc_back); // 添加分享图标 TextView hintTv = new TextView(this); hintTv.setText("操作说明"); hintTv.setTextColor(Color.WHITE); hintTv.setGravity(Gravity.CENTER); hintTv.setPadding(DisplayUtils.dip2px(this, 13), 0, DisplayUtils.dip2px(this, 13), 0); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); params.addRule(RelativeLayout.CENTER_VERTICAL); RelativeLayout reuse_actionbar = (RelativeLayout) mContentView.findViewById( R.id.reuse_actionbar); reuse_actionbar.addView(hintTv, params); //修改沉浸栏以及ActionBar 颜色 mActionbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.scan_bg)); // SystemBarTintManager tintManager = getTintManager(); // TODO: 27/09/17 更改沉浸栏颜色?? // if (tintManager != null) { // tintManager.setStatusBarTintResource(R.color.scan_bg); // } // init(); hintTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showConnHintDialog(); } }); boolean showConnHintDialog = sp.getBoolean("showConnHintDialog", true); if (showConnHintDialog || (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().getBoolean("showConnHintDialog"))) { if (showConnHintDialog) { sp.edit().putBoolean("showConnHintDialog", false).apply(); } showConnHintDialog(); } } private void init() { sp = PreferenceManager.getDefaultSharedPreferences(this); 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); } 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() { super.onDestroy(); mRadarView.setSearching(false); isDestroy = true; isStopScan = true; handler.removeCallbacksAndMessages(null); } @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.点击“零流量传送”,再点击“我要接收”", // "确定"); // TODO 是否需要关闭扫描?? 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()); } @OnClick(R.id.actionbar_rl_back) public void onBackListener() { closeSocket(); HaloApp.remove("FileInfo"); } //发送UDP通知信息到 文件接收方 开启ServerSocketRunnable private void createSendMsgToServerRunnable(final String ipAddress) { HaloApp.MAIN_EXECUTOR.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 (!"192.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("FileInfo", 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() { mActionbar.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() { mActionbar.setVisibility(View.VISIBLE); Utils.toast(ChooseReceiverActivity.this, "连接失败"); 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; } } }