我是android的新手。我正在开发android中的警报应用程序。我已经做了以下的代码,这将工作时,设备是打开,但在设备重新启动,它将不工作,我。我将该警报存储在共享首选项中,并从中检索。当设备重新启动时,我重新安排从OnBootReceiver发出的警报。我已经提到了对Android声明的权限,为了测试目的,我采用了硬编码的值。请检查以下代码,并帮助我研究它从一天和半天。任何人都有想法。谢谢。
公共类FirstActivity扩展活动实现OnClickListener{
int mHour = 14;
int mMinute = 48;
static String prefkey="SHARED_KEY";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences =getSharedPreferences(prefkey,Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("min",mMinute);
editor.putInt("hour",mHour);
editor.commit();
}
}公共类OnBootReciever扩展BroadcastReceiver {
int sethour,setmin;
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "booting....", Toast.LENGTH_LONG).show();
SharedPreferences preferences=context.getSharedPreferences(FirstActivity.prefkey,Context.MODE_PRIVATE);
sethour=preferences.getInt("hour",14);
setmin=preferences.getInt("min",48);
Calendar cal=Calendar.getInstance();
cal.add(Calendar.MINUTE,setmin);
cal.add(Calendar.HOUR_OF_DAY,sethour);
cal.add(Calendar.SECOND,0);
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context,RepeatingAlarm.class);
PendingIntent sender1 = PendingIntent.getBroadcast(context,0, i,PendingIntent.FLAG_UPDATE_CURRENT);
mgr.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),AlarmManager.INTERVAL_FIFTEEN_MINUTES,sender1);
}}
公共类RepeatingAlarm扩展BroadcastReceiver {
static MediaPlayer mMediaPlayer ;
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Trigger the alarm", Toast.LENGTH_LONG).show();
mMediaPlayer = new MediaPlayer();
mMediaPlayer.create(getcontext,R.raw.warm).start();
}}
在AndroidManifest.xml-->中
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="com.vidushi.alarmsystem.RepeatingAlarm"></receiver>
<receiver android:name=".OnBootReciever" android:process=":remote">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>发布于 2011-11-09 12:23:53
当android调用您的OnBootReceiver类时,可能会传递它自己的上下文,而不是来自应用程序的上下文。所以它找不到共享的首选项,因为android没有它们。尝试使用您自己的上下文,而不是使用onReceive方法中的上下文。您可以使用这样的Application创建context类,并在应用程序启动时初始化它:
进口android.content.Context;
public class Application extends android.app.Application {
private static Context context;
public void onCreate(){
context=getApplicationContext();
}
public static Context getContext() {
return context;
}
}您还需要在AndroidManifest.xml中为标记添加以下属性:
android:name=".Application"链接
然后使用Application获取共享首选项:
Context context = Application.getContext();
SharedPreferences preferences=context.getSharedPreferences(FirstActivity.prefkey,Context.MODE_PRIVATE);发布于 2012-07-17 20:40:47
你的应用程序是否安装在sd卡上?如果是的话,它就不会收到‘引导完成’的通知。
请参阅App安装位置
https://stackoverflow.com/questions/8063144
复制相似问题