Android如何在使用点击系统返回或主页按钮时停止服务?

时间:2014-04-17 16:37:57

标签: android android-service

我在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.
    }

2 个答案:

答案 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);