我在mainActivity #create中启动了一个STICKY服务,但是当用户按下System Home或Back按钮时,该服务并没有被遗弃......无论如何?它不应该是STICKY吗?
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
...
startService(new Intent(this, FeedbackService.class));
FeedbackService.java
public class FeedbackService extends Service implements OnInitListener {
….
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.i(TAG, "Received start id " + startId + ": " + intent);
return START_STICKY; // run until explicitly stopped.
}
答案 0 :(得分:3)
这将确认用户想要在杀死服务之前退出。
@Override
public void onBackPressed() {
final DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
super.onBackPressed();
stopService(intentName)
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you exit and stop the background process?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
答案 1 :(得分:0)
重写onPause()方法并在onPause()
上添加以下代码stopService(intent_name);