gpt4 book ai didi

android - 在android应用程序上以编程方式获取cpu信息

转载 作者:太空狗 更新时间:2023-10-29 13:30:03 25 4
gpt4 key购买 nike

我在网上找到这段代码:

package com.exercise.AndroidCPUinfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView CPUinfo = (TextView) findViewById(R.id.CPUinfo);
CPUinfo.setText(getInfo());

}

private String getInfo() {
StringBuffer sb = new StringBuffer();
sb.append("abi: ").append(Build.CPU_ABI).append("\n");
if (new File("/proc/cpuinfo").exists()) {
try {
BufferedReader br = new BufferedReader(
new FileReader(new File("/proc/cpuinfo")));
String aLine;
while ((aLine = br.readLine()) != null) {
sb.append(aLine + "\n");
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

这是 MainActivity.java

package eu.lucazanini.swipeviews;

import android.app.ActionBar;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends FragmentActivity {

CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
TextView textOut;
// Notification code

private static final int SIMPLE_NOTIFICATION_ID = 1;

NotificationManager mNotificationManager;
// fine
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Readcpuinfo
TextView CPUinfo = (TextView) findViewById(R.id.CPUinfo);
CPUinfo.setText(getInfo());
//fine readcpuinfo

// Notification code
mNotificationManager = (NotificationManager) `getSystemService(Context.NOTIFICATION_SERVICE);`

View btnradio_hindi = findViewById(R.id.radio_hindi);
// fine
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());

// Set up action bar.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
}
private String getInfo() {
StringBuffer sb = new StringBuffer();
sb.append("abi: ").append(Build.CPU_ABI).append("\n");
if (new File("/proc/cpuinfo").exists()) {
try {
BufferedReader br = new BufferedReader(new FileReader(new `File("/proc/cpuinfo")));`
String aLine;
while ((aLine = br.readLine()) != null) {
sb.append(aLine + "\n");
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

/// Inizio creazione funzioni

public Boolean execCommands(String... command) {
try {
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());

for(int i = 0; i < command.length; i++) {
os.writeBytes(command[i] + "\n");
os.flush();
}
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (IOException e) {
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}

/**
* A {@link android.support.v4.app.FragmentStatePagerAdapter} that returns a
* fragment representing an object in the collection.
*/
public class CollectionPagerAdapter extends FragmentStatePagerAdapter {

final int NUM_ITEMS = 3; // number of tabs

public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}

@Override
public int getCount() {
return NUM_ITEMS;
}

@Override
public CharSequence getPageTitle(int position) {

String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.label1);
break;
case 1:
tabLabel = getString(R.string.label2);
break;
case 2:
tabLabel = getString(R.string.label3);
break;
}

return tabLabel;
}
}

/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class TabFragment extends Fragment {

public static final String ARG_OBJECT = "object";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);

int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.tab1;
break;
case 1:
tabLayout = R.layout.tab2;
break;
case 2:
tabLayout = R.layout.tab3;
break;
}

View rootView = inflater.inflate(tabLayout, container, false);

return rootView;
}
}
public void onRadioButtonClicked(View view) {

((RadioButton) view).isChecked();

// Check which radio button was clicked
// switch(view.getId()) {
// case R.id.radio_hindi:
// if (checked)

switch (view.getId())
{
case R.id.radio_hindi:
String[] commands = {
"echo 3 > /proc/sys/vm/drop_caches",
"cat /proc/meminfo | awk 'NR == 2'"

};
sendSimpleNotification();
Toast.makeText(this, "Hai liberato memoria! Hai: " + `Runtime.getRuntime().freeMemory() + "", Toast.LENGTH_LONG).show();`
execCommands(commands);

String commandText = "echo 'foo' >> /sdcard/foo.txt\necho 'bar' >> `/sdcard/foo.txt";`

execCommands(commandText.split("\n"));
break;

case R.id.radio_english:
String[] commands1 = {"echo ondemand > `/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor",`
"/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor"};
execCommands(commands1);
sendSimpleNotificationOndemand();
Toast.makeText(this, "Hai selezionato il governor Ondemand", `Toast.LENGTH_LONG).show();`
break;
case R.id.interactive_btn:
String[] commands2 = {"echo interactive > `/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor",`
"/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor"};
execCommands(commands2);
sendSimpleNotificationInteractive();
Toast.makeText(this, "Hai selezionato il governor: Interactive", `Toast.LENGTH_LONG).show();`
break;
case R.id.conservative_btn:
String[] commands3 = {"echo conservative > `/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor",`
"/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor"};
execCommands(commands3);
sendSimpleNotificationConservative();
Toast.makeText(this, "Hai selezionato il governor: Conservative", `Toast.LENGTH_LONG).show();`
break;
}
}
protected void cancelSimpleNotification() {
mNotificationManager.cancel(SIMPLE_NOTIFICATION_ID);
}
private void sendSimpleNotification() {

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);

// Titolo e testo della notifica
notificationBuilder.setContentTitle("Boost RAM");
notificationBuilder.setContentText("Memoria libera: "+ `Runtime.getRuntime().freeMemory() + "bytes");`

// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Memoria liberata con successo");

// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());

// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);

// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);

notificationBuilder.setContentIntent(contentIntent);

// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
// Notification per il governor ondemand
private void sendSimpleNotificationOndemand() {

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);

// Titolo e testo della notifica
notificationBuilder.setContentTitle("Governor Changed");
notificationBuilder.setContentText("Hai selezionato il governor Ondemand");

// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Governor Ondemand settato");

// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());

// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);

// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);

notificationBuilder.setContentIntent(contentIntent);

// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}

//Notification per il governor interactive
private void sendSimpleNotificationInteractive() {

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);

// Titolo e testo della notifica
notificationBuilder.setContentTitle("Governor Changed");
notificationBuilder.setContentText("Hai selezionato il governor Interactive");

// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Governor Interactive settato");

// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());

// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);

// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);

notificationBuilder.setContentIntent(contentIntent);

// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}

//Notification per il governor conservative
private void sendSimpleNotificationConservative() {

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);

// Titolo e testo della notifica
notificationBuilder.setContentTitle("Governor Changed");
notificationBuilder.setContentText("Hai selezionato il governor Conservative");

// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Governor Conservative settato");

// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());

// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);

// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);

notificationBuilder.setContentIntent(contentIntent);

// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
}

我有一个带有 3 个 tab.xml(tab1.xml、tab2.xml 和 tab3.xml)的 swipeview 在 tab1 中有 cpu 信息的 id。

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="CHANGE GOVERNOR"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FF8000"
tools:ignore="HardcodedText" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Change the CPU Governor: "
android:textColor="#00AEEF"
tools:ignore="HardcodedText" />

<RadioButton
android:id="@+id/radio_english"
android:layout_width="201dp"
android:layout_height="55dp"
android:onClick="onRadioButtonClicked"
android:text="OnDemand"
tools:ignore="HardcodedText" />

<RadioButton
android:id="@+id/interactive_btn"
android:layout_width="200dp"
android:layout_height="55dp"
android:onClick="onRadioButtonClicked"
android:text="Interactive"
tools:ignore="HardcodedText" />

<RadioButton
android:id="@+id/conservative_btn"
android:layout_width="200dp"
android:layout_height="55dp"
android:layout_gravity="fill"
android:onClick="onRadioButtonClicked"
android:text="Conservative"
tools:ignore="HardcodedText" />

<TextView
android:id="@+id/AndroidCPUInfo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Android CPU Info.:"
tools:ignore="HardcodedText" />

<TextView
android:id="@+id/CPUinfo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:ignore="SelectableText" />

</RadioGroup>

如果我尝试在新应用程序中运行这段代码,它会很顺利并显示 cpu 信息。当我将代码放入我的应用程序时,它在启动时崩溃了!日志很干净,没有错误。没什么.. 太奇怪了。我用的是swipeview..有问题吗?

最佳答案

行:

05-23 20:58:37.803: E/AndroidRuntime(30025): at `eu.lucazanini.swipeviews.MainActivity.onCreate(MainActivity.java:49)`

表明 java.lang.NullPointerException 发生在您的 onCreate 方法中。查看您发布的代码,我的猜测是 findViewById(R.id.CPUinfo) 返回 null。我建议您添加 Log.d(...) 以打印出 CPUinfo 是否为空。

关于android - 在android应用程序上以编程方式获取cpu信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16721614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com