gpt4 book ai didi

android - 我的服务在后退按钮后停止

转载 作者:行者123 更新时间:2023-12-02 15:37:42 26 4
gpt4 key购买 nike

我有一个服务和一个交流的 Activity 。当我单击按钮时(我有 galaxy s3,只有一个按钮)然后我的 Activity 当然消失并且我的服务继续运行但是如果我单击后退(触摸)按钮然后我的服务被破坏。我该如何更改它?我希望服务继续运行,直到 Activity 破坏它。

编辑

代码如下:

服务: 公共(public)类 MyService 扩展服务 { private static final String TAG = "BroadcastService"; public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent"; 私有(private)最终处理程序处理程序=新处理程序(); 私有(private) Intent ; int 计数器 = 0;

    @Override
public void onCreate()
{
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}

@Override
public void onStart(Intent intent, int startId)
{
// handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second

}

private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 1000); // 10 seconds
}
};

private void DisplayLoggingInfo() {
intent.putExtra("counter", String.valueOf(++counter));
sendBroadcast(intent);
}

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

@Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}

Activity :

public class MainActivity extends Activity {
private static final String TAG = "BroadcastTest";
private Intent intent;

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

intent = new Intent(this, MyService.class);

startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(MyService.BROADCAST_ACTION));
}

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


@Override
public void onDestroy() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}

private void updateUI(Intent intent)
{
String counter = intent.getStringExtra("counter");
Log.d(TAG, counter);

TextView txtCounter = (TextView) findViewById(R.id.textView1);
txtCounter.setText(counter);
}
}

最佳答案

您可以将您的应用程序置于后台而不是完成它。

   @Override
public void onBackPressed() {
moveTaskToBack(true);
// super.onBackPressed();
}

关于android - 我的服务在后退按钮后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14192853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com