android - undefined intent constructor错误?
怪我咯
怪我咯 2017-04-17 11:26:31
[Android讨论组]

我在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

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(1)
PHPz

答:kalyan pvs(最佳答案)
你不应该使用Service.this,而应该按如下方法改变class:

Intent myintent =new Intent(SampleService.this,MyService.Class);

答:Raghunandan
做如下调整:

Intent myintent =new Intent(SampleService.this,MyService.this);

变为:

Intent myintent =new Intent(SampleService.this,MyService.Class);
 // first param is a context second param is a class in your case a MyServiceClass

你没有设置类似于Intent(SampleService, MyService)的构造函数,在intent constructor参数设定上出现错误。

public Intent (Context packageContext, Class<?> cls)

Added in API level 1
Create an intent for a specific component. All other fields (action, data, type, class) are null, though they can be modified later with explicit calls. This provides a convenient way to create an intent that is intended to execute a hard-coded class name, rather than relying on the system to find an appropriate class for you; see setComponent(ComponentName) for more information on the repercussions of this.

Parameters
packageContext  A Context of the application package implementing this class.
cls

The component class that is to be used for the intent.
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号