【问题标题】:Android Widget that can start/stop a service and receive updates every second可以启动/停止服务并每秒接收更新的 Android 小部件
【发布时间】:2013-02-15 10:14:12
【问题描述】:

我需要创建一个基本上只有一个开始/停止按钮和一个包含一些信息的字段的 Android 小部件。 Start 按钮应该启动一个服务,该服务每隔一秒左右就会得到一个结果。此结果的一部分应显示在 Widget 中,并且可以通过按下停止按钮再次停止服务。

谁能指出我正确的方向来实现这一点?

我现在读了很多书,但我真的不确定。据我了解,AlarmManager 会过度杀伤力,并且会非常快地耗尽电池或使手机无响应。我也不能使用广播接收器,因为服务需要超过 5 秒(??不确定)。

感谢任何帮助!

【问题讨论】:

    标签: android android-widget broadcastreceiver alarmmanager android-sensors


    【解决方案1】:

    首先,建议在从小部件创建服务时,在进行必要的更改后立即停止它,因为正在运行的服务会消耗电池和内存。

    对于制作小部件,这会有所帮助:-

    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        // TODO Auto-generated method stub
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        for (int i = 0; i < appWidgetIds.length; i++) {
            int appWidgetId = appWidgetIds[i];
            //Give the name of service you want to start in your case Alarm Service
            Intent intent = new Intent(context, WidgetService.class);
            PendingIntent pendingIntent = PendingIntent.getService(context, 0,
                    intent, 0);
            //This basically sets the layout of your widget to widget_layout
            RemoteViews views = new RemoteViews(context.getPackageName(),
                    R.layout.widget_layout);
            views.setOnClickPendingIntent(R.id.imageView1, pendingIntent);
    
            appWidgetManager.updateAppWidget(appWidgetId, views);
    
        }
    

    对于您的服务类,您可以在进行所需更改后在 OnStart() 方法中使用 stopSelf()。

    【讨论】:

      猜你喜欢
      • 2013-07-05
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多