简体   繁体   English

Android服务不起作用

[英]Android service does not work

I am tryign to make a simple service. 我很想提供简单的服务。 This is to learn how to create services. 这是学习如何创建服务。 In my code when I click start button then it does show me the toast that says service started but when I click stop button then it does not show me toast which says service stopped. 在我的代码中,当我单击开始按钮时,它确实向我显示说服务已启动的吐司,但是当我单击停止按钮时,它并没有向我显示表明服务已停止的吐司。 I am not getting any error in my logcat as well. 我的logcat也没有收到任何错误。 Here is my code 这是我的代码

package com.zafar.batterynotify;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class BatteryNotify extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button startButton = (Button) findViewById(R.id.start);
    Button stopButton = (Button) findViewById(R.id.stop);

    startButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            startService(new Intent(getBaseContext(), BatteryService.class));
        }
    });

    stopButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            stopService(new Intent(getBaseContext(), BatteryService.class));
        }
    });
}
}

service class 服务等级

package com.zafar.batterynotify;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class BatteryService extends Service {

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    return START_STICKY;
}

public void onDestory() {
    super.onDestroy();
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}

}
public void onDestory() { ...
                  ^^

You have a typo. 你有错字 Please see: When do you use Java's @Override annotation and why? 请参阅: 什么时候使用Java的@Override注释,为什么? , this is one of the reasons why you should use the @Override annotation. ,这就是您应该使用@Override批注的原因之一。

Try this: 尝试这个:

1) Add the following line in manifest file: 1)在清单文件中添加以下行:

<service  android:enabled="true"  android:name=".BatteryService " />

2) Clean your project 2)清理您的项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM