【问题标题】:How to my app run forever, even in the background如何让我的应用程序永远运行,即使在后台也是如此
【发布时间】:2019-12-13 13:49:36
【问题描述】:

我制作了一个具有语音识别功能的应用程序,所以当我按下主页按钮时它会停止录制,但我希望它也能在后台运行。我已经尝试过这段代码,但我不知道在你这里放什么。

public class YourService extends Service {

    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";

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

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

        // do your jobs here

        startForeground();

        return super.onStartCommand(intent, flags, startId);
    }

    private void startForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
                NOTIF_CHANNEL_ID) // don't forget create a notification channel first
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Service is running background")
                .setContentIntent(pendingIntent)
                .build());         
    }
}

我必须把我的整个主要活动都放在这个里面还是我必须放什么?

【问题讨论】:

    标签: java background speech-recognition


    【解决方案1】:

    我认为你应该在这里使用线程。例如,我想运行一个应用程序,并希望它在后台不断打印一些东西。它看起来像这样:

    public class BackgroundProcess implements Runnable {
    
        public boolean resume;
    
        public void stop() {
            resume = false;
        }
    
        public BackgroundProcess() {
            resume = true;
        }
    
        // code that will be run as a thread must be inside the run() function;
        @Override
        public void run() {
            while(resume) {
                System.out.println("Are we there yet?");
            }
        }
    }
    
    public class MainApp {
        public static void main(String[] args) {
        BackgroundProcess bp = new BackgroundProcess();
        bp.start(); // starts the thread
        }
    }
    

    在 Java 中创建线程有两种方法。您可以阅读以下内容https://www.javatpoint.com/creating-thread

    【讨论】:

    • Thread 无法保证应用程序将永远在后台运行。
    • 啊,是的,我在这里忘记了一件事。我将编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多