我正在尝试做一个简单的服务。这是为了学习如何创建服务。在我的代码中,当我单击开始按钮时,它确实显示了表示服务已启动的 toast,但是当我单击停止按钮时,它不会显示表示服务已停止的 toast。我的 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();
}
}