Я изменил приложение BasicNetworking (я добавил 3 функции: checkNetworkConnection () и getMCC () и saveToFile (String data)), чтобы записать данные MCC в файл MCClijst.csv (в первый раз без добавления; позже я буду добавлять добавление). Я пытаюсь записать данные (код MCC смартфона) и получить IOexception: «нет такого файла или каталога». (Путь - / storage / emulated / 0 / mcc)
Я использую Android Suite для отладки. Мое устройство подключено, и я использую «продолжить без мгновенного запуска». Я вручную создал папку / mcc на смартфоне. Таким образом, файл 'MCClijst.csv' не существует в папке emulate / 0 / mcc, и я хочу его создать.
package com.example.android.basicnetworking;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogFragment;
import com.example.android.common.logger.LogWrapper;
import com.example.android.common.logger.MessageOnlyLogFilter;
import android.telephony.TelephonyManager;import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.os.Environment;
/**
* Sample application demonstrating how to test whether a device is connected,
* and if so, whether the connection happens to be wifi or mobile (it could be
* something else).
*
* This sample uses the logging framework to display log output in the log
* fragment (LogFragment).
*/
public class MainActivity extends FragmentActivity {
final static String fileName = "MCClijst.csv";
final static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mcc/" ;
//final static String TAG = FileHelper.class.getName();
public static final String TAG = "Basic Network Demo";
// Whether there is a Wi-Fi connection.
private static boolean wifiConnected = false;
// Whether there is a mobile connection.
private static boolean mobileConnected = false;
// Reference to the fragment showing events, so we can clear it with a button
// as necessary.
private LogFragment mLogFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
// Initialize text fragment that displays intro text.
SimpleTextFragment introFragment = (SimpleTextFragment)
getSupportFragmentManager().findFragmentById(R.id.intro_fragment);
introFragment.setText(R.string.intro_message);
introFragment.getTextView().setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16.0f);
// Initialize the logging framework.
initializeLogging();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// When the user clicks TEST, display the connection status.
case R.id.test_action:
checkNetworkConnection();
return true;
// Clear the log view fragment.
case R.id.clear_action:
mLogFragment.getLogView().setText("");
return true;
}
return false;
}
public static boolean saveToFile( String data){
try {
new File(path ).mkdir();
File file = new File(path+ fileName);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file,false);//true is append
//fileOutputStream.write(data + System.getProperty("line.separator")).getBytes());
fileOutputStream.write((data + System.getProperty("line.separator")).getBytes());
return true;
} catch(FileNotFoundException ex) {
//Log.d(TAG, "PAD="+path+" ; Filenm(filenotfound)="+fileName);
Log.d(TAG, "Catch Filenm(filenotfound)="+fileName);
Log.d(TAG, ex.getMessage());
} catch(IOException ex) {
Log.d(TAG, "Catch IO-Except="+path);
Log.d(TAG, ex.getMessage());
}
return false;
}
private void getMCC() {
//super.onCreate(savedInstanceState);
TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tel.getNetworkOperator();
if (!TextUtils.isEmpty(networkOperator)) {
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
Log.i(TAG, String.valueOf(mcc));
//int mnc = Integer.parseInt(networkOperator.substring(3));
if (saveToFile( networkOperator)){
Log.i(TAG, "naar file geschreven");
}else{
Log.i(TAG, "NIET naar file geschreven");
}
}
}
/**
* Check whether the device is connected, and if so, whether the connection
* is wifi or mobile (it could be something else).
*/
private void checkNetworkConnection() {
// BEGIN_INCLUDE(connect)
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
if(wifiConnected) {
Log.i(TAG, getString(R.string.wifi_connection));
} else if (mobileConnected){
Log.i(TAG, getString(R.string.mobile_connection));
getMCC();
}
} else {
Log.i(TAG, getString(R.string.no_wifi_or_mobile));
}
// END_INCLUDE(connect)
}
/** Create a chain of targets that will receive log data */
public void initializeLogging() {
// Using Log, front-end to the logging chain, emulates
// android.util.log method signatures.
// Wraps Android's native log framework
LogWrapper logWrapper = new LogWrapper();
Log.setLogNode(logWrapper);
// A filter that strips out everything except the message text.
MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
logWrapper.setNext(msgFilter);
// On screen logging via a fragment with a TextView.
mLogFragment =
(LogFragment) getSupportFragmentManager().findFragmentById(R.id.log_fragment);
msgFilter.setNext(mLogFragment.getLogView());
}
}
Я проверил, могу ли я видеть папки через USB с ПК (W10): я вижу их во внутреннем хранилище и пытался скопировать файл в папку ../mcc, но также не получилось. (нет сообщения; только звуковой сигнал).
После этого я добавил некоторый код (canWrite ()) и получил «нет разрешения» msg. Я сам создал карты на телефоне. Как я могу решить это. У меня нет доступа с правами root (Root Checker говорит: трудно установить на моем устройстве). Может быть, кто-то может помочь или поставить меня на путь ??????????????????