Android: Intent's extra is missing (working with widget) - android

I want to make a widget with 2 Buttons(one is a Textview with a number). One button should increment the number and the other decrement it.
Here are my variables(2x action-names and an int for the number)
private static final String PLUS_ONE = "Plus1";
private static final String MINUS_ONE = "minus1";
static int counter = 0;
The onUpdate():
#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 remoteViews = new RemoteViews(context.getPackageName(), R.layout.plus1counter_widget);
remoteViews.setOnClickPendingIntent(R.id.counter_widget, getPendingSelfIntent(context, PLUS_ONE, counter));
remoteViews.setOnClickPendingIntent(R.id.img_downWid, getPendingSelfIntent(context, MINUS_ONE, counter));
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}}
getPendingSelfIntent is my method to create an intent, putting an int value in it and returning an PendingIntent
Here in detail:
protected PendingIntent getPendingSelfIntent(Context context, String action, int i) {
Intent intent = new Intent(context, Plus1CounterAppWidgetProvider.class);
intent.setAction(action);
intent.putExtra("safeInt", i);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);}
and eventually my onReturn() in which I want to set the counter to the value I gave to the Intent and perform the action:
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
counter = intent.getIntExtra("safeInt", 0);
if (PLUS_ONE.equals(intent.getAction())) {
counter++;
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.plus1counter_widget);
remoteViews.setTextViewText(R.id.counter_widget, Integer.toString(counter));
AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, Plus1CounterAppWidgetProvider.class), remoteViews);
}
if (MINUS_ONE.equals(intent.getAction())) {
counter--;
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.plus1counter_widget);
remoteViews.setTextViewText(R.id.counter_widget, Integer.toString(counter));
AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, Plus1CounterAppWidgetProvider.class), remoteViews);
}}
By calling
counter = intent.getIntExtra("safeInt", 0);
the counter is always set to 0, which means that there is no extra value.
I just do not get why! Any Solutions? :)

I found an other solution.
I just used SharedPreferences instead of the Intent and it worked! :)
Here is the code:
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;
public class Plus1CounterAppWidgetProvider extends AppWidgetProvider{
private static final String PLUS_ONE = "Plus1";
private static final String MINUS_ONE = "Minus1";
private static final String REFRESH_COUNTER = "Refresh";
static int counter = 0;
#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 remoteViews = new RemoteViews(context.getPackageName(), R.layout.plus1counter_widget);
remoteViews.setOnClickPendingIntent(R.id.counter_widget, getPendingSelfIntent(context, PLUS_ONE));
remoteViews.setOnClickPendingIntent(R.id.img_downWid, getPendingSelfIntent(context, MINUS_ONE));
remoteViews.setOnClickPendingIntent(R.id.img_refreshWid, getPendingSelfIntent(context, REFRESH_COUNTER));
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
SharedPreferences sharedPref = context.getSharedPreferences("com.plus1counter.safeFile", Context.MODE_PRIVATE);
counter = sharedPref.getInt("safeFile", 0);
if(counter == 100){
counter = 0;
}
if (PLUS_ONE.equals(intent.getAction())) {
counter++;
writeSharedPrefs(sharedPref);
}
if (MINUS_ONE.equals(intent.getAction())) {
counter--;
writeSharedPrefs(sharedPref);
}
if(REFRESH_COUNTER.equals(intent.getAction())){
counter = 0;
writeSharedPrefs(sharedPref);
}
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.plus1counter_widget);
remoteViews.setTextViewText(R.id.counter_widget, Integer.toString(counter));
AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, Plus1CounterAppWidgetProvider.class), remoteViews);
}
public void writeSharedPrefs(SharedPreferences sharedPref){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("safeFile", counter);
editor.commit();
}
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, Plus1CounterAppWidgetProvider.class);
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}

Related

Play sound on widget click

Here's my code, it opens the main activity, but I can't seem to find a way to just make the widget play a sound.
I tried to:
add a button to the widget (didn't work)
add an OnClickListener to the main activity (which works but it opens the main activity and I just want the sound not the activity)
write a new method to play the sound with the MediaPlayer sound.start() method in it and calling it (didn't work)
I've looked in the android dev page and all I was able to find was how to use the MediaPlayer, but it says nothing about playing audio from a widget.
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
public class ClockWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.clock_widget_layout);
views.setOnClickPendingIntent(R.id.AnalogClock0, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
To do it you need to use a service which you call like this
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.trck);
//configure other settings
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
}
Please register this service in Manifest.
<service android:enabled="true" android:name=".BackgroundSoundService" />
and you could do smth like this in widget
public class ClockWidget extends AppWidgetProvider {
private final String ACTION_WIDGET_PLAY = "PlaySong";
private final String ACTION_WIDGET_PAUSE = "PauseSong";
private final String ACTION_WIDGET_STOP = "StopSong";
private final int INTENT_FLAGS = 0;
private final int REQUEST_CODE = 0;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
RemoteViews controlButtons = new RemoteViews(context.getPackageName(),
R.layout.main);
Intent playIntent = new Intent(this, BackgroundSoundService.class);
Intent pauseIntent = new Intent(this, BackgroundSoundService.class);
Intent stopIntent = new Intent(this, BackgroundSoundService.class);
PendingIntent playPendingIntent = PendingIntent.getService(
this, REQUEST_CODE, playIntent, INTENT_FLAGS);
PendingIntent pausePendingIntent = PendingIntent.getService(
this, REQUEST_CODE, pauseIntent, INTENT_FLAGS);
PendingIntent stopPendingIntent = PendingIntent.getService(
this, REQUEST_CODE, stopIntent, INTENT_FLAGS);
controlButtons.setOnClickPendingIntent(
R.id.btnPlay, playPendingIntent);
controlButtons.setOnClickPendingIntent(
R.id.btnPause, pausePendingIntent);
controlButtons.setOnClickPendingIntent(
R.id.btnStop, stopPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, controlButtons);
}
}

How to get Click event on List Item of Home Screen widget in android [duplicate]

