Android 开机自动启动一个Service
本帖最后由 zhaohuarong 于 2018-2-2 14:53 编辑最近在做一个语音识别的程序,该程序应该是没有界面的,随着系统的启动而开始运行,生命周期伴随着整个系统的周期,永远在后台运行,因此需要做一个Service一直运行。
下面简单的介绍一下。首先是AndroidManifest.xml
添加权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
申明类:
<receiver android:name=".BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
<service android:name=".AiService">
<intent-filter>
<action android:name="com.caratech.ai.aiservice" />
</intent-filter>
</service>
新建两个类
BootBroadcastReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, AiService.class);
context.startService(service);
}
}
AiService.java
import android.app.Service;
import android.content.Intent;
public class AiService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
页:
[1]