My application requires root access. For example this code:
Process p;
try {
p = Runtime.getRuntime().exec("su");
BufferedReader es = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
if((line = es.readLine()) != null)
{
if(line.contentEquals("Permission denied"))
Log.e("TrisTag", "ROOT isn't granted");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So I know when my root access is denied (Read from the error stream). But what's about granted ? How to know ?
Answer from kevin.
public class Root {
private static String LOG_TAG = Root.class.getName();
public boolean isDeviceRooted() {
if (checkRootMethod1()){return true;}
if (checkRootMethod2()){return true;}
if (checkRootMethod3()){return true;}
return false;
}
public boolean checkRootMethod1(){
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}
public boolean checkRootMethod2(){
try {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
} catch (Exception e) { }
return false;
}
public boolean checkRootMethod3() {
if (new ExecShell().executeCommand(SHELL_CMD.check_su_binary) != null){
return true;
}else{
return false;
}
}
}
/**
* #author Kevin Kowalewski
*
*/
public class ExecShell {
private static String LOG_TAG = ExecShell.class.getName();
public static enum SHELL_CMD {
check_su_binary(new String[] {"/system/xbin/which","su"}),
;
String[] command;
SHELL_CMD(String[] command){
this.command = command;
}
}
public ArrayList<String> executeCommand(SHELL_CMD shellCmd){
String line = null;
ArrayList<String> fullResponse = new ArrayList<String>();
Process localProcess = null;
try {
localProcess = Runtime.getRuntime().exec(shellCmd.command);
} catch (Exception e) {
return null;
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(localProcess.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));
try {
while ((line = in.readLine()) != null) {
Log.d(LOG_TAG, "--> Line received: " + line);
fullResponse.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d(LOG_TAG, "--> Full response was: " + fullResponse);
return fullResponse;
}
Related
My app crashes only on a smartphone with android 10 ... not on a smartphone with android 9 Why?
This is my error:
Thread[7,tid=8537,WaitingInMainSignalCatcherLoop,Thread*=0x70f8fa2c00,peer=0x131c0378,"Signal Catcher"]: reacting to signal 3
Wrote stack traces to tombstoned
onCreate method (NetActivity.java):
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NetClient task = new NetClient();
payload = task.execute(ip, String.valueOf(Global.config_device), Global.uid, network.getSSID(), password, friendlyName).get();
}
}
});
My AsyncTask (NetClient.java):
public class NetClient extends AsyncTask<String, Void, String> {
Socket socket = null;
PrintWriter out = null;
BufferedReader buffer = null;
String ip;
int port = 8899;
String response = "";
int errors = 0;
private String[] conn_errors = {"", String.valueOf(R.string.error_provision), "Error: socket close...", "Error: receiving message...", "Unknown error...", "Error disconnecting socket..."};
protected Boolean connect() {
boolean res = false;
try {
if (socket == null) {
socket = new Socket(ip, port);
if (socket.isConnected()) {
res = true;
}
out = new PrintWriter(socket.getOutputStream());
buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
} catch (IOException e) {
Log.e("ERROR connect", e.getMessage());
errors = 1;
}
return res;
}
protected void disConnect() {
if (socket != null) {
if (socket.isConnected()) {
try {
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
errors = 5;
}
}
}
}
protected void sendData(String message) {
if (message != null) {
out.write(message);
out.flush();
}
}
protected String receiveData() {
try {
String message = "";
message = buffer.readLine();
message += buffer.readLine();
message += buffer.readLine();
message += buffer.readLine();
message += buffer.readLine();
return message;
} catch (IOException e) {
errors = 3;
return "Error receiving response: " + e.getMessage();
}
}
#Override
protected String doInBackground(String... params) {
boolean conn;
ip = params[0];
String message = "Teste sample" ;
try {
conn = connect();
Log.w("NetClient", "" + conn);
if (conn) {
sendData(message);
} else {
errors = 2;
}
if (conn) {
response = receiveData();
} else {
errors = 2;
}
} catch (Exception e) {
Log.w("NetClient", "Exception");
e.printStackTrace();
errors = 4;
} finally {
disConnect();
Log.i("NetClient", "Finished");
return response;
}
return String.valueOf(errors);
}
protected void onProgressUpdate(Integer... progress) {
Log.w("onProgressUpdate", "Progress: " + progress[0]);
}
protected void onPostExecute(String result) {
if (errors == 0) {
Log.i("onPostExecute", "Payload [" + result.length() + "] : " + result);
}
if (errors > 0) {
Log.i("ERROR", conn_errors[errors]);
}
}
}
I'm trying to use AsyncTaskLoader to retrieve data then parse the resulting json file, however, I can't figure out why I keep getting a
return null;
instead of returning
return gameList;
DailyScheduleFragment.java
Method calling the Loader:
public void loadGameScheduleList() {
getLoaderManager().initLoader(LOADER_ID_DAILY_SCHEDULE, null, new LoaderCallbacks<ArrayList<Game>>() {
public Loader<ArrayList<Game>> onCreateLoader(int id, Bundle args) {
return new DailyScheduleLoader(DailyScheduleFragment.this.getContext());
}
public void onLoadFinished(Loader<ArrayList<Game>> loader, ArrayList<Game> data) {
if (data == null) {
Exception exception = ((DailyScheduleLoader) loader).getException();
if (exception == null) {
return;
}
if (exception instanceof NoNetworkException) {
DailyScheduleFragment.this._btnMessage.setText(R.string.general_msg_no_network_connection_turn_on);
DailyScheduleFragment.this._btnMessage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intents.networkSettings(DailyScheduleFragment.this.getContext());
}
});
DailyScheduleFragment.this._progressBar.setVisibility(View.GONE);
DailyScheduleFragment.this._btnMessage.setVisibility(View.GONE);
return;
}
DailyScheduleFragment.this._btnMessage.setText(R.string.general_msg_something_went_wrong);
DailyScheduleFragment.this._btnMessage.setOnClickListener(null);
DailyScheduleFragment.this._progressBar.setVisibility(View.GONE);
DailyScheduleFragment.this._btnMessage.setVisibility(View.GONE);
return;
}
DailyScheduleFragment.this._games.clear();
Iterator it = data.iterator();
while (it.hasNext()) {
DailyScheduleFragment.this._games.add((Game) it.next());
}
DailyScheduleFragment.this._adapter.notifyDataSetChanged();
DailyScheduleFragment.this.displayListState();
}
public void onLoaderReset(Loader<ArrayList<Game>> loader) {
}
}).forceLoad();
}
DailyScheduleLoader.java
public class DailyScheduleLoader extends AsyncTaskLoader<ArrayList<Game>> {
private Context _context;
private Exception _exception;
public DailyScheduleLoader(Context context) {
super(context);
this._context = context;
}
public ArrayList<Game> loadInBackground() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this._context);
try {
ArrayList<Game> gameList = Parse.gameList(Networking.sendHttpRequest("http://api.sportradar.us/nhl/trial/v5/en/games/2018/01/01/schedule.json?api_key=xxx", this._context));
return gameList;
} catch (Exception e) {
this._exception = e;
return null;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
public Exception getException() {
return this._exception;
}
Network class:
public static final class Networking {
public static String sendHttpRequest(String urlString, Context context) throws Throwable {
NoNetworkException e;
Exception ex;
Throwable th;
if (urlString == null || urlString.trim().equals(BuildConfig.FLAVOR)) {
throw new NullPointerException("urlString");
}
HttpURLConnection httpCon = null;
InputStream input_stream = null;
InputStreamReader input_stream_reader = null;
BufferedReader input = null;
StringBuilder response = new StringBuilder();
try {
if (isNetworkAvailable(context)) {
httpCon = (HttpURLConnection) new URL(urlString).openConnection();
if (httpCon.getResponseCode() != 200) {
Log.e("TAG", "Cannot Connect to : " + urlString);
if (input == null) {
return null;
}
try {
input_stream_reader.close();
input_stream.close();
input.close();
} catch (IOException e2) {
e2.printStackTrace();
}
if (httpCon == null) {
return null;
}
httpCon.disconnect();
return null;
}
input_stream = httpCon.getInputStream();
InputStreamReader input_stream_reader2 = new InputStreamReader(input_stream);
try {
BufferedReader input2 = new BufferedReader(input_stream_reader2);
while (true) {
try {
String line = input2.readLine();
if (line == null) {
break;
}
response.append(line).append("\n");
} catch (Exception e4) {
ex = e4;
input = input2;
input_stream_reader = input_stream_reader2;
} catch (Throwable th2) {
th = th2;
input = input2;
input_stream_reader = input_stream_reader2;
}
}
if (input2 != null) {
try {
input_stream_reader2.close();
input_stream.close();
input2.close();
} catch (IOException e22) {
e22.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect();
input = input2;
input_stream_reader = input_stream_reader2;
return response.toString();
}
}
input_stream_reader = input_stream_reader2;
} catch (Exception e6) {
ex = e6;
input_stream_reader = input_stream_reader2;
ex.printStackTrace();
if (input != null) {
try {
input_stream_reader.close();
input_stream.close();
input.close();
} catch (IOException e222) {
e222.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
} catch (Throwable th4) {
th = th4;
input_stream_reader = input_stream_reader2;
if (input != null) {
try {
input_stream_reader.close();
input_stream.close();
input.close();
} catch (IOException e2222) {
e2222.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect();
}
}
throw th;
}
return response.toString();
}
throw new NoNetworkException();
} catch (NoNetworkException e7) {
e = e7;
throw e;
} catch (Exception e8) {
ex = e8;
ex.printStackTrace();
if (input != null) {
input_stream_reader.close();
input_stream.close();
input.close();
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
}
}
public static boolean isNetworkAvailable(#NonNull Context context) {
#SuppressLint("WrongConstant") NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
Parse class:
public static class Parse {
public static ArrayList<Game> gameList(String json) throws JSONException {
ArrayList<Game> games = new ArrayList();
JSONArray results = new JSONObject(json).getJSONArray("games");
// looping through All Games
for (int i = 0; i < results.length(); i++) {
JSONObject gameJSON = results.getJSONObject(i);
Game game = new Game();
game.setId(gameJSON.getString(Responses.Games.VALUE_ID));
game.setStatus(gameJSON.getString(Responses.Games.VALUE_STATUS));
games.add(game);
}
return games;
}
}
I found the code on a website and trying to modify it to suit my needs. For the most part, it works well, except I can't figure out where I'm going wrong with this.
If it helps, here's the json file that's returned in the request (sorry about the formatting):
{"date":"2018-01-01","league":{"id":"fd560107-a85b-4388-ab0d-655ad022aff7","name":"NHL","alias":"NHL"},"games":[{"id":"6d20bdbd-b5e0-46ab-8b98-45ea01ab0e2b","status":"scheduled","coverage":"full","scheduled":"2018-01-01T18:00:00+00:00","reference":"20601","venue":{"id":"faebd24e-ccfb-4e7c-aa58-1dee9e82bb0f","name":"Citi Field","capacity":45000,"address":"123 Roosevelt Ave","city":"Queens","state":"NY","zip":"11368","country":"USA","time_zone":"US/Eastern"},"broadcast":{"network":"NBC"},"home":{"id":"4416d559-0f24-11e2-8525-18a905767e44","name":"Buffalo Sabres","alias":"BUF"},"away":{"id":"441781b9-0f24-11e2-8525-18a905767e44","name":"New York Rangers","alias":"NYR"}}]}
Go here if you want it formatted.
I've added break points and stepped through the code to check the variables. All seems right, up until the
return gameList;
I'm new to android so please help me out. I am trying to save my ToDoList in a file so that the next time I open it, all the items are reloaded
This is the code I have so far,
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("storage.json"));
Entry e = gson.fromJson(br, Entry.class);
Log.d("reading", e.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}}
#Override
protected void onStop() {
super.onStop();
json = gson.toJson(mEntries);
Log.d("jsondata", json);
try {
file1 = new FileWriter("storage.json");
file1.write(json);
file1.flush();
file1.close();
} catch (IOException e) {
e.printStackTrace();
}
Entry.java
public class Entry {
String S;
boolean b;
public Entry(String S, boolean b) {
this.S = S;
this.b = b;
}
public String getS() {
return S;
}
public void setS(String S) {
this.S = S;
}
public void setB(boolean b) {
this.b = b;
}
public boolean isB() {
return b;
}
}
How do I proceed from here? In onCreate() I would like to check if the file exists and if yes, import data from file and display on screen.
Every android app has its own internal storage only that app can access, you can read from there or write to it.
In you case, you first want to check if you such file exist before creating one.
private String read(Context context, String fileName) {
try {
FileInputStream fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (FileNotFoundException fileNotFound) {
return null;
} catch (IOException ioException) {
return null;
}
}
private boolean create(Context context, String fileName, String jsonString){
String FILENAME = "storage.json";
try {
FileOutputStream fos = context.openFileOutput(fileName,Context.MODE_PRIVATE);
if (jsonString != null) {
fos.write(jsonString.getBytes());
}
fos.close();
return true;
} catch (FileNotFoundException fileNotFound) {
return false;
} catch (IOException ioException) {
return false;
}
}
public boolean isFilePresent(Context context, String fileName) {
String path = context.getFilesDir().getAbsolutePath() + "/" + fileName;
File file = new File(path);
return file.exists();
}
onCreate of the Activity, you can use do the following
boolean isFilePresent = isFilePresent(getActivity(), "storage.json");
if(isFilePresent) {
String jsonString = read(getActivity(), "storage.json");
//do the json parsing here and do the rest of functionality of app
} else {
boolean isFileCreated = create(getActivity, "storage.json", "{}");
if(isFileCreated) {
//proceed with storing the first todo or show ui
} else {
//show error or try again.
}
}
reference https://developer.android.com/guide/topics/data/data-storage.html#filesInternal
Code :
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://192.168.1.8/android-im/index.php"; //TODO change to your WebAPI Address
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = "failed";
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false)
{
//appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
}
I have succesfully saved int values to sd but cant read. It always gives numberformat information. I made all logics, but cant find why it gives error.
Here is my code ;
this my constant
private final static String EXTERNAL_FILES_DIR = "ARDROID";
private final static String FILE_NAME = "turkcell.txt";
private boolean isThereAnySavedFile = false;
when this method called, it tries to open file, if file does not exist, create the file
public void anySavedDataInSD() {
String textFromSD = String.valueOf(read());
if (isThereAnySavedFile) {
int numberOfSendedSMS = Integer.parseInt(textFromSD.toString());
numberOfSendedSMS++;
writeToSD(String.valueOf(numberOfSendedSMS));
} else {
int first=60;
String g = String.valueOf(first);
writeToSD(g);
}
}
this method for writing
private void write(File file, String msg) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(msg.getBytes());
Logger.info("oldu bu kez");
} catch (IOException e) {
Logger.info("oldu bu kez2" + e);
} finally {
Logger.info("oldu bu kez3");
try {
if (outputStream != null)
outputStream.close();
} catch (IOException exception) {
}
}
}
this methof for reading
public StringBuilder read() {
StringBuilder textBuilder = new StringBuilder();
BufferedReader reader = null;
try {
File externalFilesDir = getExternalFilesDir(EXTERNAL_FILES_DIR);
File file = new File(externalFilesDir, FILE_NAME);
Logger.info("oldu2");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
isThereAnySavedFile = true;
} catch (FileNotFoundException e) {
Logger.info("oldu3");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return textBuilder;
}