【发布时间】:2014-12-23 15:07:05
【问题描述】:
我想在安装应用时自动启动服务。启动后或设备启动后服务正常工作。那么,是否可以在安装应用程序后启动服务?
【问题讨论】:
标签: android android-service android-broadcast
我想在安装应用时自动启动服务。启动后或设备启动后服务正常工作。那么,是否可以在安装应用程序后启动服务?
【问题讨论】:
标签: android android-service android-broadcast
Google 将正确答案显示为第一次点击所以...您对此进行了一些研究吗? How to start a Service when .apk is Installed for the first time
总结:你不能这样做。
【讨论】:
从技术上讲,安装应用时无法启动服务。可以从 Google Glass Development Kit 开始。可以选择通过 Voice 安装您的应用,也可以启动服务(Voice Trigger 命令)。
<service
android:name="com.est.poc.glass.service.POCGlassService"
android:enabled="true"
android:exported="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.google.android.glass.action.VOICE_TRIGGER" />
</intent-filter>
<!-- Voice command found in res/xml/voice_trigger_start -->
<meta-data
android:name="com.google.android.glass.VoiceTrigger"
android:resource="@xml/voice_trigger_start" />
<meta-data
android:name="com.google.android.glass.voice_trigger"
android:resource="@string/voice_trigger_title" />
</service>
【讨论】:
是的,可以通过收听已安装包的广播来实现
这是你的广播
public class InstallBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = null;
if (intent != null) {
action = intent.getAction();
}
if (action != null && Intent.ACTION_PACKAGE_ADDED.equals(action)) {
String dataString = intent.getDataString();
if (dataString != null
&& dataString.equals(YOUR_PACKAGE_NAME)) {
//Launch your service :)
}
}
}
}
这是你的清单
<receiver
android:name=".InstallBroadcastReceiver"
android:enabled="false"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
希望对你有所帮助;)
【讨论】: