【发布时间】:2014-04-13 14:25:07
【问题描述】:
最近,我正在创建一个带有后台服务的应用程序。我想当我打开我的应用程序时,服务将停止,当我关闭我的应用程序时,服务将启动。我找到了一种方法来做到这一点。我将“startService”放在“onDestroy”中,将“stopService”放在 MainActivity 的“onCreate”中(此活动始终是第一个启动和最后一个销毁的活动)。但只有 startService 工作正常, stopService 使我的 MainActivity 在我启动我的应用程序时变成一个白色的空白屏幕。
MyService.class
Thread t;
public int onStartCommand(Intent intent, int flags, int startId) {
shouldContinue = true;
t = new Thread( new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(shouldContinue){
int DELAY = 60000;
SystemClock.sleep(DELAY);
/**
** I update my Database every 60 seconds
**
*/
});
t.start();
// .......
public void onDestroy() {
// TODO Auto-generated method stub
if( t.isAlive()) {
shouldContinue = false;
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
super.onDestroy();
}
这是 MyMainActivity.class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
if( isMyServiceRunning() == true){
// TODO Auto-generated method stub
Intent i= new Intent(this, MyService.class);
stopService(i);
}
protected void onDestroy() {
// TODO Auto-generated method stub
if( isMyServiceRunning() == false){
Intent i= new Intent(this, MyService.class);
startService(i);
}
super.onDestroy();
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
请帮我解决这个问题。非常感谢!
【问题讨论】:
-
你不认为你的启动和停止服务交换了吗?不应该在 onCreate 中启动,在 onDestroy 中停止吗?
-
不是 Android 专家,但在
Intent i= new Intent(this, MyService.class); stopService(i);行中没有对Service实例的引用,仅对类...也许 Android 不会自动找到正确的实例并停止它... -
不,我希望当我启动应用程序时,服务将停止,当我关闭我的应用程序时,服务将重新启动。因为我不希望应用程序和服务同时使用我的数据库 SQLite 时发生冲突
-
另外,也许是
<a href="http://developer.android.com/reference/android/app/ActivityManager.html#killBackgroundProcesses(java.lang.String)">ActivityManager.killBackgroundProcesses (String packageName)</a> is what you're looking for. You can retrieve package name fromRunningServiceInfo service.service.getPackageName()`。 -
@yair 我觉得可以,因为在下面的教程中,他们也只在需要停止服务时才调用类名。tutorialspoint.com/android/android_services.htm
标签: android multithreading service android-activity