Vikalp
Vikalp

Reputation: 2161

Calling startActivity() from outside of an activity context requires the FLAG_ACTIVITY_NEW_TASK

I am trying to start an activity inside a service class. I have a following code:

public class SendLinkService extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Bundle bundle = intent.getExtras();
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT, bundle.getString("URL"));
    getApplicationContext().startActivity(Intent.createChooser(shareIntent, "Share via"));
    return super.onStartCommand(intent, flags, startId);
}
}

It gives exception on following line of onStartCommand() :

getApplicationContext().startActivity(Intent.createChooser(shareIntent, "Share via"));

Upvotes: 13

Views: 21277

Answers (3)

Hrishikesh Kadam
Hrishikesh Kadam

Reputation: 37342

For (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) it is mandatory to add Intent.FLAG_ACTIVITY_NEW_TASK while calling startActivity() from outside of an Activity context.

Docs

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, bundle.getString("URL"));
Intent new_intent = Intent.createChooser(shareIntent, "Share via");
new_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
getApplicationContext().startActivity(new_intent);

Upvotes: 2

vedi
vedi

Reputation: 400

@hariharan answer works. However it also work without setting Intent.FLAG_ACTIVITY_NEW_TASK in the first case. More accurate answer is:

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, bundle.getString("URL"));
Intent new_intent = Intent.createChooser(shareIntent, "Share via");
new_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
getApplicationContext().startActivity(new_intent);

Upvotes: 6

Hariharan
Hariharan

Reputation: 24853

Try this.

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, bundle.getString("URL"));
Intent new_intent = Intent.createChooser(shareIntent, "Share via");
new_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
getApplicationContext().startActivity(new_intent);

Upvotes: 37

Related Questions