原先我是利用startservice启动一个服务(继承自service)时出现了个错误,报错信息为在点击事件中耗时5秒以上。所以改用intent service试试
继承intent service,系统会给我们实现两个方法
public class BLEService2 extends IntentService {
private String TAG = "BLEService2";
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public BLEService2(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i(TAG, "onHandleIntent: ");
}
}
直接启动的话会报以下错误!
image.png
大概意思就是
can't instantiate class com.example //无法实例化
Unable to instantiate service //无法实例化service
no empty constructor // 没有空构造函数
报错信息推断出IntentService需要一个无参的构造方法来,来进行初始化。所以出现java.lang.RuntimeException: Unable to instantiate service
以上系统提供的构造name属性 解释为
Used to name the worker thread, important only for debugging
翻译:用于命名工作线程,仅对调试很重要
所以在这里我们写一个构造,按要求写一个试试,修改如下
public class BLEService2 extends IntentService {
private String TAG = "BLEService2";
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public BLEService2() {
super("testService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i(TAG, "onHandleIntent: ");
}
}
image.png
修改完之后生命周期可以正常运行了~,接下来继续踩坑...
本文到此结束
不要忘记在清单文件中注册服务
<application
android:name=".application.MainApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".activity.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".receiver.BLEReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".service.BLEService" />
<!-- name:service路径
enabled:表示系统是否能够实例化该组件
exported:表示该服务是否能够被其他应用程序组件所调用或者交互
-->
<service android:name=".service.BLEService2"
tools:ignore="Instantiatable" />
</application>
网友评论