关闭所有活动,服务,线程。等退出Android应用程序时

时间:2013-02-07 15:45:34

标签: android exit resource-cleanup

我正在编写一个Android应用程序,当我第一次运行时它工作正常,但当我尝试再运行它时它变得不稳定。我想也许我第一次开始的线程或服务仍然继续工作,第二次启动应用程序时会出现冲突或其他问题。 在我的应用程序中,我有一个主要活动从中启动服务,在服务内部我启动一个运行的线程。 退出Android应用时需要遵循的一般准则是什么?有什么具体的事情要确保它在退出后没有任何东西继续运行,并确保应用程序不保留一些资源,换句话说它是一个干净的退出。

以下是我的申请的更多详情: 我的主要活动是这样的:

public class MainActivity extends Activity implements OnClickListener {
...
   public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
        if (isService == false)  {
            Intent intent1 = new Intent(this, MyService.class);
            startService(intent1);
        }
        isService = true;
        if (firstTime == false) myService.setA(true);
        firstTime = false;
        break;
    case R.id.buttonStop:
        if (isService == true)  {
            Intent intent1 = new Intent(this, MyService.class);
            myService.setA(false);
            stopService(intent1);
        }
        isService = false;
        break;
    }
   }

   ...
}

我的服务看起来像这样:

public class MyService extends Service {
private boolean a=true;
...

@Override
public void onCreate() {    
    super.onCreate(); 
    int icon = R.drawable.icon;
    CharSequence tickerText = "Hello";
    long when = System.currentTimeMillis();
    Notification notification = new Notification(icon, tickerText, when);
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, "notification title", "notification message", pendingIntent);     
    startForeground(ONGOING_NOTIFICATION, notification);
    ...
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
}

@Override
 public int onStartCommand( Intent intent, int flags, int startId ) {
    Thread mythread = new Thread() {
        @Override
        public void run() {
            while(a)
            {
                PLAY AUDIO
            }
        }
    };
    mythread.start();
    return super.onStartCommand( intent, flags, startId );
}

public void setA(boolean aa) {
    Log.d(TAG,"a is set");
    this.a = aa;
}
....
}

2 个答案:

答案 0 :(得分:1)

在不需要资源时始终清理资源。例如:如果仅在Service的运行时期间需要Activity - >在stopService中致电Activity.onPause。 (以及startService中的Activity.onResume)。

关于您的Service,是否需要继续投放。或者它应该完成1个任务然后它完成了吗?如果是这样的话,请使用IntentService,当没有更多的Intent需要处理时,它会自行关闭。

此外,您使用的是哪种线程? ThreadAsyncTask或其他什么? Thread非常基本,像AsyncTask这样的suger版本可以更好地完成工作。非常取决于你正在做什么。

答案 1 :(得分:0)

如果没有其他并发症,请尝试杀死该过程.....

android.os.Process.killProcess(android.os.Process.myPid());

由于