从活动上下文外部调用startActivity()需要FLAG_ACTIVITY_NEW_TASK

时间:2014-04-20 13:11:03

标签: android

我正在尝试在服务类中启动一个活动。我有以下代码:

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);
}
}

它在onStartCommand()的以下行上给出了异常:

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

3 个答案:

答案 0 :(得分:36)

试试这个。

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);

答案 1 :(得分:5)

@hariharan回答有效。但是,它也可以在第一种情况下不设置Intent.FLAG_ACTIVITY_NEW_TASK。更准确的答案是:

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);

答案 2 :(得分:0)

对于(Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P),从Intent.FLAG_ACTIVITY_NEW_TASK上下文外部调用startActivity()时必须添加Activity

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);