Android undefined intent constructor错误?

本文选自StackOverflow(简称:SOF)精选问答汇总系列文章之一,本系列文章将为读者分享国外最优质的精彩问与答,供读者学习和了解国外最新技术。在Android中启动Service时出现“undefined intent constructor”的错误,怎么办?

问:Ram

我在Activity中尝试启动Service,但出现“undefined intent constructor”的报错信息。

MyService.java代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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的代码如下:

1
2
3
4
5
6
7
8
9
  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的初值如下:

1
<service android:enabled="true" android:name="com.MyApp.MyService" />

请大家帮我解决这个错误。

答:kalyan pvs


(最佳答案)

你不应该使用Service.this,而应该按如下方法改变class:

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

答:Raghunandan

做如下调整:

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

变为:

1
2
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参数设定上出现错误。

1
2
3
4
5
6
7
8
9
10
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.

原文链接:http://stackoverflow.com/questions/20068783/errorundefined-intent-constructor-when-start-service-in-android

文章选自StackOverFlow社区,鉴于其内容对于开发者有所帮助,现将文章翻译于此,供大家参考及学习。9Tech将每日持续更新,读者可点击StackOverflow(简称:SOF)精选问答汇总查看全部译文内容。同时,我们也招募志同道合的技术朋友共同翻译,造福大家!报名请发邮件至zhangqi_wj@cyou-inc.com。

来自:9Tech
原文地址:https://www.cnblogs.com/aikongmeng/p/3697355.html