问题
I found this code on the web:
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();
}
}
This is the 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());
}
}
I have a swipeview
with 3 tab.xml (tab1.xml, tab2.xml and tab3.xml) In the tab1 there is the id of cpu info.
<?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>
If I try to run this code in a new application it goes well and show me the cpu info. When I put the code in my application it crashes on startup! The log is clean, none errors. Nothing.. It's so strange. I use the swipeview.. Is it a problem?
回答1:
The line:
05-23 20:58:37.803: E/AndroidRuntime(30025): at `eu.lucazanini.swipeviews.MainActivity.onCreate(MainActivity.java:49)`
suggests that the java.lang.NullPointerException
is occurring in your onCreate method. Looking at the code you posted, my guess is that findViewById(R.id.CPUinfo)
is returning null. I suggest that you add Log.d(...)
to print out whether CPUinfo
is null or not.
来源:https://stackoverflow.com/questions/16721614/get-cpu-info-programmatically-on-android-application