2012-11-29 39 views
0

我在onDestroy()方法中编写此代码。关闭背景时无法关闭服务

@Override 
public void onDestroy() 
{ 
MessageService.this.stopSelf(); 
messageThread.isRunning = false; 
System.exit(0); 
super.onDestroy(); 
} 

并关闭其他Activity中的服务。

stopService(new Intent(MainOptionActivity.this,MessageService.class)); 

我试了很多代码,关闭背景后无法关闭服务。任何人都可以给我一些建议吗?谢谢。

回答

2

下面是服务类

public class MyService extends Service { 

@Override 
public IBinder onBind(Intent intent) { 

    return null; 
} 

@Override 
public void onCreate() { 
    Toast.makeText(getApplicationContext(), "MSG onCreate SERVICE", Toast.LENGTH_LONG).show(); 
    super.onCreate(); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Toast.makeText(getApplicationContext(), "MSG onStartCommand SERVICE", Toast.LENGTH_LONG).show(); 
    return super.onStartCommand(intent, flags, startId); 
} 

@Override 
public void onDestroy() { 
    Toast.makeText(getApplicationContext(), "MSG STOP SERVICE", Toast.LENGTH_LONG).show(); 
    super.onDestroy(); 
} 

} 

一个简单的代码,这里是测试该服务

startService(new Intent(this, MyService.class)); 

    new Timer().schedule(new TimerTask() { 

     @Override 
     public void run() { 
      startService(new Intent(getApplicationContext(), MyService.class)); 
     } 
    }, 5000); 

    new Timer().schedule(new TimerTask() { 

     @Override 
     public void run() { 
      stopService(new Intent(getApplicationContext(), MyService.class)); 
     } 
    }, 10000); 

这工作得很好的代码。还要在清单中添加此代码

<service android:name=".MyService" /> 
1

请勿在Android上使用System.exit(0),而应使用finish(例如在Activity中)。

但是没有必要停止自己onDestroy方法,它实际上会被停止和销毁(这就是onDestroy方法的用途)。

您停止与System.exit(0);的方法的执行,因此系统永远不会到达super.onDestroy();点和服务不被破坏。

尽量只

@Override 
public void onDestroy() { 
    messageThread.isRunning = false; 
    super.onDestroy(); 
}