0

我正在编写一个 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;
}
....
}
4

2 回答 2

1

当您不需要它们时,请始终清理资源。例如:如果Service仅在您的 -> 调用运行时Activity需要. (和)。stopServiceActivity.onPausestartServiceActivity.onResume

关于你的Service,是否需要继续运行。还是应该做1个任务然后就完成了?如果是这样,请使用IntentService,当没有更多要处理的意图时,它将自行关闭。

此外,您使用的是哪种线程?Thread还是AsyncTask别的什么?Thread是非常基本的,一个像这样的糖版本AsyncTask可能会做得更好。很大程度上取决于你用它做什么。

于 2013-02-07T15:54:35.763 回答
0

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

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

谢谢

于 2013-06-21T08:37:25.520 回答