当前位置 : 主页 > 手机开发 > android >

错误:在android中启动服务时未定义的意图构造函数

来源:互联网 收集:自由互联 发布时间:2021-06-11
我尝试在activity中启动服务.但它显示错误,如“构造函数Intent(SampleService,MyService)未定义” MyService.java public class MyService extends Service {@Overridepublic IBinder onBind(Intent intent) { return null;}public
我尝试在activity中启动服务.但它显示错误,如“构造函数Intent(SampleService,MyService)未定义”

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);
      }
 }

清单文件中初始化的服务.

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

帮我解决错误.

不是Service.this你必须通过课程
所以这样改变..

Intent myintent =new Intent(SampleService.this,MyService.Class);
网友评论