-4

I am currently working on a code that I need to convert from 'extends Activity' to 'extends Service'. I need this because I need to have my app running (the audio being played) in the background even if the phone is in sleep mode. However, doing so caused me some errors. I have no idea how to fix this. As recommended by eclipse, I removed '@Override' before 'protected void onCreate...'. But it still has some errors with functions under it.

protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_p_3);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
        p_e=0;
        second_display=(TextView)findViewById(R.id.textView1);
        minute_display=(TextView)findViewById(R.id.textView2);
        hour_display=(TextView)findViewById(R.id.textView3);

The ones I am having problems with are:

requestWindowFeature
onCreate
setContentView
setRequestedOrientation
findViewById

finish(); (from another child class)

Are there equivalent codes in Activity that I can use in Service?

How do I fix these? I really need help.

4

2 回答 2

2

简单的答案是,不,没有——除了onCreate在服务中设置的参数与在活动中设置的参数不同。您需要了解的是,Service 在后台运行,并且不包含任何自己的 UI。因此,窗口特征、视图、方向不适用于服务。

我建议您首先阅读 google 上的服务文档。注意服务生命周期。

假设您想要一个简单的应用程序来播放声音 - 即使手机进入睡眠状态或您的活动从前台删除时也会继续这样做 - 那么您需要的是活动和服务的组合。Activity 将包含所有用户界面 - 就像它现在为您所做的那样。会改变的是声音播放。您可以从服务中播放声音,而不是从活动中播放声音。然后,您将需要在您的服务和活动之间进行通信 - 更新 UI(从服务到活动)并控制播放(从活动到服务)。

Android 开发人员指南中的服务部分提供了有关如何实现这一点的良好信息 - 以及更多信息。

于 2013-10-02T14:38:22.237 回答
0

这些方法不存在于Service. 原因是,您不需要它们。所有这些方法仅适用于活动,因为它们是显示数据/视图所必需的。

服务不能显示任何内容。检查Android 基础页面

于 2013-10-02T14:36:39.730 回答