public class SkWidgetService extends Service {
private Context mContext;
private AppWidgetManager mAppWidgetManager;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("SK", "Service");
mContext = getApplicationContext();
mAppWidgetManager = AppWidgetManager.getInstance(mContext);
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
for (int widgetId : appWidgetIds) {
Log.i("SK", "Service - " + widgetId);
update(widgetId);
}
return super.onStartCommand(intent, flags, startId);
}
private void update(final int widgetId) {
RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(),
R.layout.widget_layout);
remoteViews.setTextViewText("test");
mAppWidgetManager.updateAppWidget(widgetId, remoteViews);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("SK", "Run - " + widgetId);
updateWidgetView(widgetId);
}
}, 1000);
}
private void updateWidgetView(int widgetId) {
RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(),
R.layout.widget_layout);
remoteViews.setTextViewText("test run");
// Register an onClickListener
Intent clickIntent = new Intent(mContext, SkWidgetProvider.class);
int[] widgetIds = {widgetId};
for (int ids : widgetIds) {
Log.i("SK", "Set new - " + ids);
}
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
mContext, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT
);
remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
mAppWidgetManager.updateAppWidget(widgetId, remoteViews);
stopSelf();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}