This question already has answers here:
Android start activity when pressing widget ListView item
(2 answers)
how to attach a onClick Listener to a listview item on an app widget
(3 answers)
listview in app widget android
(1 answer)
Android clickable Widget with ListView not clickable on ListItems
(1 answer)
Closed 5 years ago.
Issue
I have widget on homescreen with Listview which dynamic data item, now
can I get click event on listview item click.
As I can get click of another button on widget but still not success on list item click.
SimpleWidgetProvider.Java
public class SimpleWidgetProvider extends AppWidgetProvider {
public static String UPDATE_ACTION = "ActionUpdateSinglenoteWidget";
public static final String TOAST_ACTION = "com.varshaaweblabs.estateblock.TOAST_ACTION";
public static final String EXTRA_ITEM = "com.varshaaweblabs.estateblock.EXTRA_ITEM";
private static final String MyButton1 = "mybutton1";
private static final String MyButton2 = "mybutton2";
static RemoteViews remoteViews;
public static SharedPreferences.Editor editor;
public static SharedPreferences pref;
public Call<Search_Response> registerResponseCall;
ArrayList<Listing> listItemList = new ArrayList<>();
Gson gson1 = new Gson();
public static GoogleMap mMap;
ArrayList<String> jarray = new ArrayList<>();
public Criteria criteria = new Criteria();
public void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager,
final int appWidgetId) {
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
pref = context.getSharedPreferences("estateblock", MODE_PRIVATE);
editor = pref.edit();
getData(context, MyButton1);
remoteViews.setInt(R.id.btn_current, "setBackgroundColor", Color.MAGENTA);
remoteViews.setInt(R.id.btn_home, "setBackgroundColor", Color.LTGRAY);
remoteViews.setInt(R.id.btn_seeall, "setBackgroundColor", Color.MAGENTA);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Set up the collection
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
setRemoteAdapter(context, remoteViews);
} else {
setRemoteAdapterV11(context, remoteViews);
}
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
remoteViews.setOnClickPendingIntent(R.id.btn_current, getPendingSelfIntent(context, MyButton1));
remoteViews.setOnClickPendingIntent(R.id.btn_home, getPendingSelfIntent(context, MyButton2));
remoteViews.setViewVisibility(R.id.progress, View.GONE);
remoteViews.setViewVisibility(R.id.widget_list, View.VISIBLE);
pushWidgetUpdate(context, remoteViews);
notifyUpdate(context, remoteViews);
}
}, 5000);
}
#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);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
/**
* Sets the remote adapter used to fill in the list items
*
* #param views RemoteViews to set the RemoteAdapter
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private static void setRemoteAdapter(Context context, #NonNull final RemoteViews views) {
views.setRemoteAdapter(R.id.widget_list,
new Intent(context, WidgetService.class));
}
/**
* Sets the remote adapter used to fill in the list items
*
* #param views RemoteViews to set the RemoteAdapter
*/
#SuppressWarnings("deprecation")
private static void setRemoteAdapterV11(Context context, #NonNull final RemoteViews views) {
views.setRemoteAdapter(0, R.id.widget_list,
new Intent(context, WidgetService.class));
}
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {
ComponentName myWidget = new ComponentName(context, SimpleWidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(myWidget, remoteViews);
}
public void notifyUpdate(Context context, RemoteViews remoteViews) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int appWidgetIds[] = manager.getAppWidgetIds(
new ComponentName(context, SimpleWidgetProvider.class));
manager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list);
hideProgress(remoteViews, context);
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
String action = intent.getAction();
AppWidgetManager mgr = AppWidgetManager.getInstance(context);
if (intent.getAction().equals(TOAST_ACTION)) {
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
int viewIndex = intent.getIntExtra(EXTRA_ITEM, 0);
Toast.makeText(context, "Touched view " + viewIndex, Toast.LENGTH_SHORT).show();
}
if (MyButton1.equals(intent.getAction())) {
pref = context.getSharedPreferences("estateblock", MODE_PRIVATE);
editor = pref.edit();
listItemList.clear();
updateData(context, MyButton1);
Toast.makeText(context, "Current Criteria", Toast.LENGTH_SHORT).show();
}
if (MyButton2.equals(intent.getAction())) {
pref = context.getSharedPreferences("estateblock", MODE_PRIVATE);
editor = pref.edit();
listItemList.clear();
updateData(context, MyButton2);
}
}
private void updateData(final Context context, String myButton) {
if (myButton.equalsIgnoreCase("mybutton1")) {
final RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
showProgress(remoteViews, context);
remoteViews.setInt(R.id.btn_home, "setBackgroundColor", Color.LTGRAY);
remoteViews.setInt(R.id.btn_current, "setBackgroundColor", Color.MAGENTA);
Intent configIntent = new Intent(context, HomeActivity.class);
configIntent.putExtra("widget", "Current");
configIntent.setAction("current");
PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.btn_seeall, configPendingIntent);
Toast.makeText(context, "Current", Toast.LENGTH_SHORT).show();
pushWidgetUpdate(context.getApplicationContext(), remoteViews);
getData(context, MyButton1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
notifyUpdate(context.getApplicationContext(), remoteViews);
}
}, 3500);
}
if (myButton.equalsIgnoreCase("mybutton2")) {
final RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
showProgress(remoteViews, context);
remoteViews.setInt(R.id.btn_home, "setBackgroundColor", Color.MAGENTA);
remoteViews.setInt(R.id.btn_current, "setBackgroundColor", Color.LTGRAY);
Intent configIntent1 = new Intent(context, HomeActivity.class);
configIntent1.putExtra("widget", "Home");
configIntent1.setAction("Home");
PendingIntent configPendingIntent1 = PendingIntent.getActivity(context, 1, configIntent1, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.btn_seeall, configPendingIntent1);
Toast.makeText(context, "All Homes", Toast.LENGTH_SHORT).show();
pushWidgetUpdate(context.getApplicationContext(), remoteViews);
getData(context, MyButton2);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
notifyUpdate(context.getApplicationContext(), remoteViews);
}
}, 3500);
}
}
}
ListProvider.java
public class ListProvider implements RemoteViewsService.RemoteViewsFactory {
private Context context = null;
private int appWidgetId;
List<Listing> list = new ArrayList<>();
List<String> mCollection = new ArrayList<>();
public static List<Listing> listItemList = new ArrayList<>();
SharedPreferences.Editor editor;
SharedPreferences pref;
Gson gson = new Gson();
public ListProvider(Context context, Intent intent) {
this.context = context;
pref = context.getSharedPreferences(Utility.APP_NAME, MODE_PRIVATE);
editor = pref.edit();
Log.e("Constructor", "Called");
populateListItem();
}
public void populateListItem() {
listItemList.clear();
String arrayListString = pref.getString("widget", "");
Type type = new TypeToken<ArrayList<Listing>>() {
}.getType();
listItemList = gson.fromJson(arrayListString, type);
}
#Override
public int getCount() {
return listItemList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public RemoteViews getViewAt(final int position) {
final RemoteViews remoteView = new RemoteViews(
context.getPackageName(), R.layout.grid_view);
Bitmap image = null;
try {
URL url = new URL(listItemList.get(position).getPrimaryPhoto().getUrl().getThumb());
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
Log.e("Image_load", e.getMessage());
}
remoteView.setImageViewBitmap(R.id.widget_item_app_icon, image);
remoteView.setTextViewText(R.id.heading, listItemList.get(position).getPriceForMap());
remoteView.setTextViewText(R.id.address, listItemList.get(position).getArea());
Intent intent = new Intent(context, Propertyfulldetailactivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
intent.putExtra(Utility.LISTING_KEY, listItemList.get(position).getListingKey());
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST", (Serializable) listItemList.get(position));
intent.putExtra("BUNDLE", args);
remoteView.setOnClickPendingIntent(R.id.widget_item_app_icon, pendingIntent);
return remoteView;
}
#Override
public RemoteViews getLoadingView() {
return null;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public void onCreate() {
Log.e("onCreate", "Called");
populateListItem();
}
#Override
public void onDataSetChanged() {
populateListItem();
}
#Override
public void onDestroy() {
}
}
So please refer my code and try to help me out with this issue.
This is very simple to add a item click listener in list-view. You just take a look in Android List-view link.

Start my application by clicking on widget

I'm trying How do I run an Activity from a button on a widget in Android? in order to launch my application on click on an image button. When i un-comment the code it switches the images but when i try to use this code it does nothing. I'd like to kick off my application instead.
public class MyWidgetIntentReceiver extends BroadcastReceiver {
private static int clickCount = 0;
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("pl.looksok.intent.action.CHANGE_PICTURE")){
updateWidgetPictureAndButtonListener(context);
}
}
private void updateWidgetPictureAndButtonListener(Context context) {
Log.i("PROJECTCARUSO", "updateWidgetPictureAndButtonListener");
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
// remoteViews.setImageViewResource(R.id.widget_button, getImageToSet());
//
// //REMEMBER TO ALWAYS REFRESH YOUR BUTTON CLICK LISTENERS!!!
// remoteViews.setOnClickPendingIntent(R.id.widget_button, MyWidgetProvider.buildButtonPendingIntent(context));
//
// MyWidgetProvider.pushWidgetUpdate(context.getApplicationContext(), remoteViews);
Intent intentClick = new Intent(context, FragmentChange.class);
PendingIntent pendingIntent = PendingIntent.getActivity (context, 0,
intentClick, 0);
remoteViews.setOnClickPendingIntent (R.id.widget_button, pendingIntent);
}
private int getImageToSet() {
clickCount++;
return clickCount % 2 == 0 ? R.drawable.app_icon : R.drawable.energy;
}
}
Here's what i finally got to work:
public class WidgetProvider extends AppWidgetProvider {
public static String SWITCH_WIDGET_UPDATE = "MainActivity.Switch";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.i("PROJECTCARUSO","onUpdate");
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
remoteViews.setOnClickPendingIntent(R.id.widget_button, buildButtonPendingIntent(context));
Intent intentClick = new Intent(context, FragmentChange.class);
PendingIntent pendingIntent = PendingIntent.getActivity (context, 0, intentClick, 0);
remoteViews.setOnClickPendingIntent (R.id.widget_button, pendingIntent);
pushWidgetUpdate(context, remoteViews);
}
public static PendingIntent buildButtonPendingIntent(Context context) {
Intent intent = new Intent();
intent.setAction("CHANGE_PICTURE");
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {
ComponentName myWidget = new ComponentName(context, WidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(myWidget, remoteViews);
}
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
super.onReceive(context, intent);
}
}

Why is AlarmManager not updating my widget?

I have a widget that is simply a textview, that I am attempting to update every second using an AlarmManager. The Log.d("test", "hello1") shows up in my LogCat when I run the app, but the Log.d("test", "service") does not show up, so it appears the program is not even reaching my MyService class.
I would greatly appreciate any help.
Thank you.
Here is my AppWidgetProvider class:
public class NetworkSpeedWidget extends AppWidgetProvider {
private PendingIntent service = null;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Log.d("test", "hello");
super.onUpdate(context, appWidgetManager, appWidgetIds);
final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final Intent i = new Intent(context, MyService.class);
if (service == null)
{
service = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
}
Log.d("test", "hello1");
m.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),1000,service);
}
}
Here is my MyService class:
public class MyService extends Service{
#Override
public void onCreate()
{
Log.d("test", "service");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
buildUpdate();
return super.onStartCommand(intent, flags, startId);
}
private void buildUpdate()
{
MainActivity object = new MainActivity();
String objectString = object.getMegaBitsPerSecondString();
AppWidgetManager manager = AppWidgetManager.getInstance(this);
ComponentName thisWidget = new ComponentName(this, NetworkSpeedWidget.class);
int[]ids = manager.getAppWidgetIds(thisWidget);
final int N = ids.length;
for (int i = 0; i < N; i++){
int awID = ids[i];
RemoteViews v = new RemoteViews(getPackageName(), R.layout.widget);
v.setTextViewText(R.id.widgetTextView,objectString);
manager.updateAppWidget(awID, v);
}
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
All my code is correct, I just needed to declare it in my Manifest.
I simply added the following line:
<service android:enabled="true" android:name=".MyService" />
Thank you jul for your help.

How to save and retrieve an android widget id

I have setup a widget like this
ToggleWidget.java
public class ToggleWidget extends AppWidgetProvider {
static RemoteViews remoteViews;
boolean status = false;
static int appWidgetId;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
appWidgetId = appWidgetIds[i];
remoteViews = new RemoteViews(context.getPackageName(), R.layout.toggle_widget);
Intent intent = new Intent(context.getApplicationContext(), WakeService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getService(
context.getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.bulb_widget, pendingIntent);
if (WakeService.isAwake) {
remoteViews.setImageViewResource(R.id.bulb_widget, R.drawable.bulb_on);
}
else {
remoteViews.setImageViewResource(R.id.bulb_widget, R.drawable.bulb_off);
}
// Tell the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onDeleted(context, appWidgetIds);
}
}
How can i save the ID of every widget i create and delete those that i've deleted with sharedPreferences?
Also from a service i'd like to update the widget like this
private void updateWidget(){
Intent intent = new Intent(this,ToggleWidget.class);
intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int[] ids = {ToggleWidget.appWidgetId};
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
sendBroadcast(intent);
}
How can i retrieve the saved IDs from the service to make the update?
In your Reciever class just override onCreate() method and under that method,
int[] ids = getIntent().getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
Then you will get int array, pls check it, it will work...:)
Take a look at android's Data Storage options. Here is how you could use SharedPreferences...
public class MyService extends Service{
//Class used to store data
private SharedPreferences preferences;
private int[] ids;
private int numIds;
public void retreiveIds(){
preferences = PreferenceManager.getDefaultSharedPreferences(this);
numIds = preferences.getInt("num",0);
ids = new int[numIds];
for(int i=0;i<numIds;i++){
ids[i] = preferences.getInt("ID"+i,0);
}
}
public void saveIds(){
SharedPreferences.Editor ed = preferences.edit();
numIds = ids.length;
//iterate through array and save each id
for(int i=0;i<numIds;i++){
ed.putInt("ID"+i,ids[i]);
}
ed.putInt("num",numIds);
ed.commit();
}
}
There is another way to do it. Code in kotlin:
val thisWidget = ComponentName(context, this.javaClass)
val allWidgetIds: IntArray = appWidgetManager.getAppWidgetIds(thisWidget)
Now you can use these allWidgetIds to update widgets.

Categories

Resources