我尝试做一个简单的服务.这是学习如何创建服务.在我的代码中,当我点击开始按钮然后它确实向我显示说服务开始的吐司,但当我点击停止按钮然后它没有显示我的吐司说服务停止.我的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));
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
服务类
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();
}
}
Run Code Online (Sandbox Code Playgroud)
public void onDestory() { ...
^^
Run Code Online (Sandbox Code Playgroud)
你有一个错字.请参阅:您何时使用Java的@Override注释?为什么?,这是你应该使用@Override注释的原因之一.
| 归档时间: |
|
| 查看次数: |
354 次 |
| 最近记录: |