我正在尝试设计一个android应用程序,它首先以最高cpu使用率杀死正在运行的进程。我需要知道如何通过进程获得cpu使用率,然后如何终止进程。下面是我当前尝试执行此操作的代码+我知道activity manager已被弃用`包com.example.osproject;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private ActivityManager mActivityManager;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermissions(new String[]{Manifest.permission.KILL_BACKGROUND_PROCESSES}, 1);
// requestPermissions(new String [] { Manifest.permission.PACKAGE_USAGE_STATS}, 1);
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
intent.setData(Uri.parse("package:"+ getApplicationContext().getPackageName()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, 0);
myButton = findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
kill();
}
});
}
public void kill() {
String topPackageName ;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");
long time = System.currentTimeMillis();
// We get usage stats for the last 10 seconds
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time);
// Sort the stats by the last time used
if(stats != null) {
SortedMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
Log.e("test", usageStats.getPackageName());
}
if(!mySortedMap.isEmpty()) {
topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
}
}
}
`
暂无答案!
目前还没有任何答案,快来回答吧!