什么可能导致Android活动无限循环?

时间:2014-01-05 20:26:58

标签: java android infinite-loop

我正在编写一个简单的应用程序来扫描和记录WiFi接入点,有三种选择;一次扫描,10次扫描或扫描一段时间。

当我进入我的nWiFiScans活动时,它会执行扫描,记录文件并重新开始活动!

为什么要这样做?

nWiFiScans.java

    public class nWiFiScans extends Activity 
    {
    //declarations
    public static String pntNameStr;
    public static int numScans;
    public static int scansMin;
    LinearLayout    layout1;
    ScrollView      scrollLayout;
    TextView        label1; 
    EditText        n1Text;
    EditText        n2Text;
    LayoutParams    params_layout1;

    WifiManager mainWifi = null;
    WifiReceiver receiverWifi;
    List<ScanResult> wifiList;
    StringBuilder sb = new StringBuilder();
    Intent intent;
    SimpleDateFormat time;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        scrollLayout = new ScrollView(this);
        scrollLayout.setBackgroundColor(Color.BLUE);
        //Create new layout in "this" activity
        params_layout1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT, 1);
        layout1 = new LinearLayout(this);
        layout1.setBackgroundColor(Color.RED);
        layout1.setLayoutParams(params_layout1);
        //Create TextView in "this" activity
        label1 = new TextView(this);
        label1.setBackgroundColor(Color.YELLOW);
        //Put some text in the TextView

        // Get the message from the intent
        intent = getIntent();
        pntNameStr = intent.getStringExtra(MainActivity.EXTRA_pntNameStr);
        numScans = intent.getIntExtra(MainActivity.EXTRA_numScans, 1);

        label1.setText(pntNameStr);


        //Place the TextView inside the Layout
        layout1.addView(label1);
        layout1.setOrientation(LinearLayout.VERTICAL);
        //scrollLayout.addView(label1);
        //layout1.addView(n1Text);
        //layout1.addView(n2Text);

        //By default the layout is set to HOR, so we change it to VERT orientation:

        // Display layout1 when the activity is created:
        setContentView(layout1);

        mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        checkIfWifiIsOn(mainWifi);

        receiverWifi = new WifiReceiver();
        registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        mainWifi.startScan();
        label1.setText("Starting Scan..."+String.valueOf(numScans));


    }

    public void checkIfWifiIsOn(WifiManager mainWifi)
    { 
        if (mainWifi.isWifiEnabled() == false)
        {  
            // If wifi disabled then enable it
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",
                    Toast.LENGTH_LONG).show();

            mainWifi.setWifiEnabled(true);
        } 
        else {Toast.makeText(getApplicationContext(), "wifi is enabled... thats good...",
                Toast.LENGTH_SHORT).show();}
    }

    public void generateNoteOnSD(String sFileName, String sBody)
    {
        File root = null;
        try
        {
            root = new File(Environment.getExternalStoragePublicDirectory("SurveyAppData"), "ScanResults");
            if (!root.exists()) 
            {
                root.mkdirs();
            }
            File gpxfile = new File(root, sFileName);
            FileWriter writer = new FileWriter(gpxfile);
            writer.append(sBody);
            writer.flush();
            writer.close();
            Toast.makeText(this, "Saved" + "/n" +root.toURI(), Toast.LENGTH_LONG).show();


            Toast.makeText(getApplicationContext(), "IM MOTHERFUCKING DONE" ,
                    Toast.LENGTH_SHORT).show();
            //Log.d("Scan Results",sb.toString());
            Intent i=new Intent(nWiFiScans.this, MainActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            finish();

        }
        catch(IOException e)
        {
            e.printStackTrace();
            Toast.makeText(this, "!!! - Could NOT Saved" + "/n" +root.toURI(), Toast.LENGTH_LONG).show();

        }
    }  


    public class WifiReceiver  extends BroadcastReceiver
    {
        // This method call when number of wifi connections changed
        long fisrtScanTS;
        private String FILENAME = pntNameStr;
        public FileOutputStream outputStream;

        @SuppressLint("NewApi")
        public void onReceive(Context c, Intent intent) 
        {
            time = new SimpleDateFormat("ddMMyyyyhhmmss");
            int ScanTime = numScans;
            if(ScanTime==1 | ScanTime==10)
            {

                for (int scanNum = 1; scanNum<ScanTime+1; scanNum++)
                {
                    wifiList = mainWifi.getScanResults();
                    for(int i = 0; i < wifiList.size(); i++)
                    {               
                        sb.append(((wifiList.get(i)).BSSID + " " +  (wifiList.get(i)).level + " "  + (wifiList.get(i)).frequency + " "+ (wifiList.get(i)).timestamp + " "+ (wifiList.get(i)).SSID +" "+ time.format(new Date()) + "\n" ) );
                        fisrtScanTS = (wifiList.get(1)).timestamp;
                    } 

                    do
                    {
                        mainWifi.startScan();
                        wifiList = mainWifi.getScanResults();
                        try{Thread.currentThread().sleep(200);}
                        catch(InterruptedException ie){
                            //If this thread was intrrupted by nother thread 
                        }
                    } while(fisrtScanTS == (wifiList.get(1)).timestamp);

                    Toast.makeText(getApplicationContext(), "Scan number " + scanNum ,
                            Toast.LENGTH_SHORT).show();
                }
            }else if (ScanTime!=0)
            {
                Calendar timeNow = Calendar.getInstance();
                Calendar timeEnd = Calendar.getInstance();
                timeEnd.set(timeNow.YEAR, timeNow.MONTH, timeNow.DAY_OF_MONTH, timeNow.HOUR, timeNow.MINUTE+numScans, timeNow.SECOND);
                while(!(timeNow.after(timeEnd))){
                    wifiList = mainWifi.getScanResults();
                    for(int i = 0; i < wifiList.size(); i++){               
                        sb.append(((wifiList.get(i)).BSSID + " " +  (wifiList.get(i)).level + " "  + (wifiList.get(i)).frequency + " "+ (wifiList.get(i)).timestamp + " "+ (wifiList.get(i)).SSID +" "+ time.format(new Date()) + "\n" ) );
                        fisrtScanTS = (wifiList.get(1)).timestamp;
                    }       
                    do {
                        mainWifi.startScan();
                        wifiList = mainWifi.getScanResults();
                        try{Thread.currentThread().sleep(200);}
                        catch(InterruptedException ie){
                            //If this thread was intrrupted by nother thread 
                        }} while(fisrtScanTS == (wifiList.get(1)).timestamp);

                    timeNow = Calendar.getInstance();
                    Toast.makeText(getApplicationContext(), timeNow.getTime().toString() + " :: " + timeEnd.getTime().toString() ,
                            Toast.LENGTH_SHORT).show();
                }

            }

            generateNoteOnSD(FILENAME, sb.toString());
            FILENAME="x";
            ScanTime=0;
        }

    }   
}

MainActivity.java

  public class MainActivity extends Activity 
    {
    LinearLayout mainLayout,leftLayout,rightLayout;
    EditText pointName;
    EditText scanTime;
    Button scan10, scan1, timedScan;
    TextView msg;
    LayoutParams paramsL,paramsR;
    static final String EXTRA_pntNameStr = "com.example.surveyappv2.pntNameStr";
    static final String EXTRA_scanTimeMin = "com.example.surveyappv2.scanTimeMin";
    static final String EXTRA_numScans = "com.example.surveyappv2.numScans";

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.HORIZONTAL);

        paramsL = new LayoutParams(500,LayoutParams.MATCH_PARENT, 1);
        paramsR = new LayoutParams(500,LayoutParams.MATCH_PARENT, 1);

        leftLayout = new LinearLayout(this);
        leftLayout.setOrientation(LinearLayout.VERTICAL);
        leftLayout.setLayoutParams(paramsL);
        leftLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        leftLayout.setBackgroundColor(Color.YELLOW);

        rightLayout = new LinearLayout(this);
        rightLayout.setOrientation(LinearLayout.VERTICAL);
        rightLayout.setLayoutParams(paramsR);
        rightLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        rightLayout.setBackgroundColor(Color.BLUE);

        scanTime = new EditText(this);
        scanTime.setHint("Scan Duration (min)");
        scanTime.setInputType(InputType.TYPE_CLASS_NUMBER);     
        pointName = new EditText(this);
        pointName.setHint("Enter Point Name");
        scan10 = new Button(this);
        scan1 = new Button(this);
        timedScan = new Button(this);
        msg = new TextView(this);

        scan10.setText("Do 10 Scans");
        scan1.setText("Do a Single Scan");
        timedScan.setText("Timed Scan");
        msg.setText("Alec Sucks");


        leftLayout.addView(pointName);
        leftLayout.addView(scanTime);
        rightLayout.addView(msg);
        rightLayout.addView(scan10);
        rightLayout.addView(scan1);
        rightLayout.addView(timedScan);

        mainLayout.addView(leftLayout);
        mainLayout.addView(rightLayout);
        mainLayout.setBackgroundColor(Color.RED);
        setContentView(mainLayout);
        setButtonClickListener();

    }

    private void setButtonClickListener()
    {
        scan10.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v) 
            {
                String message2 = "Button: \n" + scan10.getText();
                msg.setText(message2);
                startScan(mainLayout,10);

            }
        });

        scan1.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v) 
            {
                String message2 = "Button: \n" + scan1.toString();
                msg.setText(message2);
                startScan(mainLayout,1);
            }
        });

        timedScan.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
                String message2 = "Button: \n" + timedScan.toString();
                msg.setText(message2);
                startScan(mainLayout,Integer.parseInt(scanTime.getText().toString()));
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void startScan(View view, int numScans)
    {
        Intent intent = new Intent(this, nWiFiScans.class);
        String pntNameStr = pointName.getText().toString();
        intent.putExtra(EXTRA_pntNameStr, pntNameStr);
        intent.putExtra(EXTRA_numScans, numScans);
        startActivity(intent);
    }
}

1 个答案:

答案 0 :(得分:2)

我运行它,删除了文件创建和Intent(你只需要调用finish();)然后它就可以了。你有没有检查过它是否真的为你创建了文件?因为我的卡住了然后它跳出了尝试所以它无法到达终点();电话,我也在unregisterReceiver(receiverWifi);

之前致电finish();

编辑,文件创建:

    File sdCard = Environment.getExternalStorageDirectory(); //returns sdcard directory
    File dir = new File (sdCard.getAbsolutePath() + "/mydirectory");
    dir.mkdirs();
    File file = new File(dir, "filename");