I want to make a widget app that is able to dial a number and user can set the number when he first drag and drop widget to home screen using widget configuration.But when the phone restarts widget uses default number again. I decide to save the entered phonenumber to Shared Preferences to save and load user's phone number but eclipse says that using getSharedPreferences is not allowed in onUpdate.Is there another way to perform it?
What should I do?
my code:
public class Main extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
for(int i=0 ; i<appWidgetIds.length ; i++)
{
SharedPreferences details = getSharedPreferences("OPERATOR", 0);
int appWidgetId = appWidgetIds[i];
String phNumber = "5554574";
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+(phNumber)));
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
views.setOnClickPendingIntent(R.id.button1, pending);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
Use:
SharedPreferences details = context.getSharedPreferences("OPERATOR", 0);
SharedPreferences has to be acquired from the context. onUpdate(...) provides you the context.
Your changed code should look like this:
public class Main extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
for(int i=0 ; i<appWidgetIds.length ; i++)
{
SharedPreferences details = context.getSharedPreferences("OPERATOR", 0);
int appWidgetId = appWidgetIds[i];
String phNumber = "5554574";
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+(phNumber)));
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
views.setOnClickPendingIntent(R.id.button1, pending);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
Please try it.
AppWidgetProvider is not a Context. But you can often create a static method to reach the context of an application, then do this
In Android Manifest file declare following
<application android:name="com.example.MyApplication">
</application>
then write the class
public class MyApplication extends Application{
private static Context context;
public void onCreate(){
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Then you can use
SharedPreferences details = MyApplication.getAppContext().getSharedPreferences("OPERATOR", 0);
I haven't worked with widgets yet so can't guarantee this solution but hope it work!
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 need to create Widgets in my android app similar work flow of contact widgets in android. But the problem facing is if there are n widgets of the same application each widgets have different functionality. how to differentiate the button click on each widgets.?
public class MyWidgetActivity extends AppWidgetProvider {
private static final String MyOnClick = "myOnClickTag";
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = MyWidgetActivityConfigureActivity.loadTitlePref(context, appWidgetId);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.simple_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
views.setOnClickPendingIntent(R.id.actionButton, getPendingSelfIntent(context, MyOnClick,views.getLayoutId()));
// 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);
// Tell the AppWidgetManager to perform an update on the current app
// widget
}
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
// When the user deletes the widget, delete the preference associated with it.
for (int appWidgetId : appWidgetIds) {
MyWidgetActivityConfigureActivity.deleteTitlePref(context, appWidgetId);
}
}
#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
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (MyOnClick.equals(intent.getAction()))
{
int appWidgetId = intent.getIntExtra(EXTRA_APPWIDGET_ID,0);
Log.e("KOKOKOKO :: ",""+appWidgetId);
MyWidgetActivityConfigureActivity.loadIdPrefCallQuick(context,appWidgetId);
//your onClick action is here
Toast.makeText(context,"Quick Action Triggered",Toast.LENGTH_SHORT).show();
}
super.onReceive(context, intent);
}
static PendingIntent getPendingSelfIntent(Context context, String action, int appWidgtId)
{
// if we brodcast than definetly we have to define ONRECEIVE
Intent intent = new Intent(context, MyWidgetActivity.class);
intent.putExtra(EXTRA_APPWIDGET_ID,appWidgtId);
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
}
Instead of this code (static PendingIntent getPendingSelfIntent) :
return PendingIntent.getBroadcast(context, 0, intent, 0);
You should do this :
return PendingIntent.getBroadcast(context, appWidgtId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
This way you should get unique intent and also unique appWidgtId.
It is important to set requestCode (2nd attribute of getBroadcast), so it wouldn't conflict.
I am using asynctask to do my feature function and getting the values there. But my text view is not getting updated, though my log statements giving me the result.
I am not using custom intent here, just the basic one.
Here are my code snippets:
public class ListViewWidget extends AppWidgetProvider{
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
updateViews = new RemoteViews(context.getPackageName(), R.layout.list_layout);
thisWidget = new ComponentName(context, ListViewWidget.class);
FetchTask fetchTask=new FetchTask();
AppWidgetManager.getInstance(context.getApplicationContext());
fetchTask.execute();
}
//FetchTask
public static class FetchTask extends AsyncTask<URL,Integer,String> implements ServerRequestEnvironment{
protected String doInBackground(URL... arg0) {
//logic part and stuff not entered
//This is the end part that returns me the result, which is not getting printed to text view.
String name="";
int i = new Random().nextInt(27);
storeObject=store.getStores().getItems().get(i).getStore();
name= storeObject.getName();
resultStuff(name);
Log.i("StoreTag","storeval:"+name); //returns name of the 0th item
return name;
}//end of doInBackground() method
protected void onPostExecute(String name) {
// TODO Auto-generated method stub
Intent intent=new Intent("android.appwidget.action.APPWIDGET_UPDATE");
PendingIntent pendingIntent=PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setTextViewText(R.id.text_view,resultStuff(name));
updateViews.setOnClickPendingIntent(R.id.next, pendingIntent);
AppWidgetManager manager = AppWidgetManager.getInstance(context.getApplicationContext());
manager.updateAppWidget(thisWidget, updateViews);
}//end of PostExecute
}//End of async task class
}//end of ListViewWidget class
What I am missing here? Please please guide..
UPDATE: Is this fine? Async task to be called both in onReceive and onUpdate??
#Override
public void onReceive(Context context,Intent intent){
if(intent.getAction().equals("android.appwidget.action.APPWIDGET_UPDATE")){
fetchTask.execute();
}
}
Update 2:
public static String name="New text"
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
updateViews = new RemoteViews(context.getPackageName(), R.layout.list_layout);
//-----------NEW LINE ADDED-------------
updateViews.setTextViewText(R.id.text_view,name);
thisWidget = new ComponentName(context, ListViewWidget.class);
//Now in onPostExecute()
//AppWidgetManager manager = AppWidgetManager.getInstance(context.getApplicationContext());
//manager.updateAppWidget(thisWidget, updateViews);
fetchTask.execute();
}
protected void onPostExecute(String name) {
// TODO Auto-generated method stub
Intent intent=new Intent("android.appwidget.action.APPWIDGET_UPDATE");
PendingIntent pendingIntent=PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setTextViewText(R.id.text_view,name);
updateViews.setOnClickPendingIntent(R.id.next, pendingIntent);
AppWidgetManager manager = AppWidgetManager.getInstance(context.getApplicationContext());
manager.updateAppWidget(thisWidget, updateViews);
}
#Dororo Didn't get you. Please explain. I have created public var in my class:
public static Context context;
public static RemoteViews updateViews;
public static ComponentName thisWidget;
FetchTask fetchTask=new FetchTask();
Have you tried using this:
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(toThis);
Are you sure you're not overwriting the updated value when you create new ComponentName(context, ListViewWidget.class);? onUpdate will be called when you call manager.updateAppWidget(thisWidget, updateViews); You shouldn't need to use static, you just need an initialisation boolean which is set to true after you've created the objects for the first time.
Solved my exception and error. Was setting context to be null. I assigned context with the application context.
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.
I respond to a button press on my appwidget in the onreceive method. When the button I pressed, I want to force the widget to call the onupdate method. How do I accomplish this?
Thanks in advance!
Widget can't actually respond to clicks because it's not a separate process running. But it can start service to process your command:
public class TestWidget extends AppWidgetProvider {
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++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch UpdateService
Intent intent = new Intent(context, UpdateService.class);
PendingIntent pendingIntent = PendingIntent.getService(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.appwidget_provider_layout);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current App Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public static class UpdateService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//process your click here
return START_NOT_STICKY;
}
}
}
You should also register the new service in your manifest file:
<service android:name="com.xxx.yyy.TestWidget$UpdateService">
You can find another example of UpdateService implementation in Wiktionary sample in SDK
And here's another good approach Clickable widgets in android
This is kinda crude, but it works rather well for me, as I've found no directly-implemented way to force an update.
public class Foo extends AppWidgetManager {
public static Foo Widget = null;
public static Context context;
public static AppWidgetManager AWM;
public static int IDs[];
public void onUpdate(Context context, AppWidgetManager AWM, int IDs[]) {
if (null == context) context = Foo.context;
if (null == AWM) AWM = Foo.AWM;
if (null == IDs) IDs = Foo.IDs;
Foo.Widget = this;
Foo.context = context;
Foo.AWM = AWM;
Foo.IDs = IDs;
.......
}
}
Now, anywhere I want to force the widget to update, it's as simple as:
if (null != Foo.Widget) Foo.Widget.onUpdate(null, null, null);