我尝试做一个简单的服务。这是学习如何创建服务。在我的代码中,当我点击开始按钮然后它确实向我显示说服务开始的吐司但当我点击停止按钮然后它没有显示我的吐司说服务停止。我的logcat中也没有出现任何错误。这是我的代码
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));
}
});
}
}
服务类
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();
}
}
答案 0 :(得分:5)
public void onDestory() { ...
^^
你有一个错字。请参阅:When do you use Java's @Override annotation and why?,这是您应该使用@Override
注释的原因之一。
答案 1 :(得分:0)
试试这个:
1)在清单文件中添加以下行:
<service android:enabled="true" android:name=".BatteryService " />
2)清理你的项目