将数据从BroadcastReceiver收集到csv

时间:2015-04-15 18:15:00

标签: java android

我正在尝试将电池信息记录到csv文件中,现在我只是在每次BroadcastReceiver收到意图后尝试记录。这是一个片段:

public class MainActivity extends Activity
    private static final String TAG = "MainActivity";
    double voltage;
    float temperature;
    int soc;
    Float current;

    CSVWriter writer = null;
    File dir = new File(Environment.getExternalStorageDirectory() + "/BatteryApp");
    FileWriter fw;
    File f;
    boolean fexists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.w(TAG, "App created");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

        if (!dir.exists())
        {
            dir.mkdirs();
        }

        int a = 1;
        fexists = true;
        while(fexists) {
            File newFilename = new File(dir + "/battery" + Integer.toString(a) + ".csv");
            if (newFilename.exists()) {
                a++;
            } else {
                f = newFilename;

                MediaScannerConnection.scanFile(MainActivity.this, new String[]{f.toString()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, Uri uri) {
                                Log.i("External Storage", "Scanned" + dir + ":");
                                Log.i("External Storage", "-> uri=" + uri);
                        }
                    });
                try {
                    writer = new CSVWriter(new FileWriter(f, true), ',');
                    String[] entries = "Voltage(V),Temperature(C),SOC(%),Current(Ah),".split(",");
                    writer.writeNext(entries);
                    writer.flush();
                    writer.close();

                }
                catch (IOException ioex) {
                    ioex.printStackTrace();
                }
                fexists = false;
            }
        }
    text = (TextView) findViewById(R.id.textView)
 }

 private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
         Log.w(TAG, "Broadcast Receiver received");
         //After receiving battery info from BatteryManager

         text.setText(
                voltage + " V\n"
                        + temperature + " C\n"
                        + current + " Ah\n"
                        + soc + " %\n");
         text.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.v(TAG, "Voltage(V): " + voltageText + " Temp(C): " + temperatureText + " SOC(%): " + socText + " Current(A): " + currentText );

                try
                {
                    writer = new CSVWriter(new FileWriter(f, true), ',');
                    String [] data = (voltageText + "," + temperatureText + "," + socText + "," + currentText + ",").split(",");
                    writer.writeNext(data);
                    writer.flush();
                    writer.close();
                    MediaScannerConnection.scanFile(MainActivity.this, new String[]{f.toString()}, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                public void onScanCompleted(String path, Uri uri) {
                                    Log.i("External Storage", "Scanned" + dir + ":");
                                    Log.i("External Storage", "-> uri=" + uri);
                                }
                            });
                }
                catch(IOException ioex)
                {
                    ioex.printStackTrace();
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void afterTextChanged(Editable s) {}
        });
    }

};

问题:如下面的logcat日志所示,在onReceive()的每次迭代之后,检索到的信息比以前显示的更多。此外,在拔出并插回USB之后,csv上的数据才会更新/无法看到。

D/OpenGLRenderer﹕ Enabling debug mode 0
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
W/MainActivity﹕ Broadcast Receiver received
V/MainActivity﹕ Voltage(V): 4.236 Temp(C): 33.0 SOC(%): 84 Current(A): 0.048
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
D/dalvikvm﹕ Debugger has detached; object registry had 1 entries
W/MainActivity﹕ Broadcast Receiver received
V/MainActivity﹕ Voltage(V): 4.248 Temp(C): 33.0 SOC(%): 84 Current(A): 0.054
V/MainActivity﹕ Voltage(V): 4.248 Temp(C): 33.0 SOC(%): 84 Current(A): 0.054
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
W/MainActivity﹕ Broadcast Receiver received
V/MainActivity﹕ Voltage(V): 4.249 Temp(C): 33.0 SOC(%): 84 Current(A): 0.08
V/MainActivity﹕ Voltage(V): 4.249 Temp(C): 33.0 SOC(%): 84 Current(A): 0.08
V/MainActivity﹕ Voltage(V): 4.249 Temp(C): 33.0 SOC(%): 84 Current(A): 0.08
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
W/MainActivity﹕ Broadcast Receiver received
V/MainActivity﹕ Voltage(V): 4.247 Temp(C): 33.0 SOC(%): 85 Current(A): 0.029
V/MainActivity﹕ Voltage(V): 4.247 Temp(C): 33.0 SOC(%): 85 Current(A): 0.029
V/MainActivity﹕ Voltage(V): 4.247 Temp(C): 33.0 SOC(%): 85 Current(A): 0.029
V/MainActivity﹕ Voltage(V): 4.247 Temp(C): 33.0 SOC(%): 85 Current(A): 0.029
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550
I/External Storage﹕ Scanned/storage/emulated/0/BatteryApp:
I/External Storage﹕ -> uri=content://media/external/file/550

任何关于为什么会发生这种情况的想法以及解决方案(如果有的话)都将非常感激。

1 个答案:

答案 0 :(得分:1)

从您的代码中可以清楚地看出来。消息正在TextWatcher侦听器中记录,每次调用onReceive方法时,都会附加另一个侦听器。每次收到广播时都不应该重新创建监听器,而应该只创建一次。

此外,似乎直接生成响应广播的日志消息要简单得多,而不是更新UI元素然后触发另一个事件来响应。