当前位置: 首页 > 知识库问答 >
问题:

当应用程序通过后退按钮关闭时,后台服务停止

杜河
2023-03-14

当用户使用后退按钮退出应用程序时,Android中的后台服务将停止运行。如果应用程序在前台或后台(点击HOME按钮),同样的服务工作得很好。

有3个案例:

    null

MainActivity.java

    package com.example.service_demo;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private TextView timerValue;
    private Button startTimer;
    private Button cancleTimer;
    Intent i;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapview();

    }

    private void mapview() {

        timerValue = (TextView) findViewById(R.id.timertext);
        startTimer = (Button) findViewById(R.id.starttimer);
        cancleTimer = (Button) findViewById(R.id.cancletimer);
        startTimer.setOnClickListener(this);
        cancleTimer.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        i = new Intent(this, SimpleService.class);
        if (isMyServiceRunning()) {
            Toast.makeText(getBaseContext(), "Service is running,",
                    Toast.LENGTH_SHORT).show();
            registerReceiver(broadcastReceiver, new IntentFilter(
                    SimpleService.BROADCAST_ACTION));
            startTimer.setEnabled(false);
        } else {
            Toast.makeText(getBaseContext(), "There is no service running",
                    Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onClick(View v) {
        if (v == startTimer) {
            startTimer.setEnabled(false);
            i = new Intent(this, SimpleService.class);
            startService(i);
            registerReceiver(broadcastReceiver, new IntentFilter(
                    SimpleService.BROADCAST_ACTION));
        } else if (v == cancleTimer) {
            i = new Intent(this, SimpleService.class);
            stopService(i);
            timerValue.setText("00:00:00");
            startTimer.setEnabled(true);

        }
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            updateUI(intent);
        }

    };

    private void updateUI(Intent intent) {
        String str = intent.getStringExtra("textval");
        timerValue.setText(str);

    }

    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager
                .getRunningServices(Integer.MAX_VALUE)) {
            if (SimpleService.class.getName().equals(
                    service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        i = new Intent(this, SimpleService.class);
        startService(i);
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        System.exit(0); // system.exit(0) is mendatory for my app so it can't be
                        // removed
    }

}

SimpleService

    package com.example.service_demo;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SimpleService extends Service {

    private NotificationManager mNM;
    private long startTime = 0L;
    long timeInMilliseconds = 0L;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;
    long basestart = System.currentTimeMillis();
    Timer timer = new Timer();
    long timeswap = 0L;
    int secs = 0;
    int mins = 0;
    int hour = 0;
    Intent intent;
    String s;
    public static final String BROADCAST_ACTION = "com.example.service_demo.MainActivity";
    private int NOTIFICATION = 1;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        intent = new Intent(BROADCAST_ACTION);
        Toast.makeText(this, "Service Started", 2000).show();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                timer.schedule(new RemindTask(), 0, 1000);
            }
        });
        t.start();

        return Service.START_NOT_STICKY;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mNM.cancel(NOTIFICATION);

        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        Toast.makeText(this, "Service Stoped", 2000).show();
    }

    class RemindTask extends TimerTask {

        @Override
        public void run() {

            timeInMilliseconds = System.currentTimeMillis() - basestart;
            timeSwapBuff = timeswap;
            updatedTime = timeSwapBuff + timeInMilliseconds;

            secs = (int) (updatedTime / 1000);
            mins = secs / 60;
            hour = mins / 60;

            secs = secs % 60;
            mins = mins % 60;

            s = "" + String.format("%02d", hour) + ":" + ""
                    + String.format("%02d", mins) + ":"
                    + String.format("%02d", secs);
            if (s.equalsIgnoreCase("00:00:15")) {
                showNotification();
            }
            intent.putExtra("textval", s);
            sendBroadcast(intent);
        }
    }

    private void showNotification() {
        // In this sample, we'll use the same text for the ticker and the
        // expanded notification
        CharSequence text = s;

        // Set the icon, scrolling text and timestamp
        @SuppressWarnings("deprecation")
        Notification notification = new Notification(R.drawable.ic_launcher,
                text, System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this
        // notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, "Notification Label", text,
                contentIntent);

        // Send the notification.
        mNM.notify(NOTIFICATION, notification);
    }

}

共有1个答案

汲睿
2023-03-14

在服务的方法onstartCommand()中,返回start_sticky。服务将继续运行,直到您在服务中显式调用stopself()或从活动中调用stopservice()

 类似资料:
  • 我有一个服务和一个交流的活动。当我点击按钮(我有galaxy s3,只有一个按钮)时,我的活动当然不满意,我的服务继续运行,但如果我点击后退(触摸)按钮,那么我的服务就被破坏了。我该如何改变这一点?我希望服务一直运行,直到活动破坏它。 活动:

  • 问题内容: 我有一个媒体播放器服务,可在整个应用程序的后台播放音乐,例如: 问题在于,当用户更改应用程序或进入手机主屏幕(应用程序在后台运行)时,音乐仍在播放。 我试图停止它和方法,但是当我更改活动时这会停止音乐,这是我不希望的(我希望音乐在用户浏览活动时继续播放)。 更新资料 我尝试了广播: 我加了 在音乐服务的onCreate和接收事件的方法中: 在应用程序类中,我这样做: 但是音乐不会恢复

  • 我有一个带有searchView图标的操作栏。我点击searchView图标,出现softInputMode键盘,我的ListView出现用于搜索。但是,当您关闭searchView时,searchView会关闭,但我无法让ListView在searchView关闭时也关闭。 下面是我在activity_maps中的ListView代码。xml 地图ctivity.java 所以最初当MapsAc

  • 问题内容: 我的应用程序包含A,B和C这三个活动。我通过“确定”按钮从A移到B,并且我想使用Android设备的默认后退按钮从B移到A。但是,当我按下按钮时,整个应用程序将关闭。我该如何解决这个问题? 问题答案: 我怀疑您是通过“确定”按钮onclick监听器调用的。不要那样做 从活动堆栈中删除您的活动。 在这里阅读更多。

  • 我正在安装我的应用程序,然后使用主活动保存数据,并转到另一个片段活动。下一次我启动我的应用程序时,总是预览第二个片段,然后按“返回”键返回主活动,但我不想返回主活动。我想按后退按钮关闭我的应用程序。我试试这个

  • 我试图重新创建Connect四,我成功了。但我想通过频繁地切换颜色,给玩家一个获胜的四张光盘在哪里的指示。我对线程和编程中的时间概念是新的。 我也成功地给了用户这个指示,但是在关闭应用程序之后,控制台仍然会给出输出,也是在使用SetonCloserEquest时。 代码如下: