I am trying to write an app for android but am not able to connect to the website. the website is
here. I am able to connect to the website in Firefox and chrome. I wrote a simple program in java SE and it is able to connect to the website. here is the code.
import java.net.*;
import java.io.*;
public class urltest {
public static void main( String[] args ) throws Exception {
URL url = new URL ( "https://alerts.weather.gov/cap/mn.php?x=0" );
BufferedReader reader = new BufferedReader( new InputStreamReader( url.openStream() ) );
String line;
while ( ( line = reader.readLine() ) != null )
System.out.println( line );
reader.close();
}
}
This program does work and does connect to the website. the android app however does not. here is the manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ledorianindustries.rss2">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Rss2">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and here is the MainActivity.
package com.ledorianindustries.rss2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new rss().execute();
}
public class rss extends AsyncTask<Integer, Void, Exception> {
#Override
protected Exception doInBackground(Integer... integers) {
try {
URL url = new URL("https://alerts.weather.gov/cap/mn.php?x=0");
BufferedReader reader = new BufferedReader( new InputStreamReader( url.openStream() ) );
String line;
while ((line = reader.readLine()) != null) {
Log.e("info", line);
}
reader.close();
} catch (IOException e) {
Log.e("info", e.toString());
}
return null;
}
}
}
for reasons that I cannot identify I am presented with the error:
2021-02-16 12:19:59.363 13978-14006/com.ledorianindustries.rss2 E/info: java.io.FileNotFoundException: https://alerts.weather.gov/cap/mn.php?x=0
I have checked to see if google is using their own implementation of the networking stack and as far as I can tell they have not. So then why does it work in java SE but not in android? I would appreciate some help on this matter.
***edit 1
the code for URLConnection will follow.
URL url = new URL("https://alerts.weather.gov/cap/mn.php?x=0");
//BufferedReader reader = new BufferedReader( new InputStreamReader( url.openStream() ) );
URLConnection uc = url.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader( uc.getInputStream() ) );
String line;
while ((line = reader.readLine()) != null) {
Log.e("info", line);
}
reader.close();
the error code is:
2021-02-16 14:12:28.132 14638-14698/com.ledorianindustries.rss2 E/info: java.io.FileNotFoundException: https://alerts.weather.gov/cap/mn.php?x=0
***edit2
I have tried a few other urls:
URL url1 = new URL("https://alerts.weather.gov/cap/mn.php?x=0");
URL url2 = new URL("https://www.rediff.com/rss/moviesreviewsrss.xml");
URL url3 = new URL("https://www.cinemablend.com/rss_review.php");
url1 is the original url. url2 and url3 work. I am starting to think the "?x=0" may be the problem? I don't know much about php but is that maybe the issue? can php be rewritten? I tried to remove that part in my browser, it was very unhappy.
Related
I am building a mobile app for my project on which I have to retrieve data sent to Thingspeak on it.
When I tap on an image button, it should open a new activity which will show its last value retrieved from Thingspeak.
The issue I am getting is that the app stops working when I click on an image button which is supposed to bring me to another activity. It does open a new activity showing that navigation to another activity is working but then it shows "Smart Agriculture has unfortunately stopped working". I think the problem is in the xml files of the activities or the TextView I have used in some TempHumidity.java file but I don't really know how to resolve them being an absolute beginner in Android Studio. I have 5 files namely activity_main.xml, MainActivity.java, TempHumidity.java, AndroidManifest.xml, imgbtnmenu.xml
TempHumidity.java class(it contains the HttpURLConnection codes)
public class TempHumidity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imgbtnmenu);
new GetMethodDemo().execute("https://thingspeak.com/channels/357670/field/1/last");
}
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
private TextView aTextView;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
aTextView.setText(s);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.teerna.smartagriculture">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".TempHumidity"> // you need to add these 3 lines inside application tag.
</activity>
</application>
</manifest>
imgbtnmenu.xml for the new activity menu(the menu that opens when Humidity and Temperature image button is tapped)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
The messages on Logcat are as follows:
Most of the logcat is only warning, you can see the W/ character. The The app crashes because you're receiving a java.lang.VerifyError which is Could not find class 'android.graphics.drawable.RippleDrawable. This error will only happen on pre-lolipop device (Android 5.0)
Try add these line to build.gradle:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
If it still not working, change app:srcCompat inside every ImageView to android:src
I am very new into the android development.
In this project, I am trying to create a JSON objects and then want to write that JSON object into a file in SD card but I am getting the following exception:
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/avinash1.json: open failed: EACCES (Permission denied)
Though I have even added the user-permission in the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.raviteja.youexample">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
package com.example.raviteja.youexample;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject obj = new JSONObject();
try {
obj.put("age", new Integer(100));
obj.put("name", "Ravi");
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray list1 = new JSONArray();
JSONObject pnObj = new JSONObject();
try {
pnObj.put("num", "99009900");
pnObj.put("type", "mhgchmc");
list1.put(pnObj);
obj.put("phoneNumber", list1);
} catch (JSONException e) {
e.printStackTrace();
}
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "avinash1.json");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(obj.toString());
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should maybe try to get the public directory with the command: getExternalStoragePublicDirectory(): android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
Although if you want to keep that info to yourself and not let any other apps touch it you should save it in your apps InteralStorage. Quick tutorial here: http://www.tutorialspoint.com/android/android_internal_storage.htm
Updating my Answer
use this method , it should work :
private void saveJson() {
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if(!root.exists())
{
root.mkdirs();
}
File file = new File(root, "avinash1.json");
try {
if (file.exists()) {file.delete ();}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(json.toString());
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
but be careful , whenever you call this , your file will be overwritten with new value , for escaping that , you should make unique name for your file , like including current date and time to your file name ...
I'm having a problem querying a database in Ragic off of Android. I've SUCCESSFULLY created a program in Eclipse that queries the online database and downloads all the JSONS, turns them into Objects, and then puts them into an ArrayList. Unfortunately, I'm running into a problem trying to download the same data using the exactly same code in Android. I've already added the permission for the internet (as shown in the AndroidManifest.xml). The code compiles and all, but throws the NullPointerException("RUNTIME EXCEPTION/ALLDOWNLOADEXCEPTIONS") at the end of the MapsActivity.java file. That is the problem, but I don't know what it causing it. Please help with that.
Here is the MapsActivity.java:
package com.main.parcaretestversion;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.*;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
ArrayList<ParkingSpot> list = init();
System.exit(0);
for (ParkingSpot spot: list) {
PolygonOptions rectOptions = new PolygonOptions()
.addAll(spot.getArrayListLatLngDefault());
if (spot.getStatus()) {
rectOptions.fillColor(Color.GREEN);
} else {
rectOptions.fillColor(Color.RED);
}
Polygon polygon = mMap.addPolygon(rectOptions);
}
}
public ArrayList<ParkingSpot> format(String input) {
ArrayList<ParkingSpot> list = new ArrayList<ParkingSpot>();
JsonElement root = new JsonParser().parse(input);
for (int i = 0; i <= 9; i++) {
String uid = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("ID").getAsString();
String coordinate1 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 1").getAsString();
String coordinate2 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 2").getAsString();
String coordinate3 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 3").getAsString();
String coordinate4 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 4").getAsString();
String statusTemp = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Status").getAsString();
boolean status;
if (statusTemp.equals("true")) {
status = true;
} else {
status = false;
}
list.add(new ParkingSpot(uid, status, new LatLong(coordinate1), new LatLong(coordinate2), new LatLong(coordinate3), new LatLong(coordinate4)));
}
return list;
}
public ArrayList<ParkingSpot> init() {
String apiKey = "some api key";
try {
//
URL url = new URL("https://api.ragic.com/some username/some sheet/1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + apiKey);
InputStream content = (InputStream) connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String uglyJson = "";
for (String line; (line = reader.readLine()) != null; ) {
uglyJson += line;
}
ArrayList<ParkingSpot> list = format(uglyJson);
throw new NullPointerException(uglyJson);
//return list;
} catch (MalformedURLException e) {
throw new NullPointerException("MALFORUMED URL EXCEPTION");
} catch (RuntimeException allDownloadExceptions) {
throw new NullPointerException("RUNTIME EXCEPTION/ALLDOWNLOADEXCEPTIONS");
} catch (ProtocolException e) {
throw new NullPointerException("PROTOCOL EXCEPTION");
} catch (IOException e) {
throw new NullPointerException("IO EXCEPTION");
}
}
}
Here is the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Use asyncTasks in your mainActivity.
For example.
private class LongOperation extends AsyncTask<String, Void, ArrayList> {
#Override
protected ArrayList doInBackground(String... params) {
URL url = new URL("https://api.ragic.com/some username/some sheet/1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + apiKey);
InputStream content = (InputStream) connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String uglyJson = "";
for (String line; (line = reader.readLine()) != null; ) {
uglyJson += line;
}
ArrayList<ParkingSpot> list = format(uglyJson);
throw new NullPointerException(uglyJson);
return list;
}
#Override
protected void onPostExecute(ArrayList result) {
//Handle result here.
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
now make call for this call
new LongOperation().execute();
Hope it will help
I'm trying to get textview to display a number, but it will not.
My activity code:
package com.example.gotteron;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Classement extends Activity{
TextView textview;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.classement);
GetCode getCode = new GetCode();
textview = (TextView)findViewById(R.id.textView1);
try {
textview.setText(getCode.test());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Class to get HTMl:
//Package
package com.example.gotteron;
//Import
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class GetCode{
public String test() throws Exception{
//Recupérer le code HTML de la page
URL oracle = new URL("http://www.nationalleague.ch/NL/fr/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
String s1 = "";
while ((inputLine = in.readLine()) != null)
s1 = s1 + inputLine;
in.close();
int Berne = s1.indexOf(">SC Bern</td>");
String s3 = String.valueOf(Berne);
return s3;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/background">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/firstPosition" />
</LinearLayout>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gotteron"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.gotteron.Principal"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="Classement" android:label="#string/app_name"></activity>
<activity android:name="Calendrier" android:label="#string/app_name"></activity>
<activity android:name="Live" android:label="#string/app_name"></activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EDIT:
Thanks for the code but there's still a problem. When I run the Application the textview displays his default message. During this time, the logcat displays a lot of messages:
http://pastebin.com/244grjYt
and at the end the app crashes
Essentially, this is what the other answers are about. Since you haven't check anything as answer, maybe this will help.
public class MyClass extends Activity {
TextView textview;
public void onCreate(Bundle bundle) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classement);
textview = (TextView)findViewById(R.id.textview);
new NetworkOperation().execute();
}
private class NetworkOperation extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
try {
URL oracle = new URL("http://www.nationalleague.ch/NL/fr/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
String s1 = "";
while ((inputLine = in.readLine()) != null)
s1 = s1 + inputLine;
in.close();
int Berne = s1.indexOf(">SC Bern</td>");
String s3 = String.valueOf(Berne);
return s3;
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
textview.setText(result);
}
}
}
You cannot make a network connection (HTTP connection) i the ui thread, try to move the call to getCode.test() into another thread or better into an AsyncTask..
You are facing NetworkOnMainThread Exception which is quite common on Emulators that are running on API level 11 and more when you are writing Network Related code in UI Thread. You change your code into doInBackground() of an AsyncTask and run it.
In your case as you are throwing Exception in test() it will not crash your app because Exceptions are caught by Exception.
Example Code:
class FetchResultTask extends AsyncTask<Void,Void,String>
{
protected String doInBackground()
{
//your network related code.
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
//set the result to TextView here.
}
}
I run my service (write logcat to file) on any emulators and real devices from 2.3.3 to 4.1. All OK.
On this devices generated right log:
--------- beginning of /dev/log/main
--------- beginning of /dev/log/system
I/ActivityManager( 3386): START {act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.androWAcivtMaae( 36:IvldakgNme W/ActivityManager( 3386): Duplcaefns eus orcitRod45c6 o.vnotsolet.tiiyilg
I/ActivityManager( 3386): Displayed com.android.calculator2/.Calculator: +9s374ms<br>
.....
.....
But when I run service on 4.1.2 (samsung (google) Nexus S (soju, crespo), SDK 16, flash 485486, build JZO54K) or 2.3.6, my service stoped after one line in logs.
On this devices generated wrong log:
--------- beginning of /dev/log/main
Only print one line and nothing.... Service stay in memory, but not work right...
This is my code
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.logcatt"
android:versionCode="1"
android:versionName="0.5">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_LOGS" />
<application android:theme="#android:style/Theme.NoTitleBar">
<activity android:name=".ActivityMain" android:label="logcatt">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BroadcastBoot" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".ServiceMain" android:enabled="true" />
</application>
</manifest>
Activity
package com.my.logcatt;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class ActivityMain extends Activity
{
#Override
public void onCreate( Bundle savedInstanceState)
{
super.onCreate( savedInstanceState);
setContentView( R.layout.main);
try { startService( new Intent( getApplicationContext(), ServiceMain.class)); } catch( Exception e) {}
}
}
Service
package com.my.logcatt;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
public class ServiceMain extends Service
{
public static Process procLogcatClean = null;
public static Process procLogcatAM = null;
public static BufferedReader readerLogcat = null;
public static void fLog( String sLogMessage)
{
FileWriter fileLog = null;
BufferedWriter bufferLog = null;
try
{
fileLog = new FileWriter( Environment.getExternalStorageDirectory().getAbsolutePath() + "/123.log", true);
if( fileLog != null)
{
bufferLog = new BufferedWriter( fileLog);
bufferLog.write( sLogMessage + "\r\n");
bufferLog.flush();
}
}
catch( Exception e) {}
finally
{
if( bufferLog != null) { try { bufferLog.close(); } catch( Exception e) {} }
if( fileLog != null) { try { fileLog.close(); } catch( Exception e) {} }
}
}
#Override
public void onCreate()
{
super.onCreate();
startService();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
}
public void startService()
{
final Thread thread = new Thread()
{
public void run()
{
try
{
Runtime localRuntimeClear = Runtime.getRuntime();
String[] sLogcatClear = new String[ 2];
sLogcatClear[ 0] = "logcat";
sLogcatClear[ 1] = "-c";
procLogcatClean = localRuntimeClear.exec( sLogcatClear);
procLogcatClean.waitFor();
Runtime localRuntimeAM = Runtime.getRuntime();
String[] sLogcatAM = new String[ 2];
sLogcatAM[ 0] = "logcat";
sLogcatAM[ 1] = "ActivityManager:I *:S";
procLogcatAM = localRuntimeAM.exec( sLogcatAM);
readerLogcat = new BufferedReader( new InputStreamReader( procLogcatAM.getInputStream()), 1024);
String str = "";
while( true)
{
str = "";
try
{
if( readerLogcat != null)
{
str = readerLogcat.readLine();
fLog( str);
}
}
catch( Exception e) {}
if( str.compareTo( "") == 0) continue;
}
}
catch( Exception e) {}
finally {}
}
};
thread.setPriority( Thread.MAX_PRIORITY);
thread.start();
}
}
What is wrong?
On 4.1.2., Only rooted and system applications can access logcat. If rooted, you could use "su logcat".
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/6U4A5irWang
I suspect that you will find that this line throws an exception which you do not handle (bad practice btw - if you had a proper catch, you would have found this I think).
procLogcatAM = localRuntimeAM.exec( sLogcatAM);
Otherwise, check for the Android version and do something different or check for the permission refusal. Or, restrict your app to < 4.1.