veiph
veiph

Reputation: 31

startService not starting when called in application context

startService isn't starting the service. I'm calling it from what should be the application context, but despite getting the console log message from just before startService, I don't get either of the ones from inside the service.

public class AntoxOnFriendRequestCallback implements OnFriendRequestCallback {

private static final String TAG = "im.tox.antox.TAG";
public static final String FRIEND_KEY = "im.tox.antox.FRIEND_KEY";
public static final String FRIEND_MESSAGE = "im.tox.antox.FRIEND_MESSAGE";

private Context ctx;

public AntoxOnFriendRequestCallback(Context ctx) {
    this.ctx = ctx;
}

@Override
public void execute(String publicKey, String message){
    Log.d(TAG, "Friend request callback");
    Intent intent = new Intent(this.ctx, ToxService.class);
    intent.setAction(Constants.FRIEND_REQUEST);
    intent.putExtra(FRIEND_KEY, publicKey);
    intent.putExtra(FRIEND_MESSAGE, message);
    this.ctx.startService(intent);
}
}

Here is the gist: https://gist.github.com/ollieh/ed93a647430645fd2ee0

AntoxFriendRequestCallback is called with getApplicationContext() at line 61 in ToxService

I see "Friend request callback" in the log from line 15 in AntoxFriendRequestCallback

I don't see "Constants.FRIEND_REQUEST" in the log from line 140 in ToxService, or "test" from line 20 in MainActivity.

If you want to see the full files, they are here: https://github.com/ollieh/Antox/tree/83eb974589a4664b2098bc0561fd0060960cfe22/app/src/main/java/im/tox/antox

Upvotes: 0

Views: 2537

Answers (2)

Sekhar Madhiyazhagan
Sekhar Madhiyazhagan

Reputation: 889

You have to make sure whether service is declared in "androidmanifest.xml" like:

<service
    android:name="[your service class]"
    android:enabled="true"
    android:icon="@drawable/ic_launcher" >
</service>

and

Intent intent = new Intent(this.ctx, ToxService.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//add this line
intent.setAction(Constants.FRIEND_REQUEST);
intent.putExtra(FRIEND_KEY, publicKey);
intent.putExtra(FRIEND_MESSAGE, message);
this.ctx.startService(intent);

Upvotes: 1

veiph
veiph

Reputation: 31

Found the problem. The startService was called earlier in the app with the DO_TOX intent, and in the bit of the service that handles that, there was an infinite loop intended to repetedly call something, but that was blocking any new startService()s from working as they get queued up and need the last to finish. I replaced the infinite loop with a ScheduledExecuterService, and now it works.

Upvotes: 1

Related Questions