package com.virjar.g4proxy;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.virjar.g4proxy.service.SchedulerTaskService;


/**
 * Created by liuzhaoce on 2019/4/14.
 */
// 这里我们先依靠slave进行守护保活
public class SelfStartReceiver extends BroadcastReceiver {

    //TODO： 有些自启动机器会报错
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        //取得SelfStartReceiver所在的App的包名
        String localPkgName = context.getPackageName();
        Uri data = intent.getData();


        if (data == null) {
            return;
        }
        //取得安装的Apk的包名，只在该app覆盖安装后自启动
        String installedPkgName = data.getSchemeSpecificPart();

        if (action == null) {
            return;
        }
        if ((action.equals(Intent.ACTION_PACKAGE_ADDED)
                || action.equals(Intent.ACTION_PACKAGE_REPLACED)) && installedPkgName.equals(localPkgName)) {

            Intent launchAppUpdateService = new Intent(context, SchedulerTaskService.class);
            launchAppUpdateService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            Intent launchHttpProxyService = new Intent(context, HttpProxyService.class);
            launchHttpProxyService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            Intent mainActivity = new Intent(context, MainActivity.class);
            mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            context.startService(launchAppUpdateService);
            context.startService(launchHttpProxyService);
            context.startActivity(mainActivity);
        }
    }
}

