Created
December 10, 2016 23:46
-
-
Save yerenutku/3abf5a32dbab972161198f1b1c7f48f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BroadcastWidget extends AppWidgetProvider { | |
private static final String ACTION_SIMPLEAPPWIDGET = "ACTION_BROADCASTWIDGETSAMPLE"; | |
private static int mCounter = 0; | |
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, | |
int appWidgetId) { | |
// Construct the RemoteViews object | |
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.broadcast_widget); | |
// Construct an Intent which is pointing this class. | |
Intent intent = new Intent(context, BroadcastWidget.class); | |
intent.setAction(ACTION_SIMPLEAPPWIDGET); | |
// And this time we are sending a broadcast with getBroadcast | |
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, | |
PendingIntent.FLAG_UPDATE_CURRENT); | |
views.setOnClickPendingIntent(R.id.tvWidget, pendingIntent); | |
// Instruct the widget manager to update the widget | |
appWidgetManager.updateAppWidget(appWidgetId, views); | |
} | |
@Override | |
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { | |
// There may be multiple widgets active, so update all of them | |
for (int appWidgetId : appWidgetIds) { | |
updateAppWidget(context, appWidgetManager, appWidgetId); | |
} | |
} | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
super.onReceive(context, intent); | |
if (ACTION_SIMPLEAPPWIDGET.equals(intent.getAction())) { | |
mCounter++; | |
// Construct the RemoteViews object | |
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.broadcast_widget); | |
views.setTextViewText(R.id.tvWidget, Integer.toString(mCounter)); | |
// This time we dont have widgetId. Reaching our widget with that way. | |
ComponentName appWidget = new ComponentName(context, BroadcastWidget.class); | |
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); | |
// Instruct the widget manager to update the widget | |
appWidgetManager.updateAppWidget(appWidget, views); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment