2012-09-30 67 views
1

我正在使用一些闹钟功能每5秒钟产生一次通知。在函数中,每次调用它时都会有变化。但没有任何事情发生,它只是继续显示通知中的第一组数据。 这是从MainActivity类别:通知中未更新的Android变量

public void setRepeatingAlarm(){ 
    Intent intent = new Intent(this, TimeAlarm.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT); 
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (5 * 1000), pendingIntent);  
} 

这是从TimeAlarm类:

public void onReceive(Context context, Intent intent) { 

    nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
    CharSequence from = "Homework"; 
    CharSequence message = "test"+ MainActivity.arraytest[x2]+ x2; 
    x2 +=1; 
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(context,TimeAlarm.class), 0); 
    Notification notif = new Notification(R.drawable.ic_launcher,"Update", System.currentTimeMillis()); 
    notif.setLatestEventInfo(context, from, message, contentIntent); 
    nm.notify(notify_id, notif); 
} 

的问题是,在X2变量没有更新。它只在第一次调用时才会更新。 谢谢。

+1

我不知道你为什么每隔5秒使用通知,但这是一个糟糕的设计选择。我会亲自卸载每隔5秒发送一次通知的应用程序。 –

+0

它只是用于测试 –

+1

其中是变量x2宣布?我猜这是TimeAlarm的私人领域?如果是这样,它将在每次闹铃中重新初始化。在这种情况下,使其静态。否则发布所有/更多的TimeAlarm类 –

回答

1

使x2变量静态似乎解决了这个问题。

0

也许远射,但...我怀疑x2可能被多个线程访问?在这种情况下,应该声明为volatile,以便编译器跳过不适合多线程访问的变量的任何优化(在此情况下可能导致错误行为)。

+0

我试着做你说的,但没有任何区别。 –

0

你还在做其他什么x2?查看BroadcastReciever.的生命周期文档可能在onReceive()的每次运行后,您的TimeAlarm实例可能会死亡;你需要做一些事情来坚持运行之间的价值x2

+0

我没有用x2做其他任何事情 –

+1

难道这与“arraytest”是静态的吗? –

+0

每次'onRecieve()'完成运行,Android都会杀死该类的实例。您需要以某种方式(例如对于平面文件或数据库)持久保存'x2'的值,然后在'onRecieve()'的每次运行中重新加载它。 – jbowes