我有活动,启动/停止服务。还有一个服务,它有一个循环。我目前正试图从主要活动中停止我的服务。我尝试了许多变体,但没有一个调用 onDestroy :/。任何帮助、想法或教导将不胜感激。:)
从我的主要活动中,我尝试通过对话框停止服务:
private void AlertDialog() {
new AlertDialog.Builder(this)
.setTitle("Delete entry")
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
stopService(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
服务:
public class SensMessageService extends Service{
public final String APP = "Ultimator";
public final String PREF_IN_USE = "inuse";
public final String PREF_TOTAL_MESSAGES = "totalmes";
public final String PREF_LEFT_MESSAGES = "leftmes";
public final String MESSAGE_BODY = "sms_body";
public final String MESSAGE_RECEIVER = "sms_receiver";
public final String MESSAGE_REPEATS = "sms_repeats";
public final String TAG = "SensMessageService";
private IBinder ibinder;
private SharedPreferences prefrences;
@Override
public IBinder onBind(Intent arg0) {
return this.ibinder;
}
public class LocalBinder extends Binder{
SensMessageService getBinder(){
return SensMessageService.this;
}
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
@Override
public void unbindService(ServiceConnection conn) {
// TODO Auto-generated method stub
super.unbindService(conn);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
stopSelf();
Toast.makeText(getApplicationContext(), "Stopped", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intentas, int startId) {
final Intent intent = intentas;
SmsManager smsManager = SmsManager.getDefault();
int repeat = Integer.parseInt(intent.getStringExtra(MESSAGE_REPEATS));
String sendTo = intent.getStringExtra(MESSAGE_RECEIVER);
String myMessage = intent.getStringExtra(MESSAGE_BODY);
for (int i=0; i<repeat; i++) {
smsManager.sendTextMessage(sendTo, null, myMessage, null, null);
}
super.onStart(intent, startId);
}
}
我认为 onDestroy 没有以某种方式被调用:/,因为我没有看到吐司
更新:
我添加了一个线程,但不知何故它没有打印出来
@Override
public void run() {
try {
while(true) {
sleep(1000);
System.out.println("fff");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();