2010-05-12 78 views
2

我在自动启动后正确初始化我的应用程序时遇到问题。Android:自动启动应用程序和加载首选项

我设法让自动启动工作,重新启动后,应用程序显示为启动,但计时器不是。 我的猜测是,当我调用context.startService()时,不会调用MyApp的“onCreate”函数。定时器在MyApp的doActivity()函数中设置。

我将不胜感激关于我可能做错的任何提示或指向优秀教程的链接。 :)

清单

<activity android:name=".MyApp" 
       android:label="@string/app_name"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <receiver android:name="MyApp_Receiver"> 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
      <category android:name="android.intent.category.DEFAULT" /> 
     </intent-filter> 
    </receiver>[/syntax] 

MyApp_Receiver是具有以下两个功能

public void onReceive(Context context, Intent intent) { 
    // Do Autostart if intent is "BOOT_COMPLETED" 
    if ((intent.getAction() != null) && (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))) 
    { 
     // Start the service 
     context.startService(new Intent(context, MyApp.class)); 
    } 
    // Else do activity 
    else 
     MAIN_ACTIVITY.doActivity(); 
} 

public static void setMainActivity(MyApp activity) 
{ 
    MAIN_ACTIVITY = activity; 
} 

MyApp的延伸PreferenceActivity一个BoradcastReciever并且具有的onCreate()和一个doActivity (),doActivity()读出首选项并根据它们设置一个计时器。

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

    // Show preferences 
    addPreferencesFromResource(R.xml.preferences);; 

    // Register Preference Click Listeners 
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); 


    // Prepare for one-shot alarms 
    if (mIntent == null) 
    { 
     mIntent = new Intent(MyApp.this, MyApp_Receiver.class); 
     mSender = PendingIntent.getBroadcast(MyApp.this, 
       0, mIntent, 0); 
     MyApp_Receiver.setMainActivity(this); 
    } 

    // Refresh and set all timers on start 
    doActivity(); 
} 

回答

3

的定时器在doActivity()MyApp的的 功能设置。

这将永远不会工作。 MyApp是一个活动,在用户进入并启动它之前不会创建。

onReceive()中读取您的SharedPreferences并在此设置警报。

+0

谢谢!很高兴知道。 :) 试图实施它我已经到了下一个问题。我使用以下方法添加我的偏好: addPreferencesFromResource(R.xml.preferences); 我似乎无法得到他们的名字,所以在onRecieve()我可以阅读它们: context.getSharedPreferences(“prefs_myApp”,Context.MODE_PRIVATE); 我真的想从XML创建它们,而不是从代码创建它们...... – BBoom 2010-05-12 12:01:27

+2

使用'PreferenceManager.getDefaultSharedPreferences'。 – CommonsWare 2010-05-12 12:24:25

+0

真棒,谢谢!你摇滚。 :)现在完美工作。 (如果我有足够的声望,我会给你投票:P) – BBoom 2010-05-12 12:59:08

相关问题