2013-02-07 41 views
0

我正在寫一個Android應用程序,當我第一次運行它可以正常工作,但是當我嘗試第二次運行時它變得不穩定。我想可能是我第一次啓動的線程或服務仍然繼續工作,第二次啓動應用程序時會出現衝突或其他問題。 在我的應用程序中,我有一個主要的活動,我從中啓動一個服務,並在服務中啓動一個運行的線程。 退出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; 
} 
.... 
} 

回答

1

當你不經常清理資源需要他們。例如:如果Service僅在您的Activity - >Activity.onPause中調用stopService的運行時期間需要。 (和startServiceActivity.onResume中)。

關於您的Service,是否需要繼續運行。或者它應該完成1項任務,然後完成?如果是這樣,則使用IntentService,當沒有更多的意圖處理時它將自行關閉。

此外你使用什麼樣的線程? ThreadAsyncTask還是別的? Thread是非常基本的,suger版本如AsyncTask可能會更好地完成這項工作。很大程度上取決於你在做什麼。

+0

感謝您的回答,我更新了我的問題,更多的細節。該服務的目的是在後臺播放音頻,只要用戶不退出應該工作的應用程序。我正在使用'Thread'而不是AsyncTask。所以根據我上面的代碼,當用戶點擊我打算放在那裏的退出按鈕時,需要關注哪些項目? – TJ1

+0

線程在這裏很好,你應該將線程創建移動到OnCreate。 OnStartCommand在處理意圖時退出(=非常快)。因此你有一個懸掛的線程繼續運行。 – RvdK

+0

所以我應該將整個線程的創建,包括'while(a){...}'移動到onCreate上,並且只是將'mythread.start()'留在'inStartCommand'中?我怎樣才能阻止線程運行? – TJ1

0

嘗試殺死進程,如果沒有其他併發症.....

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

感謝

相關問題