I am working with an android project for which I want to create a widget. Using this widget I have to control some actions of the control (that is by pressing the stop button from widget the app should stop working of some action). For that I have to pass some value to app from the widget on a button click. So far I am able to do the following:
open an activity on button click
open an URL on button click
make a toast on home screen on button click
Any help is appreciated,thank you.
I have successfully completed this part of my project.There are two scenarios
When we are passing values the app will be launched. That is we are passing the values directly to an activity
With out launching the app we can pass the values.Here we are using service
In both situation we can use two method
Using sharedpreferences
Using Intent(putExtra())
If you want pass the value directly to an activity(the App will be launched while passing the value) you can use second method above mentioned and call the activity(which activity you wanted to be launched) as follows:
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
Intent intent = new Intent(context,MainActivity.class);
PendingIntent pendingIntent = PendingIntent(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.PunchIn, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
this code to launch MainActivity from widget button click. In Inten you can use putExtra() to pass values.better to not use sharedpreference here.
For passing value with out launchingthe app,you can call service from widget button then you can add whatever code you want to add in the service.class file. you can call the service as follows:
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
Intent intent = new Intent(context,MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.PunchIn, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
from this service class you can pass values to the application using SharedPrefernce or putExtra().
if you want to make a button widget which work same as button click of the app you can use second method. Here you can call a service on on button click as mentioned above, Then write code for the button click in the service class.
i am new to android,i worked with widget in my project for that researched a lot and it took lots of time. so thought about posting this which will help anyone like me. if you found any error/mistake please correct me.happy to correct my mistake.
Thank you
I'm not sure with this problem because I have not try widget yet.
When button click, send a boardcast message. And your app needs to run a service to receive the message. You can put your values in the message?
Wish this link may give you some ideas:
http://rxwen.blogspot.com/2012/10/communication-between-android-widget.html
There is a similar question:Android - Communications between a widget and its app
Good luck!
Related
I am using Android Studio for a simple communication app and this definitly might be a stupid question but I couldn't find the answer to it yet.
I am simply starting a new intent on a button click. However, the very first time the user does this, he is asked what kind of app he wants to use. Therefore, there are at least two applications with the same intent filter, namely "ACTION_VIEW"
My Problem:
After the initial click the button always "reuses" his initial choice so the user does not have a decision anymore which app he wants to use for this intent.
Unfortunately, this is excactly what I want. The user should get the chance to select the app of his favor each time he clicks on the button.
The relevant part of code is as simple as follows:
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
Intent.FLAG_UPDATE_CURRENT could probably help you.
https://developer.android.com/reference/android/app/PendingIntent.html
You can use an App Chooser to show the dialog for the user to choose which app to use each time:
[I]f the action to be performed could be handled by multiple apps and the user might prefer a different app each time—such as a "share" action, for which users might have several apps through which they might share an item—you should explicitly show a chooser dialog.... The chooser dialog forces the user to select which app to use for the action every time (the user cannot select a default app for the action).
Intent intent = new Intent(Intent.ACTION_SEND);
...
// Always use string resources for UI text.
// This says something like "Share this photo with"
String title = getResources().getString(R.string.chooser_title);
// Create intent to show chooser
Intent chooser = Intent.createChooser(intent, title);
// Verify the intent will resolve to at least one activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(chooser);
}
I have a litte appwidget with a configuration activity.
In the configuration activity I have a EditText
to store a particular string and a button to create the widget.
In the widget itself there is only a Imageview with a static image showing a button.
when i press the button im doing the following:
AppWidgetManager app_widget_manager = AppWidgetManager.getInstance(context);
RemoteViews local = new RemoteViews(context.getPackageName(), R.layout.main);
app_widget_manager.updateAppWidget(widget_id, local);
Intent create = new Intent(this, MyWidget.class);
create.setAction("com.test.mywidget.CREATE");
create.putExtra("toastmessage", edittext1.getText().toString);
context.sendBroadcast(create);
Intent result_value = new Intent();
result_value.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widget_id);
setResult(RESULT_OK, result_value);
finish();
the extra 'toastmessage' is just the content of the edittext.
in the widget i catch the broadcast in onReceive() and get the string value that was
passed before as extra 'toastmessage' to the new widget.
if i press on my widget, i create a toast with the passed string
- and here is my problem -
the passed string is different for every widget created.
but the variable (in the widget) where i store the passed string
gets resettet after a little time or when the phone gets restartet or the app killed or something similar,
so i need persistent data for every widget instance.
I need to store which widget got which string passed,
and get this data everytime when the widget gets updated.
How can i achieve this?
According with this link you have some options to accomplish your goal.
For shared preferences, here an example.
For internal storage Take this way.
For external storage, you can use this.
For SQL Lite storage, here.
Hope these examples helps, cheers.
The widget_id you received is a unique identifier of the widget instance. Use it as a key to identify your persisted data.
I'm writing an application which should be able to add widgets (just text boxes) to the home screen of the user's phone when the user instructs my app to do so. How can I do such a thing?
I know that I can add an app widget but how about adding more?
It is not possible from a app to place a widget in the home screen. Only the home screen can add app widgets to the home screen.
similar links link1, link2, link3
But you can offer user to pick widget from widgetpicker.
Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetID);
startActivityForResult(pickIntent, KEY_CODE);
This was answered a long time ago, but in case anyone stumbles upon this question I thought I should provide an up-to-date answer.
As of Android O (API 26), you can now pin widgets to the user's launcher from your app!
Simply create the widget in your app's AndroidManifest file and use AppWidgetManager to request that the widget be pinned to the launcher. Note that it is up to the launcher to support this feature, so you must call AppWidgetManager's isRequestPinAppWidgetSupported() method before requesting to pin it.
Here's some documentation from Google that goes into more detail: https://developer.android.com/preview/features/pinning-shortcuts-widgets.html#widgets
Hope this helps!
Edit: It looks like the documentation pages have changed since I posted this answer. Here is a more helpful link that gives a code example of how to pin a widget to a launcher: https://developer.android.com/guide/topics/appwidgets/#Pinning
Looks like Dalvik Droid's links are updated again, the newest link is at requestPinAppWidget
Example:
in MainActivity.java:
private void requestToPinWidget(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AppWidgetManager appWidgetManager =
getSystemService(AppWidgetManager.class);
ComponentName myProvider =
new ComponentName(this, AppWidget.class);
assert appWidgetManager != null;
if (appWidgetManager.isRequestPinAppWidgetSupported()) {
Intent pinnedWidgetCallbackIntent = new Intent(this, MainActivity.class);
PendingIntent successCallback = PendingIntent.getBroadcast(this, 0,
pinnedWidgetCallbackIntent, PendingIntent.FLAG_UPDATE_CURRENT);
appWidgetManager.requestPinAppWidget(myProvider, null, successCallback);
}
}
}
Any anywhere in you code you have call requestToPinWidget() to prompt to see if the user wants to add it to the desktop.
Only thing is that this will not add to user's home screen, it will be appended to the page where you see all the apps:
AFAIK default launcher app does not support this. The reason is that user should place everything on the home screen himself. Allowing to place widgets from an application would open doors for apps to "spam" user's home with their "useful" widgets.
I'm trying to port my iPhone Cocos2d game to Android using the Cosos2d for Android framework (Java).
I'm running into a problem when I start PreferenceActivity from my main activity. This is my setup:
(1) HelloWordActivity.java:
Inits the Cocos2d environment and starts GameLayer.scene
(2) Gamelayer.scene:
Presents the user with the game but also has a button to show the settingspane which gets called from the Gamelayer class like this:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName(helloworldactivity, ShowSettingsActivity.class.getName());
helloworldactivity.startActivity(intent);
This shows the Preference Activity just fine, but when closing the preferences and returning to my game it appears it did not persist (it get's reloaded/restarted and does not retain it's state).
How can I present the user with a standard Android preferences screen without destroying the current game session in Cocos2d ?
from the names of your classes , I'm assuming you used Dan's tutorial as a starter
make sure you remove dan's onStop() override method , that gets called when you are loading the preferences and it calls
CCDirector.sharedDirector().end();
removing this should do it for you
I did notice that you gave up and switched to andEngine , that's a nice engine too but I thought I'd answer this one anyway
You need to get the main activity to start new activity, I hope this code will help you
Activity context = CCDirector.sharedDirector().getActivity();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName(helloworldactivity, ShowSettingsActivity.class.getName());
context.startActivity(intent);
I am making a keyboard ( InputMethodService ), which needs to launch a dialog.
As I found out, a service can not launch a dialog. So I made a separate activity which is called from the service by
Intent dialogIntent = new Intent(getBaseContext(), dialog.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dialogIntent);
and show a dialog. The problem is that this activity replaces the previous one, where the user was typing something.
What do you think would be the best way to make it "transparent" ( i.e. not to push away the previous activity ) and also what would be the best way for this activity to talk back to the service, saying that dialog option was picked.
Thanks! :)
If this is an Activity (not a Dialog), you can add a dialog theme in the activity section of your AndroidManifest:
android:theme="#android:style/Theme.Dialog"
As for getting back what the user pressed, you should use startActivityForResult(...)
You should NOT launch an activity from an IME. This is a huge break in the IME flow -- the activity comes along and does an app switch from the current app, taking focus from it, and breaking your connection with its current editor.
Also there is no way to get a result back from it, because you can only use startActivityForResult() from an activity.
To show a Dialog in your IME, just use Dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG before showing the dialog.
To resume in code what have been said, let me share some code for those who need to test the solution:
// 1. CREATE THE DIALOG
val builder: AlertDialog.Builder = AlertDialog.Builder(this, R.style.Theme_AppCompat_Light)
builder.setTitle("Title").setMessage("This is the message for the user. ")
val mDialog = builder.create()
// 2. SET THE IME WINDOW TOKEN ATTRIBUTE WITH THE TOKEN OF THE KEYBOARD VIEW
mDialog.window?.attributes?.token = this.mKeyboardView.windowToken
// 3. SET THE TYPE OF THE DIALOG TO TYPE_APPLICATION_ATTACHED_DIALOG
mDialog.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG)
// 4. SHOW THE DIALOG
mDialog.show()