I want 2 separate layouts for homescreen and lockscreen.
I have read https://developer.android.com/guide/topics/appwidgets/index.html#lockscreen
But it is unclear where to implement this and how to change the layout at runtime for both homescreen and lockscreen?
I would be grateful if there is clear tutorial / example to do this.
Thanks
If you know home screen widget implementation, it's easy.
From the code below you can figure out how to use different layout for lock screen and home screen to display the current time every second.
Create different layout for different widgets
#layout/widget_keyguard //For lock screen widget
#layout/widget_home //For home screen widget
Note: Use one TextView with id time_view on both the layouts to display the time
xml/widget_info.xml
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialKeyguardLayout="#layout/widget_keyguard" // layout for lock screen
android:initialLayout="#layout/widget_home" // layout for lock screen (if not provided) & home screen
android:minHeight="100dp"
android:minWidth="300dp"
android:previewImage="#drawable/ic_launcher"
android:resizeMode="none"
android:updatePeriodMillis="180000"
android:widgetCategory="keyguard|home_screen" > //Enable widgets on both home screen and lock screen
</appwidget-provider>
AppWidgetProvider.java
public class TestAppWidgetProvider extends AppWidgetProvider {
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}
#Override
public void onDisabled(Context context) {
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
am.cancel(sender); //When all the widgets are disabled, do not forget to cancel the service
super.onDisabled(context);
}
#Override
public void onEnabled(Context context) {
super.onEnabled(context);
Toast.makeText(context, "Widget Enabled", Toast.LENGTH_SHORT).show();
//AlarmManager to update the widgets
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent p_intent = PendingIntent.getBroadcast(context, 0, intent,
0);
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// Here I am updating the widgets every second (1000 ms) , you can use however you want
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1000, p_intent);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Toast.makeText(context, "Widget Updated", Toast.LENGTH_SHORT).show();
ComponentName thisWidget = new ComponentName(context,
TestAppWidgetProvider.class);
for (int widgetId : appWidgetManager.getAppWidgetIds(thisWidget)) {
Bundle myOptions = appWidgetManager.getAppWidgetOptions(widgetId);
int category = myOptions.getInt(
AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY, -1);
RemoteViews remoteViews;
if (category == AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD) {
// Get the remote views
remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_keyguard);
}
else {
remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_home);
}
SimpleDateFormat dateFormat = new SimpleDateFormat(
"HH:mm:ss", Locale.US);
// use TextView with time_view id on both home screen & lock screen layouts
remoteViews.setTextViewText(R.id.time_view,
dateFormat.format(new Date(System.currentTimeMillis())));
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
#Override
public void onAppWidgetOptionsChanged(Context context,
AppWidgetManager appWidgetManager, int appWidgetId,
Bundle newOptions) {
}
}
AlarmManagerBroadcastReceiver class
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
ComponentName thiswidget = new ComponentName(context,
TestAppWidgetProvider.class);
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
for (int widgetId : appWidgetManager.getAppWidgetIds(thiswidget)) {
Bundle myOptions = appWidgetManager.getAppWidgetOptions(widgetId);
int category = myOptions.getInt(
AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY, -1);
RemoteViews remoteViews;
if (category == AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD) {
// Get the remote views
Log.d("Widget", "Lockscreen widget");
remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_keyguard);
}
else {
Log.d("Widget", "Homescreen widget");
remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_home);
}
SimpleDateFormat dateFormat = new SimpleDateFormat(
"HH:mm:ss", Locale.US);
// use TextView with time_view id on both home screen & lock screen layouts
remoteViews.setTextViewText(R.id.time_view,
dateFormat.format(new Date(System.currentTimeMillis())));
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
}
Finally, do not forget to update the manifest file
<application
...
<receiver android:name=".AlarmManagerBroadcastReceiver" />
<receiver android:name=".TestAppWidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info" />
</receiver>
.....
</application>
that's it.
I hope it'll help you to solve your problem
Related
I have no idea why this is happening. I'm making widgets which show the best currency rate for the currencies that the user chooses. I've noticed after a reboot, they sometimes turn into a clock and a calendar widget. Here's my code. I assume it could be something with my Intents or OnReceive() but I'm not sure what.
public class LightRowWidget extends RowWidget {
List<CurrencyObject> currencyObjects = new ArrayList<>();
public LightRowWidget() {
super(R.layout.widget_row_layout, R.color.white, Constants.FULL_OPACITY, R.color.black);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
if (appWidgetIds != null && appWidgetIds.length > 0) {
for (int appWidgetId : appWidgetIds) {
// Create currencyObjects. They're used to assign the correct value
// to the correct texView
CurrencyObject currObj1 = new CurrencyObject(
R.id.currency1, R.id.currency1_buy, R.id.currency1_sell);
currencyObjects.add(currObj1);
CurrencyObject currObj2 = new CurrencyObject(R.id.currency2, R.id.currency2_buy, R.id.currency2_sell);
currencyObjects.add(currObj2);
// Register an onClickListener to Update the current widget on a click
Intent clickIntent = new Intent(context, LightRowWidget.class);
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
onUpdate(context, appWidgetManager, appWidgetId, currencyObjects, clickIntent);
}
//start an intent that will schedule the alarm for the next update
Intent startIntent = new Intent(context, LightRowWidget.class);
scheduleNextUpdate(context, startIntent, appWidgetIds);
}
and Here is my RowWidget class with the relevant code.
public abstract class RowWidget extends AppWidgetProvider implements WidgetInterface{
public RowWidget(int layout, int background_color, int background_opacity, int text_color){
super();
this.layout = layout;
this.background_color=background_color;
this.background_opacity=background_opacity;
this.text_color=text_color;
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetId, List<CurrencyObject> currencyObjects, Intent clickIntent) {
theAppWidgetManager = appWidgetManager;
//Get the current name of class
String currentClass = this.getClass().getName();
switch(currentClass){
case("foobar"):
configure_class=Constants.FOUR_ROW_CONFIGURE;
break;
case("foo"):
configure_class=Constants.ROW_APP_WIDGET_LIGHT_CONFIGURE;
break;
case("bar"):
configure_class=Constants.ROW_APP_WIDGET_DARK_CONFIGURE;
break;
case("barfoo"):
configure_class=Constants.TWO_ROW_CONFIGURE;
break;
}
// There may be multiple widgets active, so update all of them
// Get the preferred Currencies
Set<String> preferredCurrencies = AppWidgetConfigure.loadCurrencyPref(context,appWidgetId, configure_class);
// Inflate the layout
RemoteViews view = new RemoteViews(context.getPackageName(), layout);
// if the preferred Currencies have been declared already
if(preferredCurrencies!= null){
// Set the currencies for each object
for(String currency: preferredCurrencies){
if(currencyCount<currencyObjects.size()){
currencyObjects.get(currencyCount).setCurrencyType(currency);
currencyCount+=1;
}
}
}
else{
for(CurrencyObject curObj:currencyObjects){
curObj.setCurrencyType("RUB");
}
}
// Open up the Currency fragment on the click of the widget
Intent configIntent = new Intent(context, MainActivity.class);
configIntent.putExtra("LaunchCurrency", true);
configIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
view.setOnClickPendingIntent(R.id.row_widget_layout, configPendingIntent);
// Update the widget whenever refresh button clicked
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.refresh, pendingIntent);
makeRequest(context, theDate, view, currencyObjects, appWidgetId);
currencyCount = 0;
}
//Handle receiving the intent
#Override
public void onReceive(Context context, Intent intent){
if (intent.getAction().equals(ACTION_APPWIDGET_UPDATE)) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// Get id's
int[] allWidgetIds = intent
.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
onUpdate(context, manager, allWidgetIds);
}
else{
super.onReceive(context, intent);
}
}
EDIT: Widgets transform to a lot of different widgets that are already on my screen.
I have created everything necessary for my widget to exist and function. Even so at the first click, t does what it is supposed to but then image gets changed and says problem, and does not function. I want it to open flash and then close it.
Help will be much appreciated.
FlashlightWidgetProvider
public class FlashlightWidgetProvider extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Intent receiver = new Intent(context, FlashlightWidgetReceiver.class);
receiver.setAction("COM_FLASHLIGHT");
receiver.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, receiver, 0);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.flash_widget);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, views);
}
}
FlashlightWidgetReceiver
public class FlashlightWidgetReceiver extends BroadcastReceiver {
private static boolean isLightOn = false;
private static Camera camera;
#Override
public void onReceive(Context context, Intent intent) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.flash_widget);
if(isLightOn) {
views.setImageViewResource(R.id.button, R.drawable.off);
} else {
views.setImageViewResource(R.id.button, R.drawable.on);
}
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(new ComponentName(context, FlashlightWidgetProvider.class),
views);
if (isLightOn) {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
isLightOn = false;
}
} else {
// Open the default i.e. the first rear facing camera.
camera = Camera.open();
if(camera == null) {
Toast.makeText(context, R.string.no_camera, Toast.LENGTH_SHORT).show();
} else {
// Set the torch flash mode
Parameters param = camera.getParameters();
param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
try {
camera.setParameters(param);
camera.startPreview();
isLightOn = true;
} catch (Exception e) {
Toast.makeText(context, R.string.no_flash, Toast.LENGTH_SHORT).show();
}
}
}
}
}
Make sure the button resource refers to an ImageView and not a regular Button. I just tried this out at first with a Button in my layout file and I was getting the same problem where the widget would basically crash and remove itself from the home screen. When I changed button to be an ImageView in the layout file, the code now works.
I did modify the code a bit from yours, so in case that doesn't work by itself, here is the updated FlashlightWidgetProvider:
public class FlashlightWidgetProvider extends AppWidgetProvider {
#Override
public void onReceive(Context context, Intent intent) {
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(intent.getAction())) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, getClass()));
Intent broadcastIntent = new Intent(context, FlashlightWidgetReceiver.class);
broadcastIntent.setAction("COM_FLASHLIGHT");
broadcastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0,
broadcastIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.flashlight);
views.setOnClickPendingIntent(R.id.flashButton, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, views);
}
super.onReceive(context, intent);
}
}
Also, make sure to register the widget provider and receiver correctly in the manifest (replacing the relevant pieces with your own, of course):
<receiver
android:name="com.example.stackoverflowtester.widget.FlashlightWidgetProvider"
android:label="Flashlight" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/flashlight_widget_provider" />
</receiver>
<receiver android:name="com.example.stackoverflowtester.widget.FlashlightWidgetReceiver" >
<intent-filter>
<action android:name="COM_FLASHLIGHT" />
</intent-filter>
</receiver>
I've read a lot of Q&As but I couldn't find my answer.
May be something in my implementation is wrong.
The problem is that my TextView in the widget doesn't get updated.
The logic is this:
1.setOnClickPendingIntent on a specific button in the onUpdate()
2.clicking on this button will broadcast an intent with a declared action
3.at last i'll update the text of the textView in the onRecieve()
Widget2.class :
public class Widget2 extends AppWidgetProvider {
private static final String SCROLL_LEFT = "widget2.SCROLL_LEFT";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i = 0; i < appWidgetIds.length; i++) {
int appWidgetId = appWidgetIds[i];
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.small);
Intent scrollLeft = new Intent(Widget2.SCROLL_LEFT);
PendingIntent leftScrollPendingIntent = PendingIntent.getBroadcast(context,
appWidgetId, scrollLeft, appWidgetId);
remoteViews.setOnClickPendingIntent(R.id.left_scroller, leftScrollPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
}
#Override
public void onReceive(Context context, Intent intent) {
Log.e(getClass().getSimpleName(), "onReceive()");
int appWidgetId = intent.getFlags();
if (intent.getAction().equals(SCROLL_LEFT)) {
updateCurrentWidget(context, appWidgetId);
Log.i("onReceive", SCROLL_LEFT + " appWidgetId = " + appWidgetId);
}
super.onReceive(context,intent);
}
private void updateCurrentWidget(Context context, int appWidgetId) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.small);
remoteViews.setString(R.id.name_of_the_app, "setText", "android os");
remoteViews.setTextViewText(R.id.description, "best ever");
Log.i("updateCurrentWidget", "the text have been set");
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(appWidgetId, remoteViews);
}
manifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="14" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name=".Widget2" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="widget2.SCROLL_LEFT" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_small" />
</receiver>
</application>
</manifest>
and here is the simplified logcat logs:
onReceive()
"myPackageName".Widget2.SCROLL_LEFT
the text have been set
"myPackageName".Widget2.SCROLL_LEFT appWidgetId = 268435456
everything seems to be correct but the text is never changed!
The key in the widget is you have to set every View and every Intent before calling the updateAppWidget() method. Here You can call updateWidgetInstance(...) from your onReceive() method:
// action = the String that you get from your intent in the onRecive() method
// id = the id of the appWidget instance that you want to update
// you can get the id in the onReceive() method like this:
// int id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
private static void updateWidgetInstance(Context context, AppWidgetManager manager, String action, int id) {
RemoteViews remoteViews = updateCurrentWidget(context, id);
remoteViews = setIntents(remoteViews, context, id);
manager.updateAppWidget(id, remoteViews);
}
updating the View: (Here you can also change the layout of this instance depending on your needs)
private static RemoteViews updateCurrentWidget(Context context, int appWidgetId) {
RemoteViews remoteViews;
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_small_layout);
remoteViews.setTextViewText(R.id.widget_name_of_the_app, "Android OS");
remoteViews.setTextViewText(R.id.widget_app_description, "best ever");
remoteViews.setImageViewUri(R.id.widget_icon_of_the_app, ...);
return remoteViews;
}
updating intents:
private static RemoteViews setIntents(RemoteViews rm, Context context, int appWidgetId) {
Intent click = new Intent(context, Widget.class);
click.setAction("[name of the action]");
click.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, appWidgetId, click, PendingIntent.FLAG_UPDATE_CURRENT);
rm.setOnClickPendingIntent(R.id.button1, pendingIntent);
return rm;
}
you are setting your appWidgetId in the PendingIntent flags. that's just wrong since PendingIntet flags have meanings, they are not meant to save some data.
You should use the extras for that.
So, I've got a widget, I want it to update every 60 seconds. When the widget is first added to the homescreen, it runs its update function just fine. Beyond that it's supposed to start an AlarmManager, which will rerun the update method every 60 seconds. That's the part that it doesn't seem to be actually doing. Here's my code:
public class ClockWidget extends AppWidgetProvider {
public static String CLOCK_WIDGET_UPDATE = "com.nickavv.cleanwidget.CLEANCLOCK_UPDATE";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetIds[]) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.clocklayout);
appWidgetManager.updateAppWidget(appWidgetId, views);
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
Log.d("log","Entered update cycle");
//Unimportant for these purposes
appWidgetManager.updateAppWidget(appWidgetId, views);
}
private PendingIntent createClockTickIntent(Context context) {
Intent intent = new Intent(CLOCK_WIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
#Override
public void onEnabled(Context context) {
super.onEnabled(context);
Log.d("onEnabled","Widget Provider enabled. Starting timer to update widget every minute");
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 60000, createClockTickIntent(context));
}
#Override
public void onDisabled(Context context) {
super.onDisabled(context);
Log.d("onDisabled", "Widget Provider disabled. Turning off timer");
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(createClockTickIntent(context));
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d("onReceive", "Received intent " + intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Log.d("onReceive", "Clock update");
// Get the widget manager and ids for this widget provider, then
// call the shared
// clock update method.
ComponentName thisAppWidget = new ComponentName(context.getPackageName(), getClass().getName());
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int ids[] = appWidgetManager.getAppWidgetIds(thisAppWidget);
for (int appWidgetID: ids) {
updateAppWidget(context, appWidgetManager, appWidgetID);
}
}
}
}
It's the product of a few tutorials I've found on the matter, and my own knowledge of Android. According to my logcats, it never gets to the Log.d("onReceive", "Clock update"); line. And yes, my Manifest is set up with the clock update intent. Thanks!
EDIT: Additional info. I put a log line in the createClockTickIntent method, and it fires off. So I guess this means that my application is running the alarmManager.setRepeating line, no idea why is isn't actually repeating.
Arggghhh, it was a simple typo. The intent filter was "com.nickavv.cleanwidgets.CLEANCLOCK_UPDATE", and I had written "com.nickavv.cleanwidget.CLEANCLOCK_UPDATE"
What a pain, but hey, now I know.
So, moral of the story for anybody with a similar problem to me: Check your spelling! Check it twice, or ten times. On everything!
You have to make an appwidget-provider and set updatePeriodMillis on 0.6 second , then it will be update per 60 seconds.
<?xml version="1.0" encoding="utf-8" ?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dp"
android:initialLayout="#layout/YourLayout"
android:updatePeriodMillis="0.6"
android:minHeight="144dp"/>
Hi i've never worked with widgets before but what i'm looking to do is create a very simple widget i basically want to make a 1 by 1 widget that has just an icon, just an image set as the background no text nothing just a small icon and when the icon is pressed i want to open an activity. Basically i want to make a second icon like in the app drawer in a widget form that opens another activity rather than the main one.
Any help is greatly appreciated
My provider ended up looking like this after a lot of research and playing
public class WidgetProvider extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, ClassToLaunchHere.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.widget, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
Couple of app widget implementations that show the easiest way to do that are visible at https://github.com/commonsguy/cw-advandroid/tree/master/AppWidget.
Specifically, https://github.com/commonsguy/cw-advandroid/blob/master/AppWidget/PairOfDice/src/com/commonsware/android/appwidget/dice/AppWidget.java shows how to use a PendingIntent as the onClick target for a Button. You can make your PendingIntent start an Activity and you should be good to go.
Declare a Variable
public static String YOUR_AWESOME_ACTION = "YourAwesomeAction";
then add onUpdate and onReceive
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
ComponentName thisWidget = new ComponentName(context, DigitalClock.class);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.digital_clock);
for (int widgetId : appWidgetManager.getAppWidgetIds(thisWidget)) {
remoteViews.setOnClickPendingIntent(R.id.imageView, getPendingSelfIntent(context, YOUR_AWESOME_ACTION));
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
super.onReceive(context, intent);
if (YOUR_AWESOME_ACTION.equals(intent.getAction())) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.digital_clock);
ComponentName watchWidget = new ComponentName(context, DigitalClock.class);
appWidgetManager.updateAppWidget(watchWidget, remoteViews);
Intent ntent = new Intent(context, MainActivity.class);
ntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(ntent);
//Toast.makeText(context, YOUR_AWESOME_ACTION, Toast.LENGTH_SHORT).show();
}
}
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
and add activity on Manifest
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
hope this will help