PackageManager相关

本文介绍了一款基于Android平台的抓包工具的设计与实现细节,涵盖了从权限检测到抓包流程的各项功能,如文件重命名、上传及应用管理等,并提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.ics.aop.fragment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ics.aop.ApiUrl;
import com.ics.aop.ForkConstants;
import com.ics.aop.R;
import com.ics.aop.activity.NameActivity;
import com.ics.aop.adapter.AppAdapter;
import com.ics.aop.model.AppInfo;
import com.ics.aop.service.CaptureService;
import com.ics.aop.tool.Hanzi2Pinyin;
import com.ics.aop.tool.HttpTool;
import com.ics.aop.tool.ProgressOutHttpEntity;
import com.ics.aop.tool.ProgressOutHttpEntity.ProgressListener;

/**
 * 抓包Fragment
 * 
 */
public class CaptureFragment extends Fragment implements OnClickListener {

    private static final int REQUEST_CODE_DEFAULT_NAME = 0;
    private static final int REQUEST_CODE_CUSTOMED_NAME = 1;
    private View mRootView;
    private Activity mActivity;
    private Button btn_scratch;
    private Button btn_stop;
    private TextView tv_packet_desc;
    private Button btn_operate_latest_packet;

    private boolean isCapturing;

    private AppInfo mAppInfo;

    private CaptureService mCaptureService;

    private StopCapturingReceiver mStopCapturingReceiver;

    /**
     * 全局报文路径,包括报文名字和后缀名
     */
    private String mTargetPacketPath;

    /**
     * 全局报文名字,不包括后缀名
     */
    private String mTargetPacketName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mActivity = getActivity();

        // 初始化广播接收者
        initReceiver();

        // 启动service进行抓包
        Intent captureIntent = new Intent(mActivity, CaptureService.class);
        mActivity.bindService(captureIntent, conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_capture, container, false);
        btn_scratch = (Button) mRootView.findViewById(R.id.btn_scratch);
        btn_scratch.setOnClickListener(this);
        btn_stop = (Button) mRootView.findViewById(R.id.btn_stop);
        btn_stop.setOnClickListener(this);
        btn_operate_latest_packet = (Button) mRootView.findViewById(R.id.btn_operate_latest_packet);
        btn_operate_latest_packet.setOnClickListener(this);
        tv_packet_desc = (TextView) mRootView.findViewById(R.id.tv_packet_desc);
        if (isRoot()) {
            initTcpdumpPath();
        } else {
            btn_scratch.setEnabled(false);
            Toast.makeText(mActivity, "您的手机没有root权限", Toast.LENGTH_LONG).show();
            tv_packet_desc.setText("您的手机没有root权限,请先获取root权限。");
        }
        return mRootView;
    }

    /**
     * 判断当前手机是否有ROOT权限
     * @return
     */
    public boolean isRoot(){
        boolean bool = false;

        try{
            if ((!new File("/system/bin/su").exists()) && (!new File("/system/xbin/su").exists())){
                bool = false;
            } else {
                bool = true;
            }
        } catch (Exception e) {

        } 
        return bool;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_scratch:
            // 点击抓包
            chooseTypeDialog();
            break;
        case R.id.btn_operate_latest_packet:
            // 操作最新报文
            operateLatestPacket();
            break;
        case R.id.btn_stop:
            // 停止抓包
            stopCapture();
            btn_scratch.setVisibility(View.VISIBLE);
            btn_stop.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mTargetPacketPath) && !TextUtils.isEmpty(mTargetPacketName)) {
                btn_operate_latest_packet.setEnabled(true);
            } else {
                btn_operate_latest_packet.setEnabled(false);
            }
            break;

        default:
            break;
        }
    }

    /**
     * 操作最新报文
     */
    private void operateLatestPacket() {
        final AlertDialog operateDialog = new AlertDialog.Builder(mActivity).create();
        operateDialog.show();
        operateDialog.setContentView(R.layout.dialog_operate_local_packets);

        Button btn_rename = (Button) operateDialog.findViewById(R.id.btn_rename);
        btn_rename.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 点击重命名,弹出重命名对话框
                operateDialog.cancel();
                renamePacketDialog();
            }
        });

        Button btn_delete = (Button) operateDialog.findViewById(R.id.btn_delete);
        btn_delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 点击删除,弹出是否删除该报文的对话框
                operateDialog.cancel();
                deletePacketDialog();
            }
        });

        Button btn_upload = (Button) operateDialog.findViewById(R.id.btn_upload);
        btn_upload.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                operateDialog.cancel();
                // 上传单个报文 packet
                if (HttpTool.isNetworkConnected(mActivity)) {
                    List<File> fileList = new ArrayList<>();
                    File singleFile = new File(mTargetPacketPath);
                    if (singleFile.exists()) {
                        fileList.add(singleFile);
                        new UploadUtilsAsync(mActivity, ApiUrl.API_DOMAIN + ApiUrl.UPLOADING, fileList).execute();
                    } else {
                        Toast.makeText(mActivity, "文件不存在", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(mActivity, "请检查网络设置", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 弹出对话框,重命名报文
     * @param packetPath
     */
    private void renamePacketDialog() {
        final AlertDialog renameDialog = new AlertDialog.Builder(mActivity).create();
        renameDialog.setView(new EditText(mActivity));
        renameDialog.show();
        renameDialog.setCanceledOnTouchOutside(false);
        renameDialog.setContentView(R.layout.dialog_rename_packet);

        final EditText et_rename_packet = (EditText) renameDialog.findViewById(R.id.et_rename_packet);
        et_rename_packet.setText(mTargetPacketName);

        Button btn_confirm = (Button) renameDialog.findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 点击确定重命名
                String newFileName = et_rename_packet.getText().toString();

                if (!TextUtils.isEmpty(newFileName)) {
                    File oldFile = new File(mTargetPacketPath);
                    File newFile = new File(oldFile.getParent(), newFileName + ".pcap");

                    if (oldFile.exists()) {
                        if (newFile.exists()) {
                            Toast.makeText(mActivity, "文件名已存在", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            oldFile.renameTo(newFile);
                            renameDialog.cancel();
                            mTargetPacketPath = mTargetPacketPath.replace(mTargetPacketName, newFileName);
                            mTargetPacketName = newFileName;
                            tv_packet_desc.setText("报文名字为:\n" + mTargetPacketName + "\n保存在:\n" + mTargetPacketPath);
                            Toast.makeText(mActivity, "重命名成功", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(mActivity, "目标文件不存在", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        Button btn_cancel = (Button) renameDialog.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 点击取消重命名
                renameDialog.cancel();
            }
        });

    }

    /**
     * 弹出对话框,询问用户是否真的要删除
     * @param packetPath
     */
    private void deletePacketDialog() {
        new AlertDialog.Builder(mActivity).setMessage("客官,真的要删除该文件?")
        .setPositiveButton("是", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean deleteSuc = false;
                // 删除该报文
                File packetFile = new File(mTargetPacketPath);
                if (packetFile.exists()) {
                    // 删除单个报文
                    deleteSuc = packetFile.delete();
                }

                if (deleteSuc) {
                    Toast.makeText(mActivity, "删除成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mActivity, "删除失败", Toast.LENGTH_SHORT).show();
                }
            }
        })
        .setNegativeButton("否", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
            }
        }).show();
    }

    /**
     * 接收停止抓包的通知(单个报文大于100M的时候)
     * @author 詹子聪
     *
     */
    private class StopCapturingReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 停止抓包
            stopCapture();
            btn_scratch.setVisibility(View.VISIBLE);
            btn_stop.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化停止抓包的广播接收者(单个报文太大了)
     */
    private void initReceiver() {
        mStopCapturingReceiver = new StopCapturingReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("packet.too.large");
        mActivity.registerReceiver(mStopCapturingReceiver, filter);
    }

    /**
     * 将Tcpdump从assets文件夹复制到/data/data/com.ics.aop/files/文件夹内
     */
    private void initTcpdumpPath() {
        File fileDir = new File(mActivity.getFilesDir().getAbsolutePath());

        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        File tcpdumpFile = new File(fileDir, "tcpdump");
        try {
            if (!tcpdumpFile.exists()) {
                InputStream is = mActivity.getAssets().open("tcpdump");
                FileOutputStream fos = new FileOutputStream(tcpdumpFile);
                byte[] buf = new byte[1024];
                int count = 0;
                while ((count = is.read(buf)) > 0) {
                    fos.write(buf, 0, count);
                }
                fos.close();
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (tcpdumpFile.exists()) {
            btn_scratch.setEnabled(true);
            Toast.makeText(mActivity, R.string.msg_tcpdump_copy_suc, Toast.LENGTH_SHORT).show();
        } else {
            btn_scratch.setEnabled(false);
            Toast.makeText(mActivity, R.string.msg_tcpdump_copy_fail, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 弹出对话框让用户选择抓包类型
     */
    private void chooseTypeDialog() {

        final AlertDialog dialog = new AlertDialog.Builder(mActivity).create();
        dialog.show();
        dialog.setContentView(R.layout.dialog_choose_packet_type);
        // 设置点击对话框外面的地方不消失
        dialog.setCanceledOnTouchOutside(false);

        TextView tv_type_specify = (TextView) dialog.findViewById(R.id.tv_type_specify);
        tv_type_specify.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.cancel();

                new CleanBackgroundTask().execute();
            }
        });

        TextView tv_type_normal = (TextView) dialog.findViewById(R.id.tv_type_normal);
        tv_type_normal.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 默认抓包模式
                dialog.cancel();
                // 跳转到命名Activity
                Intent nameIntent = new Intent(mActivity, NameActivity.class);
                Bundle mBundle = new Bundle();
                mBundle.putInt("type", 0);
                nameIntent.putExtras(mBundle);
                mActivity.startActivityForResult(nameIntent, REQUEST_CODE_DEFAULT_NAME);
            }
        });
    }

    /**
     * 针对某应用抓包,从命名Activity返回的时候
     * @param appFullName
     */
    public void onAppNameResult(String appFullName, String targetPacketPath) {
        if (!TextUtils.isEmpty(appFullName)) {
            mTargetPacketPath = targetPacketPath;
            mTargetPacketName = appFullName;
            startCapture();
            startTargetApp(mAppInfo.getPackageName(), mAppInfo.getClassName());
        } else {
            //Toast.makeText(mActivity, "取消抓包", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 默认抓包,从命名Activity返回的时候
     * @param appFullName
     */
    public void onDefaultNameResult(String appFullName, String targetPacketPath) {
        if (!TextUtils.isEmpty(appFullName)) {
            mTargetPacketPath = targetPacketPath;
            mTargetPacketName = appFullName;
            startCapture();
        } else {
            //Toast.makeText(mActivity, "取消抓包", Toast.LENGTH_SHORT).show();
        }
    }

    private ProgressDialog cleanProgress;
    /**
     * 清理后台程序
     * @author 詹子聪
     *
     */
    private class CleanBackgroundTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            if (cleanProgress == null) {
                cleanProgress = new ProgressDialog(mActivity);
            }
            cleanProgress.setCancelable(false);
            cleanProgress.setMessage("正在清理后台程序...");
            cleanProgress.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // 清理后台进程
            killBackgroundApps(getBackgroundAppInfos());
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (cleanProgress != null && cleanProgress.isShowing()) {
                cleanProgress.cancel();
            }

            // 针对某应用进行抓包,弹出对话框让用户选择某应用进行抓包
            chooseAppDialog();
        }
    }

    /**
     * 弹出对话框让用户选择某应用
     */
    private void chooseAppDialog() {
        // TODO nameForPacket();
        final AlertDialog dialog = new AlertDialog.Builder(mActivity).create();
        dialog.show();
        dialog.setContentView(R.layout.dialog_choose_app);
        dialog.setCanceledOnTouchOutside(false);

        // 查询所有已经安装的应用程序
        ListView lv_app_list = (ListView) dialog.findViewById(R.id.lv_app_list);
        AppAdapter appAdapter = new AppAdapter(mActivity);
        final List<AppInfo> appInfos = new ArrayList<>();
        appAdapter.setAppInfos(appInfos);
        lv_app_list.setAdapter(appAdapter);
        lv_app_list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 选中某一个应用,则针对该应用进行流量抓包
                dialog.cancel();
                // 跳转到命名Activity
                // 有汉字先将汉字转为拼音
                AppInfo appInfo = appInfos.get(position);
                mAppInfo = appInfo;
                new ConvertAppNameTask(appInfo).execute();
            }
        });

        Button btn_choose_app_cancel = (Button) dialog.findViewById(R.id.btn_choose_app_cancel);
        btn_choose_app_cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 取消
                dialog.cancel();
            }
        });

        new FindInstalledAppsTask(appAdapter, appInfos).execute();
    }


    private ProgressDialog convertAppNameProgress;
    /**
     * 转换应用名字
     * @author 詹子聪
     *
     */
    private class ConvertAppNameTask extends AsyncTask<Void, Void, String> {

        private AppInfo appInfo;

        public ConvertAppNameTask(AppInfo appInfo) {
            // TODO Auto-generated constructor stub
            this.appInfo = appInfo;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            if (convertAppNameProgress == null) {
                convertAppNameProgress = new ProgressDialog(mActivity);
                convertAppNameProgress.setMessage("正在转换应用名字...");
                convertAppNameProgress.setCancelable(false);
            }
            convertAppNameProgress.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
            Hanzi2Pinyin hanzi2Pinyin = new Hanzi2Pinyin();
            return hanzi2Pinyin.getStringPinYin(appInfo.getName()).toLowerCase();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (convertAppNameProgress != null && convertAppNameProgress.isShowing()) {
                convertAppNameProgress.cancel();
            }

            Intent nameIntent = new Intent(mActivity, NameActivity.class);
            Bundle mBundle = new Bundle();
            mBundle.putInt("type", 1);
            mBundle.putString("appName", result);
            mBundle.putString("appVersion", appInfo.getAppVersion());
            nameIntent.putExtras(mBundle);
            mActivity.startActivityForResult(nameIntent, REQUEST_CODE_CUSTOMED_NAME);
        }

    }

    private ProgressDialog searchProgress;
    /**
     * 查找已安装应用
     * @author 詹子聪
     *
     */
    private class FindInstalledAppsTask extends AsyncTask<Void, Void, List<AppInfo>> {

        private AppAdapter adapter;
        private List<AppInfo> appInfos;
        public FindInstalledAppsTask(AppAdapter adapter, List<AppInfo> appInfos) {
            this.adapter = adapter;
            this.appInfos = appInfos;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            if (searchProgress == null) {
                searchProgress = new ProgressDialog(mActivity);
            }
            searchProgress.setCancelable(false);
            searchProgress.setMessage("正在查找已安装应用...");
            searchProgress.show();
        }

        @Override
        protected List<AppInfo> doInBackground(Void... params) {
            // TODO Auto-generated method stub
            return getInstalledAppInfos();
        }

        @Override
        protected void onPostExecute(List<AppInfo> result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            if (appInfos != null && appInfos.size() > 0) {
                appInfos.clear();
            }

            if (result != null) {
                appInfos.addAll(result);
                adapter.notifyDataSetChanged();
            }

            if (searchProgress != null && searchProgress.isShowing()) {
                searchProgress.cancel();
            }
        }

    }

    /**
     * 启动要抓包的APP
     * @param packageName 该应用的包名
     * @param className 应用的主activity类
     */
    public void startTargetApp(String packageName, String className) {
        ComponentName componet = new ComponentName(packageName, className);
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setComponent(componet);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        mActivity.startActivity(intent);
    }

    /**
     * 清掉后台进程
     */
    private void killBackgroundApps(List<AppInfo> appInfos) {
        ActivityManager activityManager = (ActivityManager) mActivity.getSystemService(Context.ACTIVITY_SERVICE);
        // 要注意不要清掉当前app
        for (AppInfo appInfo : appInfos) {
            if (!TextUtils.equals(mActivity.getPackageName(), appInfo.getPackageName())) {
                // 不是本应用的话就杀掉
                activityManager.killBackgroundProcesses(appInfo.getPackageName());
            }
        }
    }

    /**
     * 获取已安装应用信息
     * @param includeSystemApps true:包含系统应用 false:不包含系统应用
     */
    private List<AppInfo> getInstalledAppInfos() {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> resolveInfos = mActivity.getPackageManager().queryIntentActivities(mainIntent, 0);

        PackageManager pm = mActivity.getPackageManager();
        // 放到子线程中执行
        List<AppInfo> appInfos = new ArrayList<>();
        for (ResolveInfo resolveInfo : resolveInfos) {
            AppInfo appInfo = new AppInfo();
            appInfo.setName(resolveInfo.loadLabel(pm).toString());
            // 获得应用名
            appInfo.setClassName(resolveInfo.activityInfo.name);
            // 获得应用包名
            appInfo.setPackageName(resolveInfo.activityInfo.packageName);
            // 应用图标
            appInfo.setIcon(resolveInfo.activityInfo.loadIcon(pm));
            String appVersion = "";
            try {
                appVersion = mActivity.getPackageManager().getPackageInfo(resolveInfo.activityInfo.packageName, 0).versionName;
            } catch (NameNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            appInfo.setAppVersion(appVersion);
            if (!TextUtils.equals(mActivity.getPackageName(), appInfo.getPackageName())) {
                // 不是我们这个应用的话就显示出来
                appInfos.add(appInfo);
            }
        }

        Collections.sort(appInfos, new Comparator<AppInfo>() {

            @Override
            public int compare(AppInfo lhs, AppInfo rhs) {
                // TODO Auto-generated method stub
                return lhs.getName().compareTo(rhs.getName());
            }
        });
        return appInfos;
    }


    /**
     * 开始抓包
     */
    private void startCapture() {
        // 更新按钮状态
        btn_scratch.setVisibility(View.GONE);
        btn_stop.setVisibility(View.VISIBLE);
        btn_operate_latest_packet.setEnabled(false);
        isCapturing = true;
        tv_packet_desc.setText("报文名字为:\n" + mTargetPacketName + "\n保存在:\n" + mTargetPacketPath);
        try {
            mCaptureService.getBinder().transact(1, null, null, 0);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            mCaptureService = ((CaptureService.CaptureServiceBinder) service).getService();
        }
    };

    /**
     * 停止抓包
     */
    private void stopCapture() {
        try {
            mCaptureService.getBinder().transact(0, null, null, 0);
            isCapturing = false;
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        mActivity.unbindService(conn);
    }

    /**
     * 判断手机内部存储是否已经存在要保存的文件
     * @param packetName
     */
    private boolean isPacketExistInternalStorage(String packetName) {
        try {
            FileInputStream fis = mActivity.openFileInput(packetName);
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取正在运行的APP列表-------------放到子线程中执行
     */
    private List<AppInfo> getBackgroundAppInfos() {
        List<AppInfo> appInfos = new ArrayList<>();

        // 获取正在运行的进程
        ActivityManager activityManager = (ActivityManager) mActivity.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

        // 查询所有已经安装的应用程序
        PackageManager packageManager = mActivity.getPackageManager();
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);

        for (RunningAppProcessInfo appProcess : appProcesses) {
            String[] pkgList = appProcess.pkgList;
            for (String packageName : pkgList) {
                for (PackageInfo packageInfo : packageInfos) {
                    if (TextUtils.equals(packageInfo.packageName, packageName)) {
                        if (TextUtils.equals(packageName, mActivity.getPackageName())) {
                            // 如果是本应用程序,则不要添加。
                            break;
                        }
                        // 该已安装的应用程序和正在后台运行的这个应用程序是同一个
                        AppInfo appInfo = new AppInfo();
                        // 获得应用名
                        appInfo.setName(packageManager.getApplicationLabel(packageInfo.applicationInfo).toString());
                        // 获得应用包名
                        appInfo.setPackageName(packageName);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
                        appInfo.setIcon(packageInfo.applicationInfo.loadIcon(packageManager));
                        appInfo.setPid(appProcess.pid);
                        appInfos.add(appInfo);
                        break;
                    }
                }
            }
        }

        // 排序
        Collections.sort(appInfos, new Comparator<AppInfo>() {
            @Override
            public int compare(AppInfo lhs, AppInfo rhs) {
                // TODO Auto-generated method stub
                return lhs.getName().compareTo(rhs.getName());
            }
        });

        return appInfos;
    }

    public boolean isCapturing() {
        return isCapturing;
    }


    /**
     * 异步AsyncTask+HttpClient上传文件,支持多文件上传,并显示上传进度
     * @author JPH
     * Date:2014.10.09
     * last modified 2014.11.03
     */
    private class UploadUtilsAsync extends AsyncTask<String, Integer, Boolean>{
        /**服务器路径**/
        private String url;
        /**上传的参数**/
        /**要上传的文件**/
        private List<File>files;
        private long totalSize;
        private Context context;
        private ProgressDialog progressDialog;
        public UploadUtilsAsync(Context context,String url, List<File>files) {
            this.context=context;
            this.url=url;
            this.files=files;
        }

        @Override
        protected void onPreExecute() {//执行前的初始化
            // TODO Auto-generated method stub
            progressDialog=new ProgressDialog(context);
            progressDialog.setTitle("请稍等...");          
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(true);
            progressDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(String... params) {//执行任务
            // TODO Auto-generated method stub
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
            int count=0;
            for (File file:files) {
//              FileBody fileBody = new FileBody(file);//把文件转换成流对象FileBody
//              builder.addPart("file"+count, fileBody);
                builder.addBinaryBody("file"+count+"_"+ForkConstants.userId, file);
                count++;
            }       
//          builder.addTextBody(ForkConstants.userId, "userId");//设置请求参数
            builder.addTextBody("method", "method");//设置请求参数
            builder.addTextBody("fileTypes", ".pcap");//设置请求参数
            HttpEntity entity = builder.build();// 生成 HTTP POST 实体      

//          List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
//          paramPairs.add(new BasicNameValuePair("userId", ForkConstants.userId));

            totalSize = entity.getContentLength();//获取上传文件的大小
            ProgressOutHttpEntity progressHttpEntity = new ProgressOutHttpEntity(
                    entity, new ProgressListener() {
                        @Override
                        public void transferred(long transferedBytes) {
                            publishProgress((int) (100 * transferedBytes / totalSize));//更新进度
                        }
                    });
            return uploadFile(url, progressHttpEntity);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {//执行进度
            // TODO Auto-generated method stub
            Log.i("info", "values:"+values[0]);
            progressDialog.setProgress((int)values[0]);//更新进度条
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Boolean result) {//执行结果
            // TODO Auto-generated method stub
            progressDialog.dismiss();
            super.onPostExecute(result);

            if (result) {
                // 上传成功
                Toast.makeText(mActivity, "上传成功", Toast.LENGTH_SHORT).show();
            } else {
                // 上传失败
                Toast.makeText(mActivity, "上传失败", Toast.LENGTH_SHORT).show();
            }
        }
        /**
         * 向服务器上传文件
         * @param url
         * @param entity
         * @return
         */
        public boolean uploadFile(String url, ProgressOutHttpEntity entity) {               
            HttpClient httpClient=new DefaultHttpClient();// 开启一个客户端 HTTP 请求 
            httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);// 设置连接超时时间


            HttpPost httpPost = new HttpPost(url);//创建 HTTP POST 请求  


            httpPost.setEntity(entity);
            try {
                HttpResponse httpResponse = httpClient.execute(httpPost);
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    return true;
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (ConnectTimeoutException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (httpClient != null && httpClient.getConnectionManager() != null) {
                    httpClient.getConnectionManager().shutdown();
                }
            }
            return false;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ithouse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值