-1

在 android 应用程序中存储数组 { devicename, macaddress, updated } 然后在用户关闭应用程序后处理数据的最佳方法是什么。

更新:通过存储,我的意思是使用 SQLite、内部存储(创建文件然后删除)等。是否有任何最佳实践来做到这一点,询问的原因是因为我需要访问数据而不是每次调用 API。

我只是问,因为我是 Android 开发的新手。

4

1 回答 1

1

Array 或 Map 之类的对象的私有实例似乎正是您所需要的。根据您的问题和上面的评论,我认为没有理由涉及非易失性存储或花哨的 Map 对象。

从android developer docs中借用一点,并假设您正在应用程序中实现一个 Activity,您的代码可能如下所示:

...

import java.util.HashMap;
import java.util.Map;

....

public class ExampleActivity extends Activity {

    public static final String TAG = "ExampleActivity";

    // create an enum to hold your key values (plain old strings could work too)
    private enum ApiKey {
        NAME, MAC, UPDATED
    };

    //declare your data structure
    private Map<ApiKey, String> myCachedApiData;   

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.

        // initialize your data in onCreate()
        myCachedApiData = new HashMap<ApiKey, String>();

        // retrieve initial data from your API
        // you may want to do this on another thread if it takes a while

        ...

        // put data in your map
        myCachedApiData.put( ApiKey.NAME, deviceNameStr );
        myCachedApiData.put( ApiKey.MAC, macAddressStr );
        myCachedApiData.put( ApiKey.UPDATED, updatedStr );
    }
    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible, lets
        // print out (access) some of our cached API data
        // each time the user views our Activity

        Log.d( TAG, "MAC addr is: " + myCachedApiData.get( ApiKey.MAC ) );

    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.

        // No need to explicitly clear our map, it will be removed when our
        // Activity is destroyed

        // myCachedApiData.clear();
    }
}
于 2014-08-05T14:02:01.827 回答