【问题标题】:Android Widget with service (started using alarm) getting called frequently带有服务(使用警报开始)的 Android Widget 经常被调用
【发布时间】:2012-10-19 10:32:43
【问题描述】:

在一项要求中,我创建了一个应该每 5 分钟更新一次的小部件。我在互联网上发现,我应该使用 AlarmManager 来节省电池,而不是使用 java 线程。现在我正在使用 AlarmManager 进行操作。

我面临的问题是 Service 类的 onStart 方法被非常频繁地调用。一秒钟差不多10次。听说是我的两门课。

public class MyAppWidget extends AppWidgetProvider {

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {  
        intent = new Intent(context, UpdateWidgetService.class);
        context.startService(intent);
    }
}

服务类是

public class UpdateWidgetService extends Service {  

private Intent intent;

@Override
public void onStart(Intent intent, int startId) {
this.intent = intent;
System.out.println("This is getting printed 10 times in a second.");
final PendingIntent pending = PendingIntent.getService(getApplication(), 0, intent, 0);
AlarmManager alarm = (AlarmManager) getApplication().getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
long interval = 3000;
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),interval, pending);     

stopSelf();
super.onStart(intent, startId);
 } 
}

我还在 xml 文件中设置了属性以进行自动刷新,但它没有用。该应用程序未使用以下属性来刷新小部件。我还想知道如果应用程序使用了这个属性,会调用哪个方法。

android:updatePeriodMillis="1000"

【问题讨论】:

    标签: android android-widget android-alarms android-appwidget


    【解决方案1】:

    我建议你移动

    super.onStart(intent, startId);
    

    到方法的开头。用 stopSelf(); 停止服务后调用它是不对的;

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      相关资源
      最近更新 更多