0

버튼을 누르면 시작되는 스레드가 있고, 스레드에는 wifi와 관련된 브로드 캐스트 리스너 및 작업이 포함되어 있습니다. 그리고 마지막으로 검색된 피어와 안드로이드 장치를 연결합니다. 방법을 알고 싶습니다. 내 스레드가 살아있을 많은 시간 ?? 내 스레드 클래스는 다음과 같습니다안드로이드 스레드의 수명 시간

public class ConnectPeers extends Thread { 



     private List<WifiP2pDevice> deviceList = new ArrayList<WifiP2pDevice>(); 
     Context mContext; 
     private static final String TAG = "MainWiFiDirectActivity"; 
     WifiP2pManager wifiP2pManager; 
     Channel wifiDirectChannel; 
     IntentFilter peerfilter; 
     IntentFilter connectionfilter; 
     IntentFilter p2pEnabled; 
     public ConnectPeers(Context mContext) { 
     // TODO Auto-generated constructor stub 

      this.mContext = mContext; 

    } 
     /** 
      * Listing 16-19: Creating a WiFi P2P Manager Action Listener 
      */ 
      private ActionListener actionListener = new ActionListener() { 
      public void onFailure(int reason) { 

      // Toast.makeText(getApplicationContext(),"wifi direct reason"+String.valueOf(reason),Toast.LENGTH_SHORT).show(); 
       String errorMessage = "WiFi Direct Failed: "; 
       switch (reason) { 
       case WifiP2pManager.BUSY : 
        errorMessage += "Framework busy."; 
       // Toast.makeText(getApplicationContext(),errorMessage+String.valueOf(reason),Toast.LENGTH_SHORT).show(); 

        break; 
       case WifiP2pManager.ERROR : 
        errorMessage += "Internal error."; 
      //  Toast.makeText(getApplicationContext(),errorMessage+String.valueOf(reason),Toast.LENGTH_SHORT).show(); 
        break; 
       case WifiP2pManager.P2P_UNSUPPORTED : 
        errorMessage += "Unsupported."; 
      //  Toast.makeText(getApplicationContext(),errorMessage+String.valueOf(reason),Toast.LENGTH_SHORT).show(); 
        break; 
       default: 
        errorMessage += "Unknown error."; 
        break; 
       } 
       Log.d(TAG, errorMessage); 
      } 
      public void onSuccess() { 
        // Success! 
        // Return values will be returned using a Broadcast Intent 
       } 
       }; 

      /** 
      * Listing 16-18: Initializing Wi-Fi Direct 
      */ 
     private void initializeWiFiDirect() { 
       wifiP2pManager = 
        (WifiP2pManager)mContext.getSystemService(Context.WIFI_P2P_SERVICE); 

       wifiDirectChannel = wifiP2pManager.initialize(mContext,mContext.getMainLooper(), 
        new ChannelListener() { 
        public void onChannelDisconnected() { 
        initializeWiFiDirect(); 
        } 
        } 
       ); 
       } 
     /** 
      * Listing 16-21: Receiving a Wi-Fi Direct status change 
      */ 
      BroadcastReceiver p2pStatusReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       int WiFiDirectState = intent.getIntExtra(
       WifiP2pManager.EXTRA_WIFI_STATE, 
       WifiP2pManager.WIFI_P2P_STATE_DISABLED); 

       switch (WiFiDirectState) { 
       case (WifiP2pManager.WIFI_P2P_STATE_ENABLED): 
       Toast.makeText(mContext,String.valueOf(WiFiDirectState), Toast.LENGTH_SHORT).show(); 
       discoverPeers(); 
       new Handler().postDelayed(new Runnable() { 
        @Override 
        public void run() { 
         if(!deviceList.isEmpty()) 
         { 
           connectTo(deviceList.get(0)); 

         } 
        } 
       }, 4000); 

        break; 
       default: 

       } 
      } 
      }; 
      /** 
      * Listing 16-22: Discovering Wi-Fi Direct peers 
      */ 
      private void discoverPeers() { 
      wifiP2pManager.discoverPeers(wifiDirectChannel, actionListener); 
      } 

      BroadcastReceiver peerDiscoveryReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       wifiP2pManager.requestPeers(wifiDirectChannel, 
       new PeerListListener() { 
        public void onPeersAvailable(WifiP2pDeviceList peers) { 
        deviceList.clear(); 

        deviceList.addAll(peers.getDeviceList()); 

        } 
       }); 
       Toast.makeText(mContext,"discovery called", Toast.LENGTH_SHORT).show(); 

      } 

      }; 
      /** 
      * Listing 16-23: Requesting a connection to a Wi-Fi Direct peer 
      */ 
      void connectTo(WifiP2pDevice device) { 
      WifiP2pConfig config = new WifiP2pConfig(); 
      config.deviceAddress = device.deviceAddress; 
      config.groupOwnerIntent=15; 
      // if(device.status==0) 
      wifiP2pManager.connect(wifiDirectChannel, config, actionListener); 
      Toast.makeText(mContext,"Connect to", Toast.LENGTH_SHORT).show(); 

//  wifiP2pManager.createGroup(wifiDirectChannel, actionListener); 
      } 
      /** 
      * Listing 16-24: Connecting to a Wi-Fi Direct peer 
      */ 
      BroadcastReceiver connectionChangedReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 

       // Extract the NetworkInfo 
       String extraKey = WifiP2pManager.EXTRA_NETWORK_INFO; 
       NetworkInfo networkInfo = 
       (NetworkInfo)intent.getParcelableExtra(extraKey); 

       // Check if we're connected 
       if (networkInfo.isConnected()) { 
       wifiP2pManager.requestConnectionInfo(wifiDirectChannel, 
        new ConnectionInfoListener() { 
        public void onConnectionInfoAvailable(WifiP2pInfo info) { 
         // If the connection is established 
         if (info.groupFormed) { 
         // If we're the server 
         if (info.isGroupOwner) { 
          // TODO Initiate server socket. 
         // initiateServerSocket(); 

          Toast.makeText(mContext,"server"+info.groupOwnerAddress.toString(), Toast.LENGTH_LONG).show(); 

         } 
         // If we're the client 
         else if (info.groupFormed) { 
          // TODO Initiate client socket. 
         // initiateClientSocket(info.groupOwnerAddress.toString()); 

          Toast.makeText(mContext,"client"+info.groupOwnerAddress.toString(), Toast.LENGTH_LONG).show(); 

         } 
         } 
        } 
        }); 
       } else { 
       Log.d(TAG, "Wi-Fi Direct Disconnected"); 
       } 
      } 
      }; 
     @Override 
      public void run() { 

      initializeWiFiDirect();  
       peerfilter = new IntentFilter(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); 
       connectionfilter = new IntentFilter(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); 
       p2pEnabled = new IntentFilter(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); 

       // When you are done 
      mContext. registerReceiver(peerDiscoveryReceiver, peerfilter); 
      mContext. registerReceiver(connectionChangedReceiver, connectionfilter); 
      mContext. registerReceiver(p2pStatusReceiver, p2pEnabled); 
     } 

} 
+0

여기에서 뭔가를 찾을 수 있습니다. http://stackoverflow.com/questions/7363666/android-asynctask-and-thread-life-cycle – Triode

+0

타이머를 넣고 (처음에 하나)이 시간을 측정하지 않는 이유는 무엇입니까? 다양한 장소에서 몇 번씩, 그 합계를 시도의 합계로 나누고보십시오 .. 저는 누군가가 여러분에게 대략적인 값을 줄 수는 없을 것이라고 생각합니다.하지만 가장 좋은 시나리오에서는 수식을 제공합니다. – g00dy

+0

안드로이드는 쉽게 사용할 수 있도록 여기에서 사용할 수있는'AyncTask'를 제공합니다. http://developer.android.com/reference/android/os/AsyncTask.html을 참조하십시오. – guptakvgaurav

답변

0

당신이 당신의 스레드가 종료 될 때 알고 싶다면, 당신은 그것에게 처리기를 통과하고 mainActivity에게 메시지를 보낼 수있을 때 스레드 종료 (예 : run 메소드의 끝에서)

시작하기 전에 얼마나 걸릴지 알고 싶다면 정확하게 할 수 있다고 생각하지 않습니다.