![](/img/trans.png)
[英]How can I keep my app running in the background on iOS/Android with libGDX
[英]How can I keep an android app running in background
我正在制作一個簡單的嚇唬你的朋友應用程序。 您必須按一個按鈕,然后設置一個分鍾計時器,然后在屏幕上顯示經典的exorsist圖標和尖叫。 我嘗試把android:persistent="true"
,但它不起作用......這是我的活動:
package com.odysseus.myapp;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer scareMusic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startTimer = (Button) findViewById(R.id.btimerStart);
scareMusic = MediaPlayer.create(MainActivity.this, R.raw.monster_scream);
startTimer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread scareTimer = new Thread(){
public void run(){
try{
sleep(5000);
Intent activityIntent = new Intent("com.odysseus.myapp.SCARER");
startActivity(activityIntent);
}catch(InterruptedException e){
e.printStackTrace();
}
}
};
scareTimer.start();
}
});
}
}
我真的很新的android所以不要只是說使用服務或東西,因為我不知道那是什么。 我發現的其他答案對我來說太先進了所以請盡可能多地解釋!
沒有辦法讓你的應用免受關機的影響。 對於非System系統應用程序的所有應用程序,屬性“android:persistent”將被忽略。
話雖如此,為了確保應用程序在給定時間之后觸發意圖,您可能必須將啟動代碼放在一個服務器中(如果可能的話)。
使用服務並不是很難。 只需創建一個新類並添加extends Service
。 完成后,您應該添加此方法:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Your code here
return START_STICKY;
}
在此方法中,您可以啟動媒體播放器。 要停止服務,只需將stopSelf()
放在onDestroy()
。 祝好運!
您可以使用始終在后台運行的Service
,而不是使用Activity
。 有關如何創建僅包含活動的應用,請參閱此答案。 僅限服務的Android應用 。 作為解決方法,您可以創建活動無內容視圖或透明布局,然后在此活動中啟動服務,然后使用finish()
快速關閉活動。
現在,在服務中,您可以使用您嘗試在活動中使用的確切代碼。 但請記住在顯示com.odysseus.myapp.SCARER
后停止服務。
更新: -在顯示代碼后的com.odysseus.myapp.SCARER
活動中,您可以使用以下命令停止服務。
stopService(new Intent(this, service.class));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.