开发者

Android Development - starting activity from service

I've got a bit of code which is listening for a message on a socket, and parsing data from the socket into an email to be sent. I'm able to create the intent, and set the FLAG_ACTIVITY_NEW_TASK flag on it, but yet, when i call startActivity(Intent.createChooser(intent, "Email"));

I get an AndoridRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

What confuses me on this is that I have explicitly called intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Am I missing something obvious here?

protected void doEmail(DataInputStream in)  throws IOException {
  String id = in.readUTF();
  createEmail(id);
}

protected void createEmail(String rawEmailString) {
  // need to get to, subject, body and path from string
  String[] stringArray = rawEmailString.split("~");
  Intent intent = prepareEmail(stringArray[0], stringArray[1], stringArray[2], stringArray[3]);
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(Intent.createChooser(intent, "Email"));
}

public Intent prepareEmail(String to, String subject, String body, String pathToAttachment){
  Intent intent = new Intent(Intent.ACTION_SEND);
  intent.putExtra(Intent.EXTRA_EMAIL, to);
  intent.pu开发者_运维百科tExtra(Intent.EXTRA_TEXT, body);
  intent.putExtra(Intent.EXTRA_SUBJECT, subject);
  intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(pathToAttachment));
  intent.setType("*/*");

  return intent;
}


The Intent you get back from createChooser() may not have your flag. Try adding it to the result of createChooser().

Note that:

  • Having a service pop up an activity is very unusual and should be able to be disabled by the user, as it can be very intrusive.

  • Having a service pop up a chooser is lousy UX. Do you honestly think your users are going to have any idea what is going on when this "Email" chooser dialog appears out of nowhere?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