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