我的 android 服务有问题,当我关闭应用程序时,主要活动关闭并重新创建服务 - oncreated 方法调用自动和 onstart 也称为自动 - 所有状态都消失了。
这是我的活动代码
public class ServicesDemo extends Activity implements OnClickListener
{
private static final String TAG = "ServicesDemo";
Button buttonStart, buttonStop;
@Override
public void onCreate(Bundle savedInstanceState)
{
if (savedInstanceState != null)
{
Log.d(TAG, "ServicesDemo:onCreate WITH savedInstanceState)");
}
Log.d(TAG, "ServicesDemo:onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
public void onClick(View src)
{
switch (src.getId())
{
case R.id.buttonStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
// Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}
这是服务代码:
public class MyService extends Service
{
private static final String TAG = "ServicesDemo";
private static MyThread t = new MyThread();
static int yy = 90;
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onCreate()
{
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
// MockGPSLocationModel.getInstance().Counter++;
// Log.d(TAG, "MockGPSLocationModel.getInstance().Counter :: " +
// MockGPSLocationModel.getInstance().Counter);
// MockGPSLocationModel.getInstance().Counter++;
}
static public class MyThread extends Thread
{
MediaPlayer player;
public Context ctx;
@Override
public void run()
{
try
{
for (int i = 0; i < 100; i++)
{
Log.i(TAG, "lOOP - " + i);
Thread.sleep(2000);
}
player = MediaPlayer.create(ctx, R.raw.braincandy);
player.setLooping(false); // Set looping
player.start();
}
catch (Exception e)
{
Log.e(TAG, e.toString());
}
finally
{
}
}
}
@Override
public void onDestroy()
{
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
// player.stop();
}
@Override
public void onStart(Intent intent, int startid)
{
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
t.ctx = this;
t.start();
// player.start();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".ServicesDemo"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true" />
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
请帮忙。我坚持了3天。
谢谢,阿隆