android中线程的生命周期

时间:2013-12-11 12:57:06

标签: java android multithreading thread-safety android-lifecycle

我有一个线程,当按下按钮时启动,Thread包含广播监听器和与wifi Direct相关的操作,最后它将android设备与搜索到的对等体连接,我想知道我的线程将花多少时间活??我的线程类是:

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); 
         }

}

1 个答案:

答案 0 :(得分:0)

如果你需要知道你的线程何时结束,你可以传递一个处理程序,并在线程结束时向你的mainActivity发送一条消息(即:在run方法结束时)

如果你想知道在开始它之前需要多长时间,我认为你不能准确地做到这一点。