私は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;
}
....
}