PackageManager相关

Vision-Language Navigation - Windows环境下编译安装Matterport3D Simulator仿真器(三) 目录1 编译 Matterport3D Simulator 源码1.1 源码下载1.2 编译 1 编译 Matterport3D Simulator 源码   在 Windows 下编译 Matterport3D Simulator 稍微有些不方便,需要对 CMakeLists.txt 进行一些修改,如果有更好的方法欢迎大家评论。 1.1 源码下载   还是直接在 Github 上搜索 Matterport3D Simulator 的 repo,下载源码。如果用 zip 方式,那么直接在下即可。如果使用 阅读详情
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;
        }
    }
}
labelImg使用教程 Anaconda环境 安装 Anaconda 之后,在开始菜单下找到 Anaconda 文件夹 找到 Anaconda Prompt 点击运行 安装 labelImg pip install labelImg #直接命令行输入 启动 labelImg labelImg #直接命令行输入名称即可 labelImg界面 开始标注 快捷键:W(创建方框),A(上一张),D(下一张) XML文件示例 <annotation> <folder>夜读</folder> 阅读详情

相关推荐

Rasa Core开发指南

文章目录1. Rasa Core简介1.1 Rasa Core消息处理流程1.2 安装Rasa Core2. Dialogue模型训练2.1 Story样本数据2.2 Domain2.2.0 intents2.2.1 actions2.2.2 templates2.2.3 entities2.2.4 slots3 .训练和使用对话模型3.1 训练对话模型3.2 使用对话模型4. 搭建CustomA...

老蒋也疯狂 1万+

PackageManager()的使用列举相关的事件

<br />PackageManager相关 本类API是对所有基于加载信息的数据结构的封装,包括以下功能: 安装,卸载应用 查询permission相关信息 查询Application相关信息(application,activity,receiver,service,provider及相应属性等) 查询已安装应用 增加,删除permission 清除用户数据、缓存,代码段等 非查询相关的API需要特定的权限,具体的API请参考SDK文档。 ActivityManager相关 本类API是对运行时管理功能

wal812834184的专栏 5572

Windows 下安装 ros2 的超详细教程

Windows11 ROS安装

2401_83363439的博客 3319

packageManager resolveInfo相关使用

首先我们来看一下PackageItemInfo,它是包含了一些信息的基类,它的直接子类有: ApplicationInfo、 ComponentInfo、InstrumentationInfo、PermissionGroupInfo、PermissionInfo。    它的间接子类有:ActivityInfo、ProviderInfo、ServiceInfo。这个类包含的信息对于所有包中项目

maximus_chan的专栏 879

用Typora画流程图和序列图:Mermaid语法实战教程(含常见报错解决)

本文是一份详细的Typora与Mermaid语法实战教程,教你如何在Markdown文档中高效绘制流程图和序列图。文章涵盖从环境配置、核心语法到复杂图表构建的全过程,并重点解析了常见报错原因与解决方案,助你将可视化图表无缝融入文档工作流。

weixin_29279101的博客 299

Tessent ICL语法详解:如何高效定义SIB、TDR和TAP模块

本文深入解析Tessent ICL语法,指导如何高效定义SIB、TDR和TAP模块以构建芯片测试网络。通过实战代码示例,详细阐述了各模块的端口声明、接口角色与核心寄存器定义,并提供了顶层集成连接方法与调试技巧,帮助DFT工程师精准描述测试仪器拓扑,提升Tessent工具链使用效率。

silver的专栏 492

PackageManager()的使用列举相关的事件 ActivityManage

PackageManager相关 本类API是对所有基于加载信息的数据结构的封装,包括以下功能: 安装,卸载应用 查询permission相关信息 查询Application相关信息(application,activity,receiver,service,provider及相应属性等) 查询已安装应用 增加,删除permission 清除用户数据、缓存,代码段等 非查询相关的API需要特定

汪小哥 694

点到面点云配准(Point To Plane)算法知识详解和详细推导,C++代码实现

点到面 ICP (Iterative Closest Point) 是在 3D 点云配准中常见的一种变体,通过最小化点到对应面(由法向量定义的局部平面)的距离来提高收敛速度和精度。

qq_36812406的博客 1810

PackageManager相关文章

本节内容是如何获取Android系统中应用程序的信息,主要包括packagename、label、icon、占用大小等。具体分为两个  部分,计划如下:             第一部分: 获取应用程序的packagename、label、icon等 ;             第二部分: 获取应用程序的占用大小,包括:缓存大小(cachsize)、数据大小(datasize)。

凡间Android 696

基于模糊神经网络实现水质评价预测 - Matlab源码

首先定义输入层、隐含层和输出层的节点数,并初始化权重和阈值,然后开始训练模型,在每轮训练中通过比较模型的输出值与实际值的误差来更新权重和阈值,直到误差达到最小值,为了提高模型的性能,我们可以采用交叉验证等技术进行优化。首先需要准备好数据集,使用的是嘉陵江的水质监测数据集,数据集包含了多个指标,如 pH 值、溶解氧、总氮、总磷等,以及相应的水质等级,我们需要将数据集分为训练集和测试集。在当今环境日益恶化的情况下,水质监测变得越来越重要,模糊神经网络作为一种新型的。

weixin_50547796的博客 147

双向升压和降压的DC-DC转换器设计

c复制// 类型定义与常量MODE_FORWARD_BOOST, // 正向升压模式(输入700V→输出1200V)MODE_FORWARD_BUCK, // 正向降压模式(输入700V→输出<700V)MODE_REVERSE_BOOST, // 反向升压模式(输入1200V→输出700V)MODE_REVERSE_BUCK // 反向降压模式(输入<700V→输出700V)// 硬件参数float Vin;// 输入电压(0-1200V)

567

获取APK 包的相关信息PackageManager 第一部分

public class test4 extends Activity {              @Override       public void onCreate(Bundle savedInstanceState) {           super.onCreate(savedInstanceState);                  setContentView(

wjdarwin的专栏 991

【AI Agent系列】【阿里AgentScope框架】深入源码:Msg是如何转变成模型需要的Prompt形式的?多模态Prompt如何构建?

前面咱们学习AgentScope,在使用Agent来对话时,输入为一个 Msg 对象,不能是字符串,然后在Agent内部,会将Msg对象转换为模型接受的Prompt。那 AgentScope 如何根据 Msg 形成相应模型接收的Prompt结构的?如何使用 Msg 带入更多的参数,传递给大模型呢?

同学小张的博客 1535

Android系统信息 、PackageManager、ActivityManager相关

1.Android系统信息的获取:获取Android系统信息有两种方式,分别是android.os.Build和SystemProperty。比如:Build.BRAND 可以获取到brand名称,System.getProperty("os.version”)可以拿到version名称等。2.PackageManager;packageManager的一些常用方法:getPackageManag...

most_xiaoya的专栏 408

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

PackageManager的简单用法

android系统中,有很多管理服务相关的类:TelephoneManager,WindowManager,SmsManager,ActivityManager等。 本文主要介绍下packageManager。这个服务主要用户获取应用程序中的packageName,icon,label等,初次之外,他也可以获取应用程序的占用内存大小以及缓存大小等信息。 •安装,卸载应用 •查询perm

hardcum2的专栏 1万+

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

android PackageManager和PackageInstall

我们每天都在安装和卸载APK(安卓应用程序包文件),或许一天会有好几次,但是你有想过下面问题吗? 什么是Package Manager(包管理器)和Package Installer(程序安装包)?APK文件保存在Android的哪个地方?APK文件安装过程的细节是怎样的?Package Manager(包管理器)是怎样保存数据的?我应该去哪里找Package Manager和Package

u013673422的专栏 3525

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

PackageManager详解

一、PackageManager的功能:   1、安装,卸载应用  2、查询permission相关信息  3、查询Application相关信息(application,activity,receiver,service,provider及相应属性等)  4、查询已安装应用  5、增加,删除permission  6、清除用户数据、缓存,代码段等        二、Pa

qq_26817313的博客 1152

android之PackageManager

进行中。。。

lanqiaowang的博客 225
上一篇: TextView代码setTextColor无效
下一篇: 启动第三方应用(未测试)
ithouse
博客等级 码龄12年 200粉丝 212原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

ithouse

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

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

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

打赏作者

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

抵扣说明:

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

余额充值