Code is written down to update the widget.
this code works always
Toast.makeText(context, ""+cd.getId(), Toast.LENGTH_LONG).show();
But nether code only works when it is Debug.
#Override
public void onUpdate(Context context, AppWidgetManager appwidgetmanager,
int[] appWidgetIds) {
for (int i : appWidgetIds) {
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget4x4persian);
shaffle(context, appwidgetmanager, i, views);
}
}
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
super.onReceive(context, intent);
ComponentName thisWidget = new ComponentName(context, gift4x4.class);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget4x4persian);
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
clickWidget(context, appWidgetManager, intent, remoteViews);
}
private void clickWidget(Context context,
AppWidgetManager appWidgetManager, Intent intent,
RemoteViews remoteViews) {
Cursor c = null;
try {
ComponentName thisWidget = new ComponentName(context, gift4x4.class);
Bundle b = intent.getExtras();
if (b != null) {
int key = b.getInt(WIDGET_KEY);
String id = null;
int[] allWidgetIds = appWidgetManager
.getAppWidgetIds(thisWidget);
for (int i : allWidgetIds) {
RemoteViews views = new RemoteViews(
context.getPackageName(),
R.layout.widget4x4persian);
shaffle(context, appWidgetManager, i, remoteViews);
}
}
} catch (NumberFormatException e) {
e.getMessage();
} finally {
if (c != null)
c.close();
}
}
public void shaffle(Context context, AppWidgetManager appwidgetmanager,
int appWidgetId, RemoteViews Rview) {
Cursor c = null;
try {
Card cd = null;
do {
PreferenceManager pm = new PreferenceManager(context);
Cards_Count = pm.get(PREFNAME_CARDS_COUNTS, CARDS_COUNTS);
int shaffle = (new Random()).nextInt(Cards_Count);
c = context.getContentResolver().query(CONTENT_URI_CARDS,
new String[] { ID, TEXT, ISREAD, ISBOOKMARK, NOTE },
"id=" + shaffle, null, null);
if (c.moveToFirst()) {
cd = new Card(c.getInt(c.getColumnIndex(ID)), c.getString(c
.getColumnIndex(TEXT)), c.getInt(c
.getColumnIndex(ISREAD)), c.getInt(c
.getColumnIndex(ISBOOKMARK)), c.getString(c
.getColumnIndex(NOTE)));
}
c.close();
} while (c == null);
Rview.setImageViewResource(R.id.imgIsBookmarkWidget, cd
.getIsBookmark() == 1 ? R.drawable.bookmark
: R.drawable.unbookmark);
Bitmap bmp = getPicture(context, cd.getId());
Toast.makeText(context, ""+cd.getId(), Toast.LENGTH_LONG).show();
Rview.setImageViewBitmap(R.id.imgWidget, bmp);
Intent intentTemp = new Intent(context, gift4x4.class);
intentTemp.putExtra(WIDGET_KEY, key);
PendingIntent pendingintentTemp = PendingIntent.getBroadcast(context, key,
intentTemp, PendingIntent.FLAG_UPDATE_CURRENT);
Rview.setOnClickPendingIntent(R.id.imgShaffleWidget,
getProperIntent(context, 3, cd));
appwidgetmanager.updateAppWidget(appWidgetId, Rview);
} catch (Exception e) {
e.getMessage();
} finally {
if (c != null)
c.close();
}
}
Maybe the Context you are using is not the right type.
Just use the context which is passed into function, don't use private contexts declared in class.
public void onReceive(Context context, Intent intent)
Related
I am building an android app with eclipse and I have a widget that displays a listview that has a button in each for for capturing row item and saving to sqlite db. I am trying to figure out how to update the list whenever the user updates the list in the main app or if they click the refresh imageview I have on the widget. Below are the following classes/files used for the widget. I tried searching everywhere and all the solutions don't seem to work for a listview widget with a service. Any help is greatly appreciated!
WidgetProvider.class
public class WidgetProvider extends AppWidgetProvider {
DBHelper pdh;
public static final String ACTION_TOAST = "actionToast";
public static final String ACTION_BUTTON = "actionButton";
public static final String EXTRA_ITEM_POSITION = "extraItemPosition";
SimpleDateFormat sdfFinal = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat stf = new SimpleDateFormat("HH:mm");
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; ++i) {
RemoteViews remoteViews = updateWidgetListView(context, appWidgetIds[i]);
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Intent clickIntentRefresh = new Intent(context, WidgetProvider.class);
clickIntentRefresh.setAction(ACTION_BUTTON);
PendingIntent clickPendingIntentRefresh = PendingIntent.getBroadcast(context, 0, clickIntentRefresh, 0);
Intent clickIntent = new Intent(context, WidgetProvider.class);
clickIntent.setAction(ACTION_TOAST);
PendingIntent clickPendingIntent = PendingIntent.getBroadcast(context, 0, clickIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.ivRefresh,clickPendingIntentRefresh);
remoteViews.setOnClickPendingIntent(R.id.button1, pendingIntent);
remoteViews.setPendingIntentTemplate(R.id.listViewWidget, clickPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (ACTION_TOAST.equals(intent.getAction())) {
String s = intent.getStringExtra(EXTRA_ITEM_POSITION);
pdh = new DBHelper(context);
Calendar cal = Calendar.getInstance();
String strDateStamp = sdfFinal.format(cal.getTime());
String strTimeStamp = stf.format(cal.getTime());
pdh.insertRecord(s, null, strDateStamp, strTimeStamp);
Toast.makeText(context, "Saved!", Toast.LENGTH_SHORT).show();
} else if (ACTION_BUTTON.equals(intent.getAction())) {
Toast.makeText(context, "Refresh Clicked!", Toast.LENGTH_SHORT).show();
}
}
private RemoteViews updateWidgetListView(Context context, int appWidgetId) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
Intent svcIntent = new Intent(context, WidgetService.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
remoteViews.setRemoteAdapter(R.id.listViewWidget, svcIntent);
remoteViews.setEmptyView(R.id.listViewWidget, R.id.empty_view);
return remoteViews;
}
}
WidgetService.class
public class WidgetService extends RemoteViewsService {
/*
* So pretty simple just defining the Adapter of the listview here Adapter is
* ListProvider
*/
#Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return (new ListProvider(this.getApplicationContext(), intent));
}
}
ListProvider.class
public class ListProvider implements RemoteViewsFactory {
public static final String EXTRA_ITEM_POSITION = "extraItemPosition";
private ArrayList<ListItem> listItemList = new ArrayList<ListItem>();
private Context context = null;
private Intent intent;
public ListProvider(Context context, Intent intent) {
this.intent = intent;
this.context = context;
intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
populateListItem();
}
private void populateListItem() {
try {
DBHelper pdh = new DBHelper(context);
listItemList.clear();
SQLiteDatabase db = pdh.getReadableDatabase();
String[] columns = new String[] { "Categories" };
Cursor c = db.query("tblCategories", columns, null, null, null, null, "Categories asc");
int categoriesInt = c.getColumnIndex("Categories");
int totalCategories = c.getCount();
for (int i = 0; i < totalCategories; i++) {
c.moveToPosition(i);
ListItem listItem = new ListItem();
listItem.heading = c.getString(categoriesInt);
listItemList.add(listItem);
}
c.close();
db.close();
pdh.close();
} catch (Exception ex) {
}
}
#Override
public int getCount() {
return listItemList.size();
}
#Override
public long getItemId(int position) {
return position;
}
/*
* Similar to getView of Adapter where instead of View we return RemoteViews
*
*/
#Override
public RemoteViews getViewAt(int position) {
try {
final RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.list_row);
ListItem listItem = (ListItem) listItemList.get(position);
remoteView.setTextViewText(R.id.heading, listItem.heading);
Intent fillIntent = new Intent();
fillIntent.putExtra(EXTRA_ITEM_POSITION, listItem.heading);
remoteView.setOnClickFillInIntent(R.id.button1, fillIntent);
return remoteView;
} catch (Exception ex) {
return null;
}
}
#Override
public RemoteViews getLoadingView() {
// TODO Auto-generated method stub
return null;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
}
#Override
public void onDataSetChanged() {
// TODO Auto-generated method stub
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
}
}
ListItem.class
public class ListItem {
public String heading;
}
AndroidManifest.xml
<receiver android:name=".WidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widgetinfo" />
</receiver>
<service
android:name=".WidgetService"
android:permission="android.permission.BIND_REMOTEVIEWS" />
I am trying to create a simple android widget that shows and I want to use custom font in my application, can anyone help me?
this my code :
public class ExampleAppWidgetProvider extends AppWidgetProvider {
private static final String LOG_TAG = "ExampleWidget";
private static final DateFormat df = new SimpleDateFormat("hh:mm:ss");
/**
* Custom Intent name that is used by the AlarmManager to tell us to update
* the clock once per second.
*/
public static String CLOCK_WIDGET_UPDATE = "com.eightbitcloud.example.widget.8BITCLOCK_WIDGET_UPDATE";
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Log.d(LOG_TAG, "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);
}
}
}
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 onDisabled(Context context) {
super.onDisabled(context);
Log.d(LOG_TAG, "Widget Provider disabled. Turning off timer");
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(createClockTickIntent(context));
}
#Override
public void onEnabled(Context context) {
super.onEnabled(context);
Log.d(LOG_TAG,
"Widget Provider enabled. Starting timer to update widget every second");
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 1);
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
1000, createClockTickIntent(context));
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
Log.d(LOG_TAG, "Updating Example Widgets.");
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, WidgetExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget1);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current app
// widget
appWidgetManager.updateAppWidget(appWidgetId, views);
// Update The clock label using a shared method
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
public static void updateAppWidget(Context context,
AppWidgetManager appWidgetManager, int appWidgetId) {
String currentTime = df.format(new Date());
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget1);
updateViews.setTextViewText(R.id.widget1label, currentTime);
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
}
I want to reject call after 1 sec and make notification
But when i make notification then it give syntax error in getSystemService
What can i do
Here is my code for rejecting call and make notification
private String incomingnumber;
#Override
public void onReceive(Context context, Intent intent) {
String s[] = { "045193117", "800000000" };
Bundle b = intent.getExtras();
incomingnumber = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
try {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
final com.android.internal.telephony.ITelephony telephonyService = (ITelephony) m
.invoke(tm);
for (int i = 0; i < s.length; i++) {
if (s[i].equals(incomingnumber)) {
Runnable mMyRunnable2 = new Runnable() {
#Override
public void run() {
try {
telephonyService.endCall();
NotificationManager nm= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify= new Notification(android.R.drawable.ic_lock_idle_low_battery, "Battery Notification",SystemClock.currentThreadTimeMillis());
CharSequence title="Battery Level ";
CharSequence details= "Continue with what you were doing";
Intent intent= new Intent(context, MainActivity.class);
PendingIntent pi= PendingIntent.getSctivity(con, 0, intent, 0);
notify.setLatestEventInfo(con, title, details, pi);
nm.notify(0, notify);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable2, 1000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
replace
NotificationManager nm= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
with
NotificationManager nm= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
and make the context parameter as final to access it inner class (here Runnable).
public void onReceive(final Context context,Intent intent) {
//
}
when you say getSystemService() in Runnable, it will look for that method in Runnable implementation class which is actually not.
I am currently learning about widgets in Android. I want to increment counter value, but when I click on widget it increment it from 0 to 1 and stops to increase it. My onRecieve method work fine.
Here is my code:
public static CheckDate CheckDate;
public static EventList EventList;
public static String EVENT_CLICK = "EventClick";
public String msg;
public RemoteViews rviews;
public AppWidgetManager manager;
public Context cntxt;
public Intent intnt;
public int[] ids;
public int counter = 0;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
super.onUpdate(context, appWidgetManager, appWidgetIds);
CheckDate = new CheckDate();
EventList = new EventList();
manager = appWidgetManager;
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
ids = appWidgetIds;
Intent intent = new Intent(context, DayWidget.class);
intent.setAction(EVENT_CLICK);
intent.putExtra("msg", "change");
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.Event, actionPendingIntent);
CheckDate.Check();
views.setTextViewText(R.id.Today, CheckDate.Today);
views.setTextViewText(R.id.Event, String.valueOf(counter));
manager.updateAppWidget(ids, views);
}
public void UpdateWidget(){
Bundle extras = intnt.getExtras();
if(extras!=null) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(cntxt);
ComponentName AppWidget = new ComponentName(cntxt.getPackageName(), DayWidget.class.getName());
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(AppWidget);
rviews = new RemoteViews(AppWidget.getPackageName(), R.layout.widget_layout);
counter ++;
rviews.setTextViewText(R.id.Event, String.valueOf(counter));
appWidgetManager.updateAppWidget(appWidgetIds, rviews);
}
}
public void onReceive(Context context, Intent intent){
intnt = intent;
cntxt = context;
if(EVENT_CLICK.equals(intent.getAction())){
try{
msg = intent.getStringExtra("msg");
}catch(NullPointerException e){
e.printStackTrace();
}
UpdateWidget();
Toast toast = Toast.makeText(cntxt, "OnClick", Toast.LENGTH_LONG);
toast.show();
}
super.onReceive(context, intent);
}
make your public int counter = 0; static to be public static int counter = 0;
Or save it on shared preference
If I have two widgets and I press on a button on the first one, the second widget updates itself. That is not the intention :) When debugging I noticed that the first widget the widgetid of te second used for updating
public class WidgetActivity extends AppWidgetProvider {
public static WidgetActivity Widget = null;
public static Context context;
public static AppWidgetManager appWidgetManager;
public static int appWidgetIds[];
public static String ACTION_OPEN_APP = "OpenApp";
private static int appWidgetId;
#Override
public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds ) {
if (null == context) context = WidgetActivity.context;
if (null == appWidgetManager) appWidgetManager = WidgetActivity.appWidgetManager;
if (null == appWidgetIds) appWidgetIds = WidgetActivity.appWidgetIds;
WidgetActivity.Widget = this;
WidgetActivity.context = context;
WidgetActivity.appWidgetManager = appWidgetManager;
WidgetActivity.appWidgetIds = appWidgetIds;
final int N = appWidgetIds.length;
for (int i=0; i<N; i++)
{
appWidgetId = appWidgetIds[i];
updateAppWidget(context,appWidgetManager, appWidgetId);
}
}
public void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent intent = new Intent(context, UpdateService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
Intent configIntent = new Intent(context, Main.class);
configIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.headlinesBox, configPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.WidgetRefresh_btn, pendingIntent);
setHeadlines(appWidgetId);
// Tell the widget manager
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
public static void setHeadlines(int appWidgetId)
{
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
ArrayList<String> newsItems = getRssItems("*****rss.php", appWidgetId);
if(newsItems.size() == 3)
{
remoteViews.setTextViewText(R.id.headline1, newsItems.get(0));
remoteViews.setTextViewText(R.id.headline2, newsItems.get(1));
remoteViews.setTextViewText(R.id.headline3, newsItems.get(2));
}
DateTime dateTime = new DateTime();
CharSequence text = dateTime.getTime();
remoteViews.setTextViewText(R.id.WidgetUpdateTime, text);
remoteViews.setViewVisibility(R.id.progressWidget, View.GONE);
remoteViews.setViewVisibility(R.id.WidgetRefresh_btn, View.VISIBLE);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
public static ArrayList<String> getRssItems(String feedUrl, int appWidgetId)
{
}
public static class UpdateService extends Service {
#Override
public void onStart(Intent intent, int startId) {
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget);
remoteViews.setViewVisibility(R.id.WidgetRefresh_btn, View.GONE);
remoteViews.setViewVisibility(R.id.progressWidget, View.VISIBLE);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
WidgetActivity.Widget.onUpdate(context, appWidgetManager, appWidgetIds);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
}
It is difficult to understand what you mean by:
When debugging I noticed that the first widget the widgetid of te second used for updating
But, I think I understand your general problem: your AppWidgets are not being updated correctly? After glancing at your code, it looks like your problem could be that appWidgetId is declared as static. Perhaps try removing that keyword.
Also, I don't see anywhere in your code a button.
EDIT
It looks like your appWidgetId is being overwritten. Here is my suggestion, take advantage of the AppWidgetProvider being a broadcast receiver and instead send a broadcast as a result of your PendingIntent button click. You will also have to make sure to pass the appWidgetId as an extra to ensure that the correct widget gets updated. Here is an example, should be in your updateAppWidget method:
Intent refreshAction = new Intent();
refreshAction.setAction(MY_CUSTOM_REFRESH_ACTION);
refreshAction.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent refreshPendingIntent.........
And then in the onReceive override:
#Override
public void onReceive(Context context, Intent intent) {
.....
Bundle extras = intent.getExtras();
int appWidgetId = extras.getExtra(AppWidgetManager.EXTRA_APPWIDGET_ID);
.....
}
And then you should be ready to go, updating the correct widget. One more caveat, make sure to read the documentation on BroadcastReceivers if you have not already. You will have to register to accept MY_CUSTOM_REFRESH_ACTION within the WidgetActivity element in your AndroidManifest.