启动服务时收到NPE。我刚看完android开发者网站上的服务教程。
日志显示无法恢复活动…
@Override
protected void onResume() {
super.onResume();
CustomIntentService cis = new CustomIntentService();
Intent intent1 = new Intent(this, CustomIntentService.class);
intent1.putExtra("NUM", 1);
cis.startService(intent1);
}
我的服务是:
public class CustomIntentService extends IntentService {
private final static String TAG = "CustomIntentService";
public CustomIntentService() {
super("CustomIntentService");
Log.d(TAG,"out CustomIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent");
Log.d(TAG, "service num = " + intent.getIntExtra("NUM", 0));
if (Looper.getMainLooper() == Looper.myLooper()) {
Log.d(TAG, "In main ui thread");
} else {
Log.d(TAG, "In worker thread");
}
}
}
将onResume的代码修改如下:
@Override
protected void onResume() {
super.onResume();
//CustomIntentService cis = new CustomIntentService();
Intent intent1 = new Intent(this, CustomIntentService.class);
intent1.putExtra("NUM", 1);
startService(intent1);
}
这应该可以解决这个问题,记住intent知道要启动哪个服务,startService()是根据上下文调用的。这里activity的实例就是context。
,
因为Service是一个组件,所以你应该在androidmanifest文件中声明它
<service
android:name=".CustomIntentService">
</service>
*注意:CustomIntentService应该在当前目录下,或者你也可以提供绝对路径。
你可以参考