当前位置: 代码迷 >> Web前端 >> 开机后自动启动Activity中急需注意的
  详细解决方案

开机后自动启动Activity中急需注意的

热度:260   发布时间:2012-08-25 10:06:20.0
开机后自动启动Activity中需要注意的

?

public class StartupReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			System.out.println("接受到广播");
//			Intent _intent = new Intent(context,OtherActivity.class);
//			_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			Intent _intent = new Intent();
			_intent.setAction("com.michael.TEST");
			_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(_intent);
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

?

?

注:context.startActivity(_intent); 需要加上Flag:_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

?

?一种是显式?new Intent(context,OtherActivity.class);

?注:一种是隐式_intent.setAction("com.michael.TEST");

?隐式的intent-filter 需要加上 <category android:name="android.intent.category.DEFAULT" />

?

?

 <activity android:name=".OtherActivity" >
            <intent-filter >
                <action android:name="com.michael.TEST" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
 </activity>

最容易忽略的就是: 测试代码是否正确。 要先运行程序在虚拟机。 然后重启系统!!!才能验证结果。第一次运行是不会验证的。

?

?

?写道
下面是为什么需要设置:android.intent.category.DEFAULT
In principle, therefore, an Intent object with no categories should always pass this test, regardless of what's in the filter. That's mostly true. However, with one exception, Android treats all implicit intents passed to?startActivity()?as if they contained at least one category: "android.intent.category.DEFAULT" (the?CATEGORY_DEFAULT?constant). Therefore, activities that are willing to receive implicit intents must include "android.intent.category.DEFAULT" in their intent filters. (Filters with "android.intent.action.MAIN" and "android.intent.category.LAUNCHER" settings are the exception. They mark activities that begin new tasks and that are represented on the launcher screen. They can include "android.intent.category.DEFAULT" in the list of categories, but don't need to.) See?Using intent matching, later, for more on these filters.)
下面是为什么要设置:FLAG_ACTIVITY_NEW_TASK
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.
1 楼 silentJesse 2012-03-16  
good good
  相关解决方案