我创建了一个扩展 IntentService 的类,我想从一个不是 Activity 的类启动服务,因此,我无权访问 Context 对象。我在文档或网络中找不到这样的示例。是否可以 ?
问问题
10606 次
2 回答
20
您需要将当前 Activity 上下文传递给非 Activity 类,以便从非 Activity 类启动服务:
public class NonActivity {
public Context context;
public NonActivity(Context context){
this.context=context;
}
public void startServicefromNonActivity(){
Intent intent=new Intent(context,yourIntentService.class);
context.startService(intent);
}
}
并将当前上下文传递为:
public class AppActivity extends Activity {
NonActivity nonactiityobj;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nonactiityobj=new NonActivity(CuttentActivity.this);
//start service here
nonactiityobj.startServicefromNonActivity();
}
}
于 2012-12-14T16:03:45.137 回答
3
使用此代码启动和停止服务
public class MyService {
Context context ;
public MyService(Context cont) {
this.context = context ;
}
public void StartMyService()
{
Intent i = new Intent(context,YourService.class);
context.startService(i);
}
public void StopMyService()
{
Intent i = new Intent(context,YourService.class);
context.stopService(i);
}
}
这只是创建这个类的对象
MyService mySevice ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myService = new MyService(this);
//For Startting Service
myService.StartMyService();
//For Stopping Service
myService.StopMyService();
}
于 2012-12-14T17:41:00.040 回答