我制作了一款具有语音识别功能的应用,因此当我按下主屏幕按钮时,它会停止录制,但我也希望它在后台运行。我已经试过这段代码,但是我不知道在这里放什么工作。
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());
}
}
我必须把我的整个主要活动都放在这还是必须放置什么?
答案 0 :(得分:0)
我认为您应该在这里使用线程。例如,我要运行一个应用程序,并希望它在后台不断地打印一些内容。看起来像这样:
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