[Android初级]BroadReceiver之自启动应用

在如今应用app的使用中,几乎每个应用都有自动启动的功能,实现原理就是通过监听android的启动广播,对其运行相应的服务(activity或者service)。

如下是对系统启动后,简单的启动一个网页的代码。


1.定义BootBroadcastReceiver类:

public class BootBroadcastReceiver extends BroadcastReceiver {
	static final String BOOT_ACTION = "android.intent.action.BOOT_COMPLETED";
	
	@Override
	public void onReceive(Context context, Intent intent) {
		if(intent.getAction().equals(BOOT_ACTION)){
			Log.i("info", "收到系统启动广播");
			Intent bootIntent = new Intent();
			intent.setClass(context, BootStartDemo.class);
			bootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(bootIntent);
		}
	}
}

2.在AndroidManifest.xml注册这个类:

 <receiver android:name=".BootBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>

3.测试你的类吧:

public class BootStartDemo extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_boot_start_demo);
		Uri uri = Uri.parse("http://wap.baidu.com/s?word=" + "apple");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        startActivity(intent);
	}
}


你可能感兴趣的:([Android初级]BroadReceiver之自启动应用)