【问题标题】:Android service recreated when main activity destroyed主要活动被破坏时重新创建Android服务
【发布时间】:2014-07-05 07:01:13
【问题描述】:

我的安卓服务有问题, 当我关闭应用程序时,主要活动关闭并重新创建服务 - 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 天。

谢谢, 阿隆

【问题讨论】:

    标签: android service android-service android-intentservice


    【解决方案1】:

    您的代码的第一个问题是您允许在MyServcie 类中多次启动线程。每次用户按下“开始”按钮,都会调用线程start方法,根据Java API specification是非法的:

    多次启动一个线程是不合法的。特别是,线程一旦完成执行就可能不会重新启动。

    您应该防止在您的服务类中重复启动线程,例如使用一个标志来告知线程是否已启动。

    还请注意,自 API 级别 5 起,Service#onStart 方法已被弃用。相反,您应该尽可能使用 Service#onStartCommand。 从这个方法中,正如 Sanket 所指出的,如果你只想执行一次 MyThread#run 方法的代码,你应该返回 START_NOT_STICKY。此外,您可能希望在 finally 块中显式停止服务。

    【讨论】:

      【解决方案2】:

      看看这是否有帮助 - 使用共享首选项为状态保存一些字符串,并在活动重新打开时取回。

      【讨论】:

      • 我想避免使用持久性,据我所知服务实例在停止服务调用之前不会被销毁,不是这样吗?
      【解决方案3】:

      在服务类中使用此方法

      @Override
          public int onStartCommand(Intent intent, int flags, int startId) {
              // We want this service to continue running until it is explicitly
              // stopped, so return sticky.
      
              // do your logic here not in onStart().
      
              return START_NOT_STICKY;
          }
      

      START_NOT_STICKY 和 START_STICKY

      这里是 START_NOT_STICKY 和 START_STICKY 的好答案

      https://stackoverflow.com/a/9441795/942224

      如果您想在应用关闭时停止服务,而不是在 onDestroy 中使用 stopService

      【讨论】:

      • 当我这样做时,服务在活动关闭时被破坏。
      • 从 onDestroy 中移除 stopService。因此,如果您从最近删除应用程序,服务将被破坏
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      相关资源
      最近更新 更多