结果在文件中写入多个时间

时间:2015-12-06 01:20:10

标签: java android

这是我用来写入文件的方法。我试图将结果写入ExternalStorage中的文件。我能够写出结果但是它被写了多次。我想在活动保持活动状态时调用writeToFile()方法。我不知道如何纠正它。

try {
    File file;
    file = new File(Environment.getExternalStorageDirectory(), "UpdatedContactDetails.txt");
    FileOutputStream fos = new FileOutputStream(file, true);
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
    outputStreamWriter.append("ContactName: " + updatedContactName + "  updatedTime: "+ updatedDateStr +" " + updatedTimeStr);
    outputStreamWriter.close();
}
catch(Exception e)
{
    System.out.println(e.getMessage());
}

以下是onCreate方法。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_observer);
        ContactObserver co = new ContactObserver(new Handler());
        //CONTENT_URI is the sensor's or plugin's table URI you are interested in
        getContentResolver().registerContentObserver(ContactsContract.Data.CONTENT_URI, true,co);

    }

下面是我调用writeToFile()方法的方法。

public class ContactObserver extends ContentObserver
    {

        public ContactObserver(Handler handler) {
            super(handler);
        }

        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            contactChange = true;
            String[] mProjection = {
                    ContactsContract.Data.CONTACT_LAST_UPDATED_TIMESTAMP,
                    ContactsContract.Data.DISPLAY_NAME_ALTERNATIVE,
                    ContactsContract.Data.LAST_TIME_USED

            };
            Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, mProjection, null, null, ContactsContract.Data.CONTACT_LAST_UPDATED_TIMESTAMP + " DESC LIMIT 1");
            if (c != null && c.moveToFirst()) {
                lastUpdatedtimeStamp = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_LAST_UPDATED_TIMESTAMP));
                updatedContactName = c.getString(c.getColumnIndex(ContactsContract.Data.DISPLAY_NAME_ALTERNATIVE));
                System.out.println("last updated" + "Contact Name: " + updatedContactName + "\nUpdated time :" + lastUpdatedtimeStamp
                        + "\nLastTimeUsed" + usageTimeStamp);
                c.close();
            }
            boolean conversionSuccess = getHumanReadableDateTime(lastUpdatedtimeStamp, usageTimeStamp);
            if (conversionSuccess)
            {
                try {
                    writeUpdateDetailsToFile();
                    } catch (FileNotFoundException fe) {
                    System.out.println("FILE WRITE EXCEPTION" + fe.getMessage());
                }
            }
        } 

0 个答案:

没有答案