我在Activity中尝试启动Service,但出现“undefined intent constructor”的报错信息。
MyService.java代码如下:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
public static boolean isInstanceCreated() {
return instance != null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
instance = this;
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
instance = null;
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(getBaseContext(), "Service started",Toast.LENGTH_SHORT).show();
}
}
启动SampleService.java的代码如下:
public class SampleService extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_activity);
Intent myintent =new Intent(SampleService.this,MyService.this);//Error show here..
startService(myintent);
}
}
在manifest file中设定service的初值如下:
<service android:enabled="true" android:name="com.MyApp.MyService" />
请大家帮我解决这个错误。
原问题:Error:undefined intent constructor when start service in android
答:kalyan pvs(最佳答案)
你不应该使用Service.this,而应该按如下方法改变class:
答:Raghunandan
做如下调整:
变为:
你没有设置类似于Intent(SampleService, MyService)的构造函数,在intent constructor参数设定上出现错误。