如何使Android应用开机时自动启动
如果需要在Android开机时自动启动应用程序,可以通过响应android.intent.action.BOOT_COMPLETED广播消息来实现, Android系统启动结束时,会发出 android.intent.action.BOOT_COMPLETED 消息。 具体步骤如下:
1. 定义一个Broadcast Receiver ,比如:BootupReceiver
[java]
public class BootupReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//better delay some time.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(context, BootupDemoActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
public class BootupReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//better delay some time.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(context, BootupDemoActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
用于响应android.intent.action.BOOT_COMPLETED。
2. 在Manifest文件中定义该Broadcast Receiver
<receiver android:name=”.BootupReceiver” android:enabled=”true”
android:permission=”android.permission.RECEIVE_BOOT_COMPLETED”>
<intent-filter>
<action android:name=”android.intent.action.BOOT_COMPLETED”></action>
<category android:name=”android.intent.category.DEFAULT” />
</intent-filter>
</receiver>
3. 加上所需权限
<uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED” />
这些,但手机重启示会自动运行你的应用。 不过此时你的应用可能会被屏幕锁定挡住。解除屏幕锁定后可以看到你运行的应用。
如果想用户一开机就看到你的应用,可以使用代码就屏幕锁去除,方法如下:
1. 在Activity的onCreate事件处理中添加下面代码
[java]
KeyguardManager keyguardManager
= (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
KeyguardManager keyguardManager
= (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
2. 在Manifest文件中添加所需权限
<uses-permission android:name=”android.permission.DISABLE_KEYGUARD” />
本例代码下载:/2012/0518/20120518113514147.zip
摘自 引路蜂移动软件
补充:移动开发 , Android ,