2024年3月30日发(作者:)
Android Service如何开机自启动以及自启动失败原因
本文主要介绍
Android Service如何开机自启动;
自启动失败的原因;
adb命令发送BOOT_COMPLETED。
应用程序是否可以在安装后自启动,没有ui的纯service应用如何启动?
1、Android应用如何开机自启动
1:
package ;
import astReceiver;
import t;
import ;
public class BootCompletedReceiver extends BroadcastReceiver {
}
@Override
public void onReceive(Context context, Intent intent) {
if (ion().equals(_BOOT_COMPLETED))
{
// 开机启动的Activity
//Intent newIntent = new Intent(context, );
//注意,必须添加这个标记,否则启动会失败
//gs(_ACTIVITY_NEW_TASK);
//ctivity(newIntent);
// 开机启动的Service
Intent serviceIntent = new Intent(context, );
// 启动Service
ervice(serviceIntent);
}
}
2:
package ;
//import BarActivity;
import ty;
import ;
import ;
import em;
public class BootTestActivity extends Activity {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
}
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in .
int id = mId();
if (id == _settings) {
}
return onsItemSelected(item);
return true;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
}
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(_test, menu);
return true;
@Override
protected void onCreate(Bundle savedInstanceState) {
}
te(savedInstanceState);
setContentView(_test);
3:
package ;
import ;
import AccessFile;
import e;
import ;
import nment;
import r;
import ;
public class BootTestService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Service被启动时,将会有弹出消息提示[MyService onStart]
//xt(this, "[MyService onStart]", _LONG).show();
return START_STICKY;
}
}
4:
package="" android:versionCode="1" android:versionName="1.0" > android:minSdkVersion="8" android:targetSdkVersion="21" /> android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
2、自启动失败的原因
接收不到BOOT_COMPLETED广播可能的原因
(1)、BOOT_COMPLETED对应的action和uses-permission没有一起添加
(2)、应用安装到了sd卡内,安装在sd卡内的应用是收不到BOOT_COMPLETED广播的
(3)、系统开启了Fast Boot模式,这种模式下系统启动并不会发送BOOT_COMPLETED广播
(4)、应用程序安装后重来没有启动过,这种情况下应用程序接收不到任何广播,包括BOOT_COMPLETED、
ACTION_PACKAGE_ADDED、CONNECTIVITY_ACTION等等。
Android3.1之后,系统为了加强了安全性控制,应用程序安装后或是(设置)应用管理中被强制关闭后处于stopped状态,在这种
状态下接收不到任何广播,除非广播带有FLAG_INCLUDE_STOPPED_PACKAGES标志,而默认所有系统广播都是
FLAG_EXCLUDE_STOPPED_PACKAGES的,所以就没法通过系统广播自启动了。所以Android3.1之后
(1)、应用程序无法在安装后自己启动
(2)、没有ui的程序必须通过其他应用激活才能启动,如它的Activity、Service、Content Provider被其他应用调用。
存在一种例外,就是应用程序被adb push /system/app/下是会自动启动的,不处于stopped状态。
具体说明见:
/about/versions/#launchcontrols
/blog/2011/07/13/
3、adb发送BOOT_COMPLETED
可以通过发送命令:
adb shell am broadcast -a _COMPLETED
命令发送BOOT_COMPLETED广播,而不用重启测试机或模拟器来测试BOOT_COMPLETED广播,
这条命令可以更精确的发送到某个package,如下:
adb shell am broadcast -a _COMPLETED -c -n package_name/class_name
发布评论