Launch an Activity on the first launch of a widget - android

I would like to launch an Activity, when the user adds the widget on the launcher.
How can I do that ?
The onReceive method is called too often.
And with onEnabled, it simply doesn't launch.
How can I do that ?
Tkx

I'm not sure on this, I havne't done a widget yet, but I think when you create a widget, the widgets onCreate() method gets called. Try placing your startActivity(Intent) in there and see if that works.

Widget Doesn't have a OnCreate() method. Instead it has a onEnabled() Method.
#Override
public void onEnabled (Context context){
super.onEnabled(context);
Toast.makeText(context, "Launching Config Activity", Toast.LENGTH_SHORT).show();
//Launching the Widget Config Activity on creating widget first time
myIntent = new Intent(context, ConfigActivity.class);
//Needed because activity is launched from outside another activity
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myIntent.putExtra("WIDGET_SIZE", "default");
context.startActivity(myIntent);
}
Remember you need to add the widget to the home screen using code after the configuration is complete with necessary changes.
Refer more here:
http://developer.android.com/guide/topics/appwidgets/index.html

Related

Close PreferenceFragment after widget configuration complete

I am using a PreferenceFragment to configure my widget when it is added to the home screen. After the user has edited the preference to their likings, how can I close the preference fragment so the widget can then be added based on the settings?
I was thinking of using an "Add Widget" preference at the bottom of the fragment, and adding an onClickListener. But am at a loss as what to do programmatically after the user clicks this. I was thinking something like a finish() method, but this only works on Activities.
All help is greatly appreciated.
As per the App Widgets guide: You must create an Intent, add the app widget Id as an extra (with the AppWidgetManager.EXTRA_APPWIDGET_ID key), call setResult and finish. If it's a fragment, use getActivity() to call these methods on the Activity.
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, result); // or getActivity().setResult(RESULT_OK, result);
finish(); // or getActivity().finish();

Android how to open Activity when open home screen widget?

I am implementing an app related to widgets in this I prepared one widget and that's working perfectly and when click on views that opens the activity to prepare settings for that widget.
But my requirement is when click on home screen widget I want to open directly activity and then widget.
From the above picture when click on Custom Analog Clock widget open first Activity in my application and then I want to show the widget because from my activity I will setup some settings for that widget. How can I open activity first?
Widgets can have a special activity called when they are added to the home screen. That activity can return a SUCCESS intent with the widget ID receive in the "onCreate" method of the activity or RESULT_CANCELED if you want to prevent the creation of the widget itself.
You just need to add the configure activity class in a android:configure attribute at the appwidget-provider XML and add an intent filter with android.appwidget.action.APPWIDGET_CONFIGURE to your activity declaration at the AndroidManifest. It's detailed in http://developer.android.com/guide/topics/appwidgets/index.html#Configuring
The intent received has the widget ID:
public void onCreate(Bundle savedInstanceState) {
...
int widgetID = getIntent().getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
...
}
and then you can either finish your activity with setResult(RESULT_CANCELED); or confirm the widget creation with:
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID);
setResult(RESULT_OK, resultValue);
You can do all your widget settings from that activity.
On the other hand, if you want to perform other setup that only needs to occur once for all your widgets instances, you can make then in the onEnabled method of your AppWidgetProvider class as described in http://developer.android.com/guide/topics/appwidgets/index.html#AppWidgetProvider
You should check out this tutorial: http://android-er.blogspot.nl/2010/10/simple-home-screen-app-widget-with.html It does exactly what you want.

android: hiding and destroying activity started from a service

I'm new to Android development. I am trying to monetize a live wallpaper that I built and the ad delivery company wants me to call their code from the onCreate of an activity.
The live wallpaper didn't have an activity before I started to monetize it, being an extension to WallpaperService, so I've added one. I've managed to create the activity and make it translucent, but it doesn't close when the dialog closes. I cannot edit the dialog code since it is being created by a call into a .jar, so I thought I could setup a listener for when the dialog is dismissed, but I wasn't able to find any practical examples that might help with the code below.
LWP.java
public class SBLiveWallpaper extends WallpaperService {
super.onCreate();
Intent i = new Intent();
// i.setClass(this, MainActivity.class);
i.setComponent(new ComponentName("appname", "appname.MainActivity"));
// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
activity_main.xml has no elements (just the RelativeLayout)
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppBucksAPI.initialize(this, APPID, "APIKEY", true, null, null);
AppBucksAPI.userOptOutDialog(this, "marketname");
}
I could make the activity be non-transparent, and just add a close button, but that is ugly and confuses users.
Edit for clarification: I had tried originally to call the dialog directly from the service's onCreate(). It causes the LWP to crash in the screen where you can make it the active LWP. The error I get is android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application.
I contacted AppBucks support before making the original post here. Their response (pasted below) prompted me to create the translucent activity.:
I believe this error means that there is a problem with the first parameter you are passing to the AppBucksAPI.userOptOutDialog method… the call which looks like this from the docs:
AppBucksAPI.userOptOutDialog(this, "<App Name>");
This call expects an Activity or Activity context as the first parameter. It needs this because our default opt out dialog uses an AlertDialog call, which requires an active Activity for it to display correctly. If you are already creating an Activity along with your service, you should pass that activity as the first parameter instead of “this” (or you could move this call to the onCreate of that activity instead of onCreate for the service).
If you don’t have an Activity in your app, I found this StackOverflow question which has an answer that may help (in a nutshell, you can create a transparent activity when your service starts up, and make the userOptOutDialog call from that instead of your service’s onCreate method):
Display AlertDialog as system overlay window from Service
Unfortunately, the above article covers creating the activity and closing the dialog under the assumption that the person reading it has access to the dialog's code. Since I do not have access to that, because it is imported into my project as a library, I need to know how to listen, from the parent activity, for the child to finish.
I did some digging and it looks like either of these could work, depending on how the activity is started from the dialog call my code makes:
http://developer.android.com/reference/android/app/Activity.html#finishActivityFromChild(android.app.Activity, int)
or
http://developer.android.com/reference/android/app/Activity.html#finishFromChild(android.app.Activity)
I'll give those a try tonight.
The AppBucks SDK also exposes the following functions:
setIconAdsEnabledForUser
setPushAdsEnabledForUser
The AppBucksAPI.userOptOutDialog is basically a convenience function that wraps calls to these in an AlertDialog. For your app, it probably makes more sense to forego the convenience function and write your own AlertDialog that calls the enable functions directly. That way you will have full control over what happens when the dialog is dismissed and can close the new activity you created when you need to.
Looking at the AppBucks API and documentation, I don't think using an Activity is mandatory. It is just the most common way.
I think you can call AppBucks method in your service onCreate as well?
When dismissing your dialog, send an intent to your activity for it to close itself.
For instance
Put this in the dialog dismiss method:
sendBroadcast(new Intent(MainActivity.ACTION_TERMINATE));
Then in the MainActivity add and register a BroadcastReceiver:
Add fields for the receiver and the filter in the activity:
private ActivityBroadcastReceiver mReceiver;
static final IntentFilter mFilter = new IntentFilter();
static {mFilter.addAction(ACTION_TERMINATE);}
Instantiate it in onCreate():
mReceiver = new ActivityBroadcastReceiver();
Register it in onResume():
registerReceiver(mReceiver, mFilter);
Unregister it in onPause():
unregisterReceiver(mReceiver);
And the broadcast receiver's inner class in the activity would look like this
private class ActivityBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
if (ACTION_TERMINATE.equals(action)) {
finish();
}
} catch (Exception e) {
Log.w(mTag, "Oops: " + e, e);
}
}
}

clear Activity Stack when user Logs in

There are a lot of topics on this post. But i couldn't find a solution to my problem.
Let me describe my activity stack first.
SplashScreen->A->Login->Home.
What i would like to achieve is , when i click on back button after logging in to Home, i should come out of the application and go to Home if i use my application again. For this i am assuming i should clear the activity stack before Home, after i login. I would also like to preserve the activity stack if the user hasn't logged in yet.
I want this to work on or after 2.1
What i have tried already.
using finish() in Login Activity , before calling startActivity on Home. This will redirect me to A , if i use back button on Home.
All variations of FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TOP . Nothing worked, when i use back button, i am redirected to login screen.
Any suggestions or simple solution to achieve this?
using finish() in Login Activity , before calling startActivity on Home. This will redirect me to A , if i use back button on Home.
ok so use finish on all the activities that you want them to be popped before calling startActivity
go to Home if i use my application again
Simply save your login parameters in SharedPreference and from A startActivity Home directly if login successful.
You can also try to make use of BroadcastReceiver aswell if you want to try that route.
In your "SplashScreen" and "A" activities, in the onCreate method you can create and register and IntentFilter and a BroadcastReceiver like so:
Assuming you have a global variable called broadcastReceiver
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("ACTION_LOGIN");
this.broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
registerReceiver(broadcastReceiver, intentFilter);
Also don't forget to unregister your receiver in the onDestroy method (this is to prevent memory leaks in the program):
#Override
protected void onDestroy() {
unregisterReceiver(this.broadcastReceiver);
super.onDestroy();
}
Now in your "Login" activity, once the user has successfully logged in, you can broadcast a message to all the registered receivers, which will finish those activites in the back stack:
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("ACTION_LOGIN");
sendBroadcast(broadcastIntent);
Your SplashScreen and A activities will now be finished.

how to call a service from an activity?

I have a service which starts an activity by
Intent dialogIntent = new Intent(getBaseContext(), dialog.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dialogIntent);
But I'm not sure how to pass a call when this new activity finishes to the service?
Note that "startActivityForResult" does not work from a service. ;)
On the other hand, maybe there is some "when focus comes back" listener for the service?
Thanks!
edit:
activity finishes by
Intent dialogIntent = new Intent(getBaseContext(), TotalKeyboard.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dialogIntent);
finish();
yet this, in service, doesn't get the call
#Override public void onStart(Intent intent, int startid)
{
Toast.makeText(getApplicationContext(), "aaa!", Toast.LENGTH_SHORT).show();
}
when you try to start service which is already running then it's onCreate method does not get the call but it's onStart() methods gets the call......you can use this property to meet your need...
You never get foucs on a Service. I'm not sure what you are trying to achieve, and maybe this is not the best solution but you can bound from you Activity to the Service and declare a method in your Service class and then you can call that method from your Activity, after you are bound to your service.
EDIT: You can simulate a dialog show from a Service by creating an Activity that looks like a dialog. You can do this by setting the theme attribute in your AndroidManifest.xml:
<activity
android:name="myPackages.ui.DialogActivity"
android:theme="#android:style/Theme.Dialog"
android:launchMode="singleInstance"
android:excludeFromRecents="true"
android:finishOnTaskLaunch="true" />
You can declare a method in your Service let's say:
public void performAction(boolean userChoice){
//implementation
}
and in your DialogActivity class you can bound to your Service class and on the press of a button you can call :
mBoundService.performAction(true);
or
mBoundService.performAction(false);
based on the user choice.
In Short , Activity itself has to take care of this.

Categories

Resources