我已经在StackOverflow上研究了这个错误并尝试了所有的建议,但仍然有错误。应用程序尝试加载,我可以看到几个警报背后的主屏幕以及应用程序关闭的错误。
我尝试的事情:
添加到Manifest -
在MainActivity
中,确保我使用" this
"代替其他参考文献
添加到AlertDialog
-
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
注意:我还在onCreate()
之后的MainActivity
setContentView(R.layout.activity_main);
中注释掉了所有内容,但仍然有错误。我怀疑这个问题与我如何使用我的片段和tjerk直接相关。 ActionSlideExpandableListView
菜单。
我的代码: 的 MainActivity
public class MainActivity extends Activity implements DataPasser {
private final String LOGCAT = "MAINACTIVITY.LOGCAT";
private DrawerLayout mDrawerLayout;
Toolbar toolbar;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
Fragment fragment = null;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
Menu menuMain;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
// --------------------------------------------------
private final String PREF_NAME = "band_wit";
String firstLaunch = "firstLaunch", itemPosition = "2";
private TCPdump tcpdump = null;
private TCPdumpHandler tcpDumpHandler = null;
static public String local_Ip_Address;
DBHelper dbHelper;
FragmentManager fragmentManager;
private MyReceiver receiver;
private static final int VPN_REQUEST_CODE = 0x0F;
private boolean waitingForVPNStart;
public static String APP_UID;
public static String NETFLIX_APP_UID;
public static String FACEBOOK_APP_UID;
private BroadcastReceiver vpnStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (LocalVPNService.BROADCAST_VPN_STATE.equals(intent.getAction())) {
if (intent.getBooleanExtra("running", false))
waitingForVPNStart = false;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = DBHelper.newInstance(this);
local_Ip_Address = getLocalIpAddress();
// Local VPN
LocalBroadcastManager.getInstance(this).registerReceiver(
vpnStateReceiver,
new IntentFilter(LocalVPNService.BROADCAST_VPN_STATE));
// ====
Intent tcp_Dump_Inent = new Intent(MainActivity.this,TcpDumpService.class);
startService(tcp_Dump_Inent);
/* start service for download manager */
startService(new Intent(this, MyDownloaderMangerService.class));
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
// Find People
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
// Pages
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// ** setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(this,
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
toolbar,
//R.drawable.ic_drawer,
R.string.app_name,
R.string.app_name)
{
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
startService(new Intent(this, MyService.class));
// Run when application first time launched
Const.preferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
boolean isFirstTime = Const.preferences.getBoolean(firstLaunch, true);
if (isFirstTime) {
Const.preferences.edit().putBoolean(firstLaunch, false).commit();
addBgData(Const.preferences);
setInitialDataBucket();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.splash_screen, null);
builder.setView(view);
dialog = builder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
}
APP_UID = myAppUid("com.oda.bandwit");
NETFLIX_APP_UID = myAppUid("com.netflix.mediaclient");
FACEBOOK_APP_UID = myAppUid("com.facebook.katana");
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
try {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new MyReceiver();
registerReceiver(receiver, filter);
} catch (Exception e) {
// TODO: handle exception
}
startVPN();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try {
unregisterReceiver(receiver);
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int fragment = 0;
Fragment f = this.getFragmentManager().findFragmentById(
R.id.frame_container);
if (f instanceof HomeFragment) {
fragment = 0;
} else if (f instanceof GeneralSettingsFragment) {
fragment = 1;
} else if (f instanceof ApplicationSettinsFragment) {
fragment = 2;
} else if (f instanceof NetworkSettingsFragment) {
fragment = 3;
} else if (f instanceof GraphAnalysisFragment) {
fragment = 4;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.menuToday:
menuMain.findItem(R.id.menuSelectedItem).setTitle("Today");
itemPosition = "0";
displayView(fragment);
return true;
case R.id.menuThisWeek:
menuMain.findItem(R.id.menuSelectedItem).setTitle("Current Week");
itemPosition = "1";
displayView(fragment);
return true;
case R.id.menuThisMonth:
menuMain.findItem(R.id.menuSelectedItem).setTitle("Current Month");
itemPosition = "2";
displayView(fragment);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menuMain = menu;
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menuMain.findItem(R.id.menuToday).setVisible(!drawerOpen);
menuMain.findItem(R.id.menuThisWeek).setVisible(!drawerOpen);
menuMain.findItem(R.id.menuThisMonth).setVisible(!drawerOpen);
menuMain.getItem(Integer.parseInt(itemPosition)).setChecked(true);
return super.onPrepareOptionsMenu(menuMain);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
try {
fragment = new HomeFragment("" + itemPosition);
callFragment(position);
} catch (Exception e) {
e.getMessage();
}
break;
case 1:
fragment = new ApplicationSettinsFragment();
callFragment(position);
break;
case 2:
startActivity(new Intent(MainActivity.this, GraphicalAnalysis.class));
break;
case 3:
sendMail();
break;
case 4:
dialog = new Dialog(MainActivity.this);
Toast.makeText(MainActivity.this, "Change Limit", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Set Threshold");
ListView list=new ListView(MainActivity.this);
ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
new String[]{"5","10","15","20","25","30","35","40","45","50","55","60","65","70","75","80","85","90","95","100","105","110","115","120","125","130","135","140","145","150","155","160","165","170","175","180","185","190","195","200"});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Toast.makeText(MainActivity.this,
"Now Threshold " + (position + 1) * 5 +" is set",
Toast.LENGTH_SHORT).show();
LocalVPNService.netFlixMaxVal = (position + 1) * 5;
navDrawerItems.get(4).setCount(""+LocalVPNService.netFlixMaxVal);
MainActivity.this.adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
builder.setView(list);
dialog=builder.create();
dialog.show();
break;
case 5:
fragment = new WhatsHotFragment();
callFragment(position);
break;
default:
break;
}
}
Dialog dialog;
private void callFragment(int position) {
if (fragment != null) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VPN_REQUEST_CODE && resultCode == RESULT_OK) {
startService(new Intent(this, LocalVPNService.class));
}
}
}
Home Fragment
public class HomeFragment extends Fragment {
Boolean checked;
DBHelper dbHelper;
String filterFlag = "", networkTypeSelected = "";
CustomAdapter adap = null;
OnClickListener clickListener;
TextView tvNetworkType;
SharedPreferences prefs;
private static String FILENAME = "mlogs.txt";
public HomeFragment() {
// TODO Auto-generated constructor stub
}
public HomeFragment(String dataFilter) {
filterFlag = dataFilter;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_home,
container, false);
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
try {
dbHelper = DBHelper.newInstance(getActivity());
tvNetworkType = (TextView) rootView
.findViewById(R.id.tvNetworkTypeHome);
clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Editor edit = prefs.edit();
if (v.getId() == R.id.btnCellularHome) {
checked = false;
tvNetworkType.setText("Cellular Data");
edit.putString("network", "0");
} else if (v.getId() == R.id.btnWifiHome) {
checked = true;
tvNetworkType.setText("Wi-fi Data");
edit.putString("network", "1");
}
edit.commit();
setListViewData(rootView);
}
};
rootView.findViewById(R.id.btnCellularHome).setOnClickListener(
clickListener);
rootView.findViewById(R.id.btnWifiHome).setOnClickListener(
clickListener);
if (prefs.getString("network", "0").equalsIgnoreCase("1")) {
checked = true;
tvNetworkType.setText("Wi-fi Data");
} else {
tvNetworkType.setText("Cellular Data");
checked = false;
}
setListViewData(rootView);
} catch (Exception e) {
e.getMessage();
}
TextView ytdata = (TextView) rootView.findViewById(R.id.ytdata);
TcpDumpUtills tcpDumpUtills = new TcpDumpUtills(getActivity());
ytdata.setText(StringUtils.formatToMultiplier(tcpDumpUtills
.getAppsConsumedData("com.google.android.youtube")));
ytdata.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
writeDataToFile(log.toString());
} catch (IOException e) {
}
}
});
super.onSaveInstanceState(savedInstanceState);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//mContext = activity;
}
public void writeDataToFile(String data){
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getActivity(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getActivity(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(getActivity().openFileOutput(FILENAME, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Logss", "File write failed: " + e.toString());
}
}
public ListAdapter getData() {
Resources res = getResources();
ArrayList<ListModel> arr = new ArrayList<ListModel>();
ArrayList<ListModel> arrFinal = new ArrayList<ListModel>();
String networkType = "";
if (checked) {
networkType = "1";
} else {
networkType = "0";
}
PackageManager manager = getActivity().getPackageManager();
arr = dbHelper.getAppsDataAccordingToNetworkType(networkType);
if (arr.size() >= 1) {
for (ListModel modelGetter : arr) {
ListModel modelSetter = new ListModel();
String packageName = modelGetter.getAppName();
// Setting App Name
try {
ApplicationInfo appInfo = manager.getApplicationInfo(
modelGetter.getAppName(), 0);
String appName = "" + manager.getApplicationLabel(appInfo);
modelSetter.setAppName(appName);
// Setting Total Data Consumned by the app
long appTotalData = getTotalDataPerApp(modelGetter
.getAppName());
modelSetter.setDataConsumed(appTotalData);
String appTotalDataStr = CommonFunctions
.humanReadableByteCount(appTotalData, false);
modelSetter.setTotalData(appTotalDataStr);
// Setting Total Data as per the network selected
long networkDataPerApp = getDailyNetworkDataPerApp(
modelGetter.getNetworkData(), packageName);
String networkDataStr = CommonFunctions
.humanReadableByteCount(networkDataPerApp, false);
modelSetter.setNetworkData(networkDataStr);
double percd = networkDataPerApp / (double) appTotalData
* 100;
int perc = (int) percd;
modelSetter.setPercenatge(perc);
// Setting App Icon
Drawable draw = manager.getApplicationIcon(modelGetter
.getAppName());
modelSetter.setDrawable(draw);
// Setting Today's Data
long appTodaysData = getUsageData(packageName);
String appTodayDataStr = CommonFunctions
.humanReadableByteCount(appTodaysData, false);
modelSetter.setTodaysData(appTodayDataStr);
Calendar cal = Calendar.getInstance();
long dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
long dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
long time = cal.get(Calendar.HOUR_OF_DAY);
long appConsumptionRate = getConsumptionRate(cal,
appTotalData);
String appConsumptionDataStr = CommonFunctions
.humanReadableByteCount(appConsumptionRate, false);
if (filterFlag.equalsIgnoreCase("0")) {
appConsumptionDataStr = appConsumptionDataStr + " /hr";
} else if (filterFlag.equalsIgnoreCase("1")) {
appConsumptionDataStr = appConsumptionDataStr + " /day";
}else if (filterFlag.equalsIgnoreCase("2")) {
appConsumptionDataStr = appConsumptionDataStr + " /day.";
}
modelSetter.setConsumptionRate(appConsumptionDataStr);
// Setting Forecast Data
long appForecastData = getForecastData(appConsumptionRate,
dayOfMonth, dayOfWeek, time, appTotalData);
String appForecastDataStr = CommonFunctions
.humanReadableByteCount(appForecastData, false);
modelSetter.setForecastData(appForecastDataStr);
arrFinal.add(modelSetter);
} catch (Exception e) {
e.getMessage();
}
}
} else {
ListModel modelSetter = new ListModel();
modelSetter.setAppName("No Data");
modelSetter.setConsumptionRate("0.0 KB");
modelSetter.setForecastData("0.0 KB");
modelSetter.setNetworkData("0.0 KB");
modelSetter.setTodaysData("0.0 KB");
modelSetter.setTotalData("0.0 KB");
arrFinal.add(modelSetter);
}
Collections.sort(arrFinal, new Comparator<ListModel>() {
@Override
public int compare(ListModel lhs, ListModel rhs) {
// TODO Auto-generated method stub
return lhs.getDataConsumed() > rhs.getDataConsumed() ? -1
: lhs.getDataConsumed() < rhs.getDataConsumed() ? 1
: 0;
}
});
adap = new CustomAdapter(getActivity(), arrFinal, res, networkType);
adap.notifyDataSetChanged();
return adap;
}
public void setListViewData(View view) {
try {
ListAdapter adap = getData();
ActionSlideExpandableListView list = (ActionSlideExpandableListView) view
.findViewById(R.id.list);
list.setAdapter(adap);
list.setSmoothScrollbarEnabled(true);
// listen for events in the two buttons for every list item.
// the 'position' var will tell which list item is clicked
} catch (Exception e) {
e.getMessage();
}
}
private long getTotalDataPerApp(String packageName) {
String[] arr = CommonFunctions.getDateAccordingToDuration(filterFlag);
String sDate = arr[0];
String eDate = arr[1];
long data = dbHelper.getDailyTotalDataPerApp(sDate, eDate, packageName);
return data;
}
private long getDailyNetworkDataPerApp(String networkType,
String packageName) {
String[] arr = CommonFunctions.getDateAccordingToDuration(filterFlag);
String sDate = arr[0];
String eDate = arr[1];
long data = dbHelper.getDailyNetworkDataPerApp(sDate, eDate,
networkType, packageName);
return data;
}
private long getUsageData(String packageName) {
String[] arr = CommonFunctions.getDateAccordingToDuration(filterFlag);
String sDate = arr[0];
String eDate = arr[1];
long data = dbHelper.getDailyTotalDataPerApp(sDate, eDate, packageName);
return data;
}
private long getForecastData(long cRate, long dayOfMonth, long dayOfWeek,
long time, long appTotalData) {
long output = 0;
if (filterFlag.equalsIgnoreCase("0")) {
output = (cRate * (24 - time)) + appTotalData;
} else if (filterFlag.equalsIgnoreCase("1")) {
long leftDaysOfWeek = 7 - dayOfWeek;
output = (cRate * leftDaysOfWeek) + appTotalData;
} else if (filterFlag.equalsIgnoreCase("2")) {
long leftDaysOfMonth = 31 - dayOfMonth;
output = (cRate * leftDaysOfMonth) + appTotalData;
}
return output;
}
private long getConsumptionRate(Calendar cal, long totalData) {
long output = 0;
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int time = cal.get(Calendar.HOUR_OF_DAY);
if (filterFlag.equalsIgnoreCase("0")) {
output = totalData / time;
} else if (filterFlag.equalsIgnoreCase("1")) {
output = totalData / dayOfWeek;
} else if (filterFlag.equalsIgnoreCase("2")) {
output = totalData / dayOfMonth;
}
return output;
}
public ListAdapter buildDummyData() {
final int SIZE = 20;
String[] values = new String[SIZE];
for (int i = 0; i < SIZE; i++) {
values[i] = "Item " + i;
}
return new ArrayAdapter<String>(getActivity(),
R.layout.expandable_list_item, R.id.tvAppName, values);
}
}
崩溃日志 11-19 21:33:24.010 12557-12557 / com.oda.bandwit E / AndroidRuntime:FATAL EXCEPTION:main 处理:com.oda.bandwit,PID:12557 android.view.WindowManager $ BadTokenException:无法添加窗口 - 令牌null不适用于应用程序 在android.view.ViewRootImpl.setView(ViewRootImpl.java:682) 在android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342) 在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93) 在android.app.Dialog.show(Dialog.java:316) 在android.app.AlertDialog $ Builder.show(AlertDialog.java:1112) at com.oda.bandwit.TcpDumpService.startTCPdump(TcpDumpService.java:98) at com.oda.bandwit.TcpDumpService.access $ 000(TcpDumpService.java:22) 在com.oda.bandwit.TcpDumpService $ 1.run(TcpDumpService.java:62) 在android.os.Handler.handleCallback(Handler.java:751) 在android.os.Handler.dispatchMessage(Handler.java:95) 在android.os.Looper.loop(Looper.java:154) 在android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:865) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)