How can I fire a method instead of an Activity in my code?
I want to use the AddProximityAlert() method from the LocationManager but it needs an Intent to work and I don't want to call another activity since the method I want to fire is in the same Activity from where I'm using AddProximityAlert()
Goes like this:
public clase onCreate()
{
......
LocationManager LM; // already initialized
LM.addProximityAlert(lat,long,radio,expiration,INTENT) <--- This INTENT needs to call myMethod()
}
public void MyMethod()
{
.......
}
I have several hours trying to find a solution for this, and all I find is for calling another activity, please be as much specific, even if I have to do something with the manifest.xml because I haven't used intents before.
Thanks
What if you create a android service (or broadcast receiver might be more appropriate) within the same application that handles the intent.
You don't leave the same pid, it's a non-visual service and you never leave your activity?
You can call your service directly by creating a intent the references it's class name directly.
intent = new Intent(context, my_service.class);
It then will hit the services "onStartCommand()" function and you can do your intent processing from there.
Related
I get intent for push or custom scheme in A activity.
I'm handling them in onResume.
It seems the intents are not disposed unless explicitly told.
I start an activity for intents, and when I close the started activity, it keeps restarted (I suspect this is due to the living intents)
How should I dispose them?
Are there better way of handling for example, push intent?
(without the need to disposing them?)
--- edit
I think my problem is due to the way I handle push, (or scheme)
GcmIntentService creates notification which would start a MainActivity
MainActivity then look at args and starts appropriate activities.
I guess the more conventional way is to go from GcmIntentService to appropriate activities directly?
Try putting this inside onCreate() method of your MainActivity.java :
if (savedInstanceState == null) {
final Intent launchIntent = new Intent(MainActivity.this, AnotherActivity.class);
startActivity(launchIntent);
}
If the activity is already created, rather put this inside onStart() method.
I want to start a service in a static way. So from my activity I call
SpeechActivationService.makeStartServiceIntent(
this.getApplicationContext(),
"WordActivator");
Here is the actual class that extends from service class http://dpaste.com/hold/928115/ As you can see there are several log points, e.g. in the onCreate method.
This is not logged. Only if I put log text in makeStartServiceIntent method it appears, however not in the onCreate method.
Here's the makeStartServiceIntent method:
public static Intent makeStartServiceIntent(Context context,
String activationType) {
Intent i = new Intent(context, SpeechActivationService.class);
i.putExtra(ACTIVATION_TYPE_INTENT_KEY, activationType);
return i;
}
In manifest file I have
<service android:name="root.gast.speech.activation.SpeechActivationService"/>
Any ideas why the service is not started?
Aside from you not posting code showing startService(), it looks like the package name of your Service in the manifest doesn't match your SpeechActivationService class (assuming the code link you posted is the actual SpeechActivationService class in your project, and not just a class you copied from).
<service android:name="com.mkyong.android.SpeechActivationService"/>
Your makeStartService() just creates an Intent for you. You don't seem to actually be firing that intent off to start the service. Try like this
Intent i = SpeechActivationService.makeStartServiceIntent(this,"WordActivator");
startService(i);
Note that if this.getApplicationContext() works you are likely already inside of a Context object so simply using this should work also.
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);
}
}
}
I need to receive a broadcast event inside a broadcast receiver and than pass this information to an activity that is already open. How can I inform the activity from the broadcast receiver without it getting recreated? This causes a total refresh which is not needed.
Now I could receive intent inside a broadcast receiver that is declared within the activity, but I also need to receive the intent when its in background as well, hence the main place I am processing the intents is in a separate broadcast receiver. So I just don't know how to inform the activity that a new intent has arrived without onCreate() getting called and re-init the whole UI.
I think I need the NEW_TASK flag or it won't run.
PS: What are these insane downvotes about. What could be more relevant than how to start an activity from a broadcast receiver in such a way as not to recreate the activity. BTW, I am going to find an answer w/wo you. Why the bitter downvotes? I suspect it is because you know I could use an answer. Well I'll probably be posting an answer to this great question myself quite soon.
if you want to recreate this activity do this:
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if don't want to recreate , just do this:
while this activity on your task's top,intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
declare the actvity in the manifest with: android:lauchMode= "singleTask";
And the answer is .....
declare the Activity in the manifest with
android:launchMode="singleTop"
Still would like feedback on this answer as I notice that in onResume() the intent does not seem to carry over the values as it did before. So I cannot pull out values that I set on the intent inside the broadcast receiver ...
Update: In order to get the values from the receiver you may need to do the following inside the Activity:
#Override
public void onNewIntent(Intent intent)
{
setIntent(intent);
}
How can I send data from a Service to an Activity? Broadcast receiver? Handlers? Intent? I have several Strings in particular that I would like to send from Service to an Activity, so that I can then display some View to the user.
getApplication().startActivity(new Intent()) ?
Since both Activity & Service is in same application. Instead of going for Service Binder IPC, try implementing register callBack mechanism. Try follow below step.
-> Make a static class which extends from class Application to make quick reference anywhere in your application.
-> Register a callBack from Activity to this application class.
-> Post event from your service to the application class and let Application class deliver the event to all register callBacks.
As #justin-shield mentioned the best way is to use some form of IPC. I don't think you need to use AIDL, however. You can see another answer I gave to a similar question that outlines the basic steps to register Handlers and Messengers in your Activity and your Service.
I think all your answers are way more complex than what I need. I think I have come up with a rather simple solution (psuedo-code):
Service:
Intent i = new Intent(this,Activity.class);
i.putExtra(name,value);
startActivity(i);
Activty:
private Intent intent;
private String s1;
from the onCreate(Bundle savedInstanceState)
{
super(savedInstanceState);
intent = this.getIntent(); //Gets the intent that started this Activity.
s1=intent.getExtras().getString(name);
}
Would I use same code in onStart() ? What about onResume() ? onRestart() ? Lastly, I only want to send to the Activity some data to publish via some View objects, I don't need any communication going back to the Service.