2012-11-30 99 views
2

我在我的应用程序下面的代码段:麻烦启动服务时,按一下按钮

.... tb1.setOnClickListener(新OnClickListener(){

@Override 
public void onClick(View v) { 

    // Auto-generated method stub 
    startService(Intent this.Main); 
} 
}); 
} 

public void onStart(Intent intent, int startid) { 

    Toast.makeText(context, "yessssss", Toast.LENGTH_LONG).show(); 
//and do something// 

} 

和我要开始服务时的“TB1”按钮,用户点击,

我曾尝试:

startService(new Intent(this,Main.class));

startService(Main.class);

但他们都没有启动服务,我该怎么办?

+0

你可以使用标签活动? – Hemant

+0

在包含包名的清单中给出'Service'的完整路径。 –

+0

是什么?你的意思,而不是我使用Tab活动的服务?我不明白。 –

回答

4

更改您的代码为在按钮点击启动服务:

Intent intent = new Intent(Current_Activity.this, Main.class); 
startService(intent); 

,并确保你有在Manifast.xml中将您的服务注册为:

<service 
    android:name=".Main"/> 
+0

它仍然没有开始服务。 –

+0

它没有奏效。我可以补充说我的Current_Activity和Main.class是一样的,我的意思是我像这样编辑你的代码** Intent intent = new Intent(Main.this,Main.class); ** –

+0

不是你可以尝试'Intent intent =新的意图(getApplicationContext(),Main.class); 'intent意图=新意图(Main.this,Main.class);'和你的服务名称是什么? –

0

试试这个

Intent myIntent = new Intent(this, Main.class); 
startService(myIntent); 

同时添加为您服务,您的清单

<service android:name="packagename.Main"></service> 
+0

它没有奏效。我可以补充说我的Current_Activity和Main.class是一样的,我的意思是我像这样编辑你的代码Intent intent = new Intent(Main.this,Main.class); –

0
Intent myIntent = new Intent(this, Main.class); 
startService(myIntent); 

没有编译 删除参数匹配 '意愿()' 与X标记出现。

0
Intent myIntent = new Intent(this, Main.class); 
startService(myIntent); 

没有编译。删除参数以匹配Intent()与X标记一起出现。

一个小小的改变将会奏效。

Intent myIntent = new Intent(MainActivity.this, MyService.class); //is working both 
startService(myIntent); and stopService(myIntent); // also working.