您的位置:首页 > 移动开发 > Android开发

Android 在Service中调用Activity

2013-08-02 13:58 253 查看
前几天做一个小应用,需要用到在service中调用Activity, 但是发现总是出现ANR,百度了下,发现各种说法,不过经过尝试,发现问题不大,只需要加一句代码就足够了,代码如下:

public class XXXService extends Service {
	
	public void onCreate() {
		super.onCreate();
		//拨打电话
		Intent call = new Intent("android.intent.action.CALL", Uri.parse("tel:110"));
		call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		startActivity(call);
	}
}


关键语句是:call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 究其原因可能是android系统考虑到稳定性(容易出现ANR)。

可以看一下官方文档中对于startActivity()方法的描述:

Note that if this method is being called from outside of an Activity Context, then the Intent must include the FLAG_ACTIVITY_NEW_TASK launch flag. This is because, without being started from
an existing Activity, there is no existing task in which to place the new activity and thus it needs to be placed in its own separate task.

大致的意思是这样的:请注意,如果一个外部的Activity Context调用此方法,那么,Intent对象必须包含 FLAG_ACTIVITY_NEW_TASK标志,这是因为,待创建的Activity并没有从一个已经存在的Activity启动(任务栈中并没有此Activity),它并没有已经存在的任务,因此它需要被放置在自己独立的任务中(也就是在任务栈中新建一个任务)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: