我有一项服务和一项沟通活动。 当我点击按钮(我有galaxy s3只有一个按钮)然后我的活动当然消失了,我的服务继续运行,但如果我点击后面(触摸)按钮,那么我的服务就会被破坏。 我怎么能改变它?我希望服务继续运行,直到活动破坏它。
修改
以下是代码:
服务: 公共类MyService扩展了Service { private static final String TAG =“BroadcastService”; public static final String BROADCAST_ACTION =“com.websmithing.broadcasttest.displayevent”; private final Handler handler = new Handler(); 私人意图; int counter = 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();
}
}
的活动:
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);
}
}
答案 0 :(得分:2)
当您按下后退按钮时,您的服务会停止。后退按钮大多数在活动上调用finish()
,并且它被销毁。当您按下另一个按钮(主页按钮)时,它只会最小化您的应用程序,并且只有在操作系统想要释放空间时才会销毁它。
如果您希望保持服务正常运行,请将其作为前台服务,并且不要在活动销毁时将其停止。
答案 1 :(得分:0)
你可以将你的应用程序放在后台而不是完成它。
@Override
public void onBackPressed() {
moveTaskToBack(true);
// super.onBackPressed();
}