簡體   English   中英

如何更新Android應用更新時在單獨進程中運行的服務?

[英]How to update a service running in a separate process when the Android app is updated?

當我將應用程序更新為新版本時,與之前的應用程序版本一起安裝的服務仍在運行。 當我第二次更新應用程序時,更新的服務正在正常運行。

但是,在第一次更新后,每當我關閉應用程序或重新啟動手機時,都會運行先前版本的服務。

如何在應用更新后立即強制新服務運行。

這是我的代碼

AndroidManifest.xml中

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.djuro.updateservicewithappupdate">

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <service
            android:name=".MyService"
            android:process=":myService" />

        <receiver android:name=".PackageReplacedReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <data android:scheme="package" android:path="com.djuro.updateservicewithappupdate"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

App.java

public class App extends Application {
    private static final String TAG = App.class.getName();

    private static App mInstance;

    private Messenger myServiceMessenger;
    private boolean isBound;

    private Messenger replyMessenger = new Messenger(new IncomingHandler());



    @Override
    public void onCreate() {
        super.onCreate();

        if (mInstance == null) {
            mInstance = this;
            startMyService();
        }

        isBound = false;

        // start the chore service (if it is not running) and bind to it

    }


    public void startMyService() {
        startService(new Intent(mInstance, MyService.class));
        doBindService();
    }

    public void stopMyService() {
        doUnBindService(true);
        stopService(new Intent(mInstance, MyService.class));
    }



    public static App getInstance() {
        return mInstance;
    }

    public static Context getContext() {
        return mInstance.getApplicationContext();
    }

    public static Messenger getChoreMessenger() {return mInstance.myServiceMessenger;}


    @Override
    public void onTerminate() {
        doUnBindService(false);
        super.onTerminate();
    }

    private void doBindService() {
        if (!isBound) {
            Log.d(TAG, "Binding ChoreService.");
            bindService(new Intent(this, MyService.class), myServiceConnection, Context.BIND_AUTO_CREATE);
            isBound = true;
        }
    }


    private void doUnBindService(boolean restartService) {
        if (isBound) {
            Log.d(TAG, "Unbinding ChoreService.");
            if (myServiceMessenger != null) {
                try {
                    Message msg = Message.obtain(null, MyService.UNREGISTER_CLIENT);
                    msg.replyTo = replyMessenger;
                    replyMessenger.send(msg);
                }
                catch (RemoteException e) {
                    // There is nothing special we need to do if the service has crashed.
                }
            }
            if (restartService) {
                try {
                    Message msg = Message.obtain(null, MyService.STOP_SERVICE_ON_UNBIND);
                    msg.replyTo = replyMessenger;
                    replyMessenger.send(msg);
                }
                catch (RemoteException e) {
                    // There is nothing special we need to do if the service has crashed.
                }
            }
            unbindService(myServiceConnection);
            isBound = false;
        } else if (restartService) {
            stopService(new Intent(mInstance, MyService.class));
        }
    }




    private ServiceConnection myServiceConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder service) {
            myServiceMessenger = new Messenger(service);
            Log.d(TAG, "connected to service");
            try {
                Message msg = Message.obtain(null, MyService.REGISTER_CLIENT);
                msg.replyTo = replyMessenger;
                myServiceMessenger.send(msg);
            }
            catch (RemoteException e) {
                // In this case the service has crashed before we could even do anything with it
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            myServiceMessenger = null;
            Log.d(TAG, "disconnected from ChoreService");
        }
    };

    class IncomingHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
        }
    }
}

MyService.java

public class MyService extends Service {

    private static final String TAG = MyService.class.getName();

    public static final int UNREGISTER_CLIENT = 1;
    public static final int REGISTER_CLIENT = 2;
    public static final int STOP_SERVICE_ON_UNBIND = 3;

    final Messenger messenger = new Messenger(new IncomingHandler());

    private String appVersion;
    private boolean stopOnUnbind;
    private int boundCount = 0;


    // called when the intent starts the Service
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //return super.onStartCommand(intent, flags, startId);
        Log.d(TAG, "onStartCommand()");
        getVersion();
        return START_STICKY;
    }


    // called once at creation (before onStartCommand)
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }

    // used to bind intent to service
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //doStopForeground();
        boundCount ++;
        Log.d(TAG, "bound count: " + boundCount);
        return messenger.getBinder();
    }


    @Override
    public boolean onUnbind(Intent intent) {
        boundCount --;
        Log.d(TAG, "bound count: " + boundCount);
        boolean result = super.onUnbind(intent);
        if (stopOnUnbind) {
            Log.d(TAG, "stopSelf()");
            stopSelf();
        }
        return result;
    }

    // called when the service is destroyed
    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy()");
        super.onDestroy();
    }



    public void getVersion() {
        try {
            PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
            appVersion = pInfo.versionName;
            Log.d(TAG, "appVersion: " + appVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }


    private class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            Log.d(TAG, "IncomingHandler handling message. msg.what= " + msg.what);
            switch (msg.what) {
                case STOP_SERVICE_ON_UNBIND:
                    stopOnUnbind = true;
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    }
}

PackageReplacedReceiver.java

public class PackageReplacedReceiver extends BroadcastReceiver {

    private static final String TAG = PackageReplacedReceiver.class.getName();

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "package updated");
        App.getInstance().stopMyService();
    }

}

在intent filer中使用android.intent.action.MY_PACKAGE_REPLACED操作,並從廣播接收器停止服務。

<receiver android:name=".PackageReplacedReceiver" android:enabled="@bool/is_at_least_api_12" > <intent-filter> 
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
 </intent-filter> 
</receiver>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM