欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-05 11:50:41
...

 

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.