【发布时间】:2011-06-02 00:39:57
【问题描述】:
我在 DDMS 中尝试使用 MyActivity 上的 CheckBox 来启动名为“MyService”的服务时看到以下错误:
W/ActivityManager( 73): Unable to start service Intent { cmp=com.example.android.myprogram/.MyService }: not found
我使用了教程 http://developer.android.com/resources/tutorials/views/hello-formstuff.html 并将提供的代码添加到我的 onCreate() 方法的末尾。我在 MyActivity.java 和 MyService.java 中分别指定了类。
package com.example.android.myprogram;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
public class MyActivity extends Activity {
private static final String TAG = "MyActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now checked
if (((CheckBox) v).isChecked()) {
// TODO: Add code to START the service
Log.d(TAG, "startService from checkbox");
startService(new Intent(MyActivity.this, MyService.class));
} else {
// TODO: Add code to STOP the service
Log.d(TAG, "stopService from checkbox");
stopService(new Intent(MyActivity.this, MyService.class));
}
}
});
}
}
我的清单文件确实包含以下内容,其中我还尝试了完整的命名空间、短名称、在每次搜索时使用意图过滤器等。我并不是说什么是正确的。我只是把它停在了一个地方。
<service android:name=".MyService">
<intent-filter><action android:name="com.example.android.myprogram.MyService"></action>
</intent-filter>
</service>
最后,我决定将我的服务分解到最低限度:
package com.example.android.myprogram;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate");
//code to execute when the service is first created
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
//code to execute when the service is shutting down
}
@Override
public void onStart(Intent intent, int startid) {
Log.d(TAG, "onStart");
//code to execute when the service is starting up
}
}
我对 Java/Android 编程和一般编程(但正在学习)非常、非常、非常陌生,所以我确信这是用户错误,可能是其他所有人的常识。任何建议都会很棒。
【问题讨论】:
-
您能粘贴服务的代码吗?
-
克里斯蒂安,感谢您的回复。已添加代码。问题:我应该能够使用它并获得成功的结果吗? android.kgmoney.net/2010/05/08/…。它也不起作用。
标签: android service android-activity android-intent