有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在应用程序第一次启动时运行特定代码?

我想在我的应用程序第一次启动时运行一些代码,它是将过去一周的SMS消息同步到我的web应用程序。我不确定如何在一周内过滤掉任何东西,但这是我获取所有短信的代码:

Uri allMessage = Uri.parse("content://sms/");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(allMessage, null, null, null, null);
while  (c.moveToNext()) {
   String row = c.getString(1);
   //upload the recent 1 week sms messages to the server's database
}

我只想运行这段代码一次,所以当它第一次打开时就可以了


共 (2) 个答案

  1. # 1 楼答案

    您还可以创建一个扩展Application的类。这将仅在应用程序启动时运行

  2. # 2 楼答案

    使用^{}。例如:

       SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
       boolean firstTime = settings.getBoolean("FirstTime", true);
       if (firstTime) {
           // execute your one time code...
           // change the value in the shared preferences:
           SharedPreferences.Editor editor = settings.edit();
           editor.putBoolean("FirstTime", false);
           editor.commit();
       }