0

私はAndroidアプリを書いていますが、最初に実行すると正常に動作しますが、2回目に実行しようとすると不安定になります。おそらく、最初に開始したスレッドまたはサービスは引き続き機能し、2回目にアプリを開始すると競合などが発生する可能性があります。私のアプリには、サービスを開始するメインアクティビティがあり、サービス内では、実行されるスレッドを開始します。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呼び出しstopServiceますActivity.onPause。(およびstartServiceActivity.onResume)。

あなたについてService、それは実行し続ける必要がありますか?それとも、1つのタスクを実行してから実行する必要がありますか?その場合はIntentService、を使用します。これは、処理するインテントがなくなると自動的に終了します。

さらに、どのようなスレッドを使用していますか?ThreadまたはAsyncTaskまたは何か他のもの?Threadかなり基本的なもので、のようなsugerバージョンAsyncTaskの方がうまくいくかもしれません。あなたがそれで何をしているかに非常に依存します。

于 2013-02-07T15:54:35.763 に答える
0

他に問題がない場合は、プロセスを強制終了してみてください。

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

ありがとう

于 2013-06-21T08:37:25.520 に答える