Why read logcat in loop read only one time - java

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.

Related

React Native: Override Error on Package without Duplicate

I'm trying to use the react-native-camera package but when I added this to my project, I wasn't able to see the camera, instead it was loading and a warning. Then I search on the internet for this warning and saw that I had to link this library manually and so I did. But when I try to build I got this:
Here is my MainApplication.java
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.reactnative.camera.RNCameraPackage;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
public boolean canOverrideExistingModule() {
return true;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new RNCameraPackage());
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this); // Remove this line if you don't want Flipper enabled
}
/**
* Loads Flipper in React Native templates.
*
* #param context
*/
private static void initializeFlipper(Context context) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
Android Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>
Getting this when trying to access the camera:
Possible Unhandled Promise Rejection (id: 0):
TypeError: CameraManager.checkVideoAuthorizationStatus is not a function
TypeError: CameraManager.checkVideoAuthorizationStatus is not a function
at requestPermissions$ (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:129653:61)
at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25682:19)
at Generator.invoke [as _invoke] (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25857:24)
at Generator.prototype.<computed> [as next] (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25725:23)
at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25682:19)
at invoke (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25758:22)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25788:13
at tryCallTwo (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27046:7)
at doResolve (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27210:15)
at new Promise (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27069:5)
Well, the message sais it pretty clear in my opinion. Rect-Native 0.60+ uses autlinking to link native packages, so you are not require to use react-native link react-native-camera anymore.
Which means you don't need to import and have packages.add(new RNCameraPackage()); in your MainApplication.java
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new RNCameraPackage()); // Remove this line and the import statement
return packages;
}
You also need to remove all the other things that were added when running the react-native link command. Reinstall and your app should open now.
LE:
As backup, you can turn off autolinking for specific packages like below. Edit or create react-native.config.js add have the following.
module.exports = {
dependencies: {
'react-native-camera': {
platforms: {
android: null, // disable Android platform, other platforms will still autolink if provided
},
},
},
};

Why is my ACTION_SEND working on API 25+ perfectly, but messes up on previous APIs?

So I have a Share button that will share an image and a body of text.
On Nougat (API 25) and Oreo (API 26), it works absolutely perfectly. But when it comes to a couple older version it doesn't work as expected.
Marshmallow (API 23): Inserts the image just fine but no body of text.
Lollipop (API 22): Crashes when you push the Share button with popup error "Unfortunately, Messaging has stopped." LOGCAT isn't showing me any errors when this happens.
Here is my share button code:
if (id == R.id.action_shareWine) {
Intent intentShare = new Intent(Intent.ACTION_SEND);
intentShare.putExtra(intentShare.EXTRA_STREAM, imageURI);
intentShare.setType("image/*");
intentShare.putExtra(Intent.EXTRA_TEXT, "body of text goes here");
if (intentShare.resolveActivity(getPackageManager()) != null) {
startActivity(intentShare);
}
return true;
}
Here is a picture to give a visual idea of whats going on:
Anyone have any ideas what could be going on here?
UPDATE 1
Here is the crash log for the Lollipop emulator:
FATAL EXCEPTION: Mms-1
Process: com.android.mms, PID: 7570
java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Which I'm not sure why it is happening because the cursor is loading the image just fine in an ImageView in that same activity.
Call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) on the ACTION_SEND Intent, to allow third parties the ability to read the content identified by the Uri.
Also, since the image would appear to be a JPEG (based on the file extension), the MIME type is image/jpeg, not image/* or image/png.
For More Details
working in Oreo and Marshmallow Version Read this
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
Source Code
https://drive.google.com/open?id=1vfO43dMSt096CMp6nrOJNl3fJAf6MPwG
create xml folder inside providers_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.holostik.sharescreenshotexample">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.holostik.sharescreenshotexample.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
</application>
</manifest>
package com.holostik.sharescreenshotexample;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.holostik.sharescreenshotexample.share.ScreenshotType;
import com.holostik.sharescreenshotexample.share.ScreenshotUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int n;
String photoPath;
LinearLayout rootContent;
ImageView iv_share;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootContent = (LinearLayout) findViewById(R.id.rootContent);
iv_share = (ImageView) findViewById(R.id.iv_share);
iv_share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Log.e("MainActivity ", "P granted");
takeScreenshot(ScreenshotType.FULL);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 1);
}
} else {
Log.e("MainActivity", "Lower Than MarshMallow");
takeScreenshot(ScreenshotType.FULL);
}
}
});
}
/* Method which will take screenshot on Basis of Screenshot Type ENUM */
private void takeScreenshot(ScreenshotType screenshotType) {
Bitmap b = null;
switch (screenshotType) {
case FULL:
b = ScreenshotUtils.getScreenShot(rootContent);
break;
case CUSTOM:
//If Screenshot type is CUSTOM
break;
}
//If bitmap is not null
if (b != null) {
// showScreenShotImage(b);//show bitmap over imageview
Log.e("keshav", "bitmap is -- > " + b);
SaveImage(b);
shareScreenshot();
/* File saveFile = ScreenshotUtils.getMainDirectoryName(MainActivity.this);//get the path to save screenshot
File file = ScreenshotUtils.store(b, "screenshot" + screenshotType + ".jpg", saveFile);//save the screenshot to selected path
shareScreenshot(file);//finally share screenshot
Log.e("file Path", String.valueOf(file));
*/
} else
//If bitmap is null show toast message
Toast.makeText(MainActivity.this, R.string.screenshot_take_failed, Toast.LENGTH_SHORT).show();
}
private void SaveImage(Bitmap finalBitmap)
{
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/* TODO Show screenshot Bitmap */
// private void showScreenShotImage(Bitmap b) {
// imageView.setImageBitmap(b);
// }
private void shareScreenshot()
{
photoPath = Environment.getExternalStorageDirectory() + "/saved_images" + "/Image-" + n + ".jpg";
File F = new File(photoPath);
//Uri U = Uri.fromFile(F);
// Uri U = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".my.package.name.provider", F);
// TODO your package name as well add .fileprovider
Uri U = FileProvider.getUriForFile(MainActivity.this.getApplicationContext(), "com.holostik.sharescreenshotexample.fileprovider", F);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/png");
i.putExtra(Intent.EXTRA_STREAM, U);
startActivityForResult(Intent.createChooser(i, "Email:"), 1);
}
// TODO Share Screen SHOT End ..............
}

Having trouble exporting SQLite Database in Android

I have an application that I want to export the current SQLite database to the Internal storage Downloads folder of the device. I am getting the below error.
java.io.FileNotFoundException:
/storage/emulated/0/Download/Pipe_Tally: open failed: EACCES
(Permission denied)
I have what I think are the correct permissions included in the AndroidManifest.xml file for reading and writing to storage.
Here is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.bigdaddy.pipelinepipetally">
<uses-feature android:name="android.hardware.camera2"
android:required="true"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="HardcodedDebugMode">
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".TallyActivity2"
android:windowSoftInputMode="adjustResize">
</activity>
<activity
android:name=".JobAndDbActivity"
android:windowSoftInputMode="adjustResize">
</activity>
<activity
android:name=".ExistingTallyActivity"
android:windowSoftInputMode="adjustResize">
</activity>
<activity android:name=".ImageToFullscreen"
android:windowSoftInputMode="adjustResize">
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.bigdaddy.pipelinepipetally.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths">
</meta-data>
</provider>
</application>
</manifest>
Here is the method I am trying to use to create the file for the /Downloads/ folder within the internal device storage:
public void backUpDatabase() {
/* Open your local db as the input stream */
DBHelper anotherDbHelper = null;
try {
try {
anotherDbHelper = new DBHelper(ExistingTallyActivity.this);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String path = null;
if (anotherDbHelper != null) {
path = String.valueOf(getApplicationContext().getDatabasePath(anotherDbHelper.getDatabaseName()));
Log.i(TAG, "backUpDatabase: 1" +path);
}
File dbFile = null;
if (path != null) {
dbFile = new File(path);
Log.i(TAG, "backUpDatabase: 2" + String.valueOf(dbFile));
}
FileInputStream fis = null;
try {
if (dbFile != null) {
fis = new FileInputStream(dbFile);
Log.i(TAG, "backUpDatabase: 3" + String.valueOf(dbFile));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String outFileName = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+ "/Pipe_Tally/");
Log.i(TAG, "backUpDatabase: 4"+ outFileName);
// Open the empty db as the output stream
OutputStream outputStream = null;
//FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(outFileName);
Log.i(TAG, "backUpDatabase: 5"+ outFileName);
Log.i(TAG, "backUpDatabase: 6"+ String.valueOf(outputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Transfer bytes from the input-file to the output-file
byte[] buffer = new byte[1024];
int length;
try {
if (fis != null) {
while ((length = fis.read(buffer)) > 0) {
try {
if (outputStream != null) {
outputStream.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
//Close the streams
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Here is the method I am using to check for the correct permissions at Runtime:
private boolean checkSdCardPermissions() {
/* Checking here if we already have permissions*/
if (ActivityCompat.checkSelfPermission(ExistingTallyActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(ExistingTallyActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { /* Added this for Write External Storage permissions */
/* Checking to see if we are equal to or at a higher version than Marshmallow */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
/* System default popup box here to ask for permissions. */
ActivityCompat.requestPermissions(ExistingTallyActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSION_READ_EXTERNAL_STORAGE);
/* Added this today for trying to prompt for writing external storage*/
ActivityCompat.requestPermissions(ExistingTallyActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSION_WRITE_EXTERNAL_STORAGE);
}
return true;
} else {
return false;
}
}
This is the onOptionsItemSelected() method that has the switch in it to handle the menu and what is selected. The case:R.id.menu_save_and_export:
is where I am checking if checkSdCardPermissions() method is true, then calling the backUpDatabase() method.
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
/*
When Tally New Pipe is selected from the Menu, it sends the user to the TallyActivity
page, all encapsulated in a runnable and passed to thread below.
*/
case R.id.menu_new_pipe:
class ToTallyActivityManager implements Runnable {
#Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Intent intentToTallyActivity =
new Intent(ExistingTallyActivity.this, TallyActivity2.class);
startActivity(intentToTallyActivity); /* Heading to TallyActivity.*/
} /* run method ends here. */
} /* Runnable ends here. */
/* This thread takes care of the call to go to TallyActivity page from here.*/
mThreadToTallyActivity = new Thread(new ToTallyActivityManager());
mThreadToTallyActivity.start();
break;
/* When selected, sends the user to the MainActivity page. */
case R.id.menu_to_main:
Intent intentToMainActivity =
new Intent(ExistingTallyActivity.this, MainActivity.class);
startActivity(intentToMainActivity); // Heading to MainActivity
break;
/* When chosen allows the option to save and export the current DB.*/
case R.id.menu_save_and_export:
if (checkSdCardPermissions()) {
try {
backUpDatabase();
} catch (/*IOException*/ SQLException e) {
e.printStackTrace();
}
}
break;
/* When chosen from the menu, this kills the app completely. Has popup embedded.*/
default:
AlertHelperDialog.displayExitAlertDialog(ExistingTallyActivity.this);
} /* switch/case ends here */
return super.onOptionsItemSelected(menuItem);
} /* onOptionsItemSelected method ends here. */
I really appreciate any help or advice with fixing this issue. Thank you.
You have a android:maxSdkVersion="18" set on the WRITE_EXTERNAL_STORAGE permission. If you are running on a phone with SDK > 18 the app will not have permission to WRITE_EXTERNAL_STORAGE. So I suggest you remove the android:maxSdkVersion attribute. Read the documentation.
android:maxSdkVersion : The highest API level at which this permission should be granted to your app. Setting this attribute is useful if the permission your app requires is no longer needed beginning at a certain API level.
Change it as follows,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Can someone help me with Android RemoteControlClient?

I'm trying to get the RemoteControlClient set up so my app's music can be controlled by the widget that pops up on the lock screen (like SoundCloud, Google Play Music, and other music/video apps work). I'm not sure what's wrong with my code and why it isn't correctly hooking, but here's what I have so far...
A class called MusicService that tries to handle the updates to the RemoteControlClient
public class MusicService extends Service
{
public static final String ACTION_PLAY = "com.stfi.music.action.PLAY";
private RemoteController controller = null;
#Override
public void onCreate()
{
super.onCreate();
System.out.println("Creating the service.");
if(controller == null)
{
controller = new RemoteController();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
String action = intent.getAction();
System.out.println("Got an action of " + action);
/* Logic to get my Song cur */
controller.register(this);
controller.updateMetaData(cur);
return START_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
System.out.println("Destorying MusicService");
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
This uses a class I have called RemoteController which houses my RemoteControlClient.
public class RemoteController {
private RemoteControlClient remoteControlClient;
private Bitmap dummyAlbumArt;
public void register(Context context)
{
if (remoteControlClient == null)
{
System.out.println("Trying to register it.");
dummyAlbumArt = BitmapFactory.decodeResource(context.getResources(), R.drawable.dummy_album_art);
AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
ComponentName myEventReceiver = new ComponentName(context.getPackageName(), MediaButtonReceiver.class.getName());
audioManager.registerMediaButtonEventReceiver(myEventReceiver);
// build the PendingIntent for the remote control client
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setComponent(myEventReceiver);
// create and register the remote control client
PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(context, 0, mediaButtonIntent, 0);
remoteControlClient = new RemoteControlClient(mediaPendingIntent);
remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_NEXT
| RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY
| RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
);
audioManager.registerRemoteControlClient(remoteControlClient);
}
}
/**
* Update the state of the remote control.
*/
public void updateState(boolean isPlaying)
{
if(remoteControlClient != null)
{
if (isPlaying)
{
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
}
else
{
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
}
}
}
/**
* Updates the state of the remote control to "stopped".
*/
public void stop()
{
if (remoteControlClient != null)
{
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
}
}
public void updateMetaData(Song song)
{
if (remoteControlClient != null && song != null)
{
System.out.println("Updating metadata");
MetadataEditor editor = remoteControlClient.editMetadata(true);
editor.putBitmap(MetadataEditor.BITMAP_KEY_ARTWORK, dummyAlbumArt);
editor.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, (long)1000);
editor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, "Artist");
editor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, "Title");
editor.apply();
updateState(true);
}
}
/**
* Release the remote control.
*/
public void release() {
remoteControlClient = null;
}
}
Every time I want to update the widget, I call startService(new Intent(MusicService.ACTION_PLAY));. It looks like it correctly creates the service, and it always gets to the point where it says "Updating metadata", but for some reason when I lock my screen and unlock it, I don't see any widget on my lock screen.
Below is the important parts of my manifest as well, seeing as that could somehow cause the issue...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stfi"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:hardwareAccelerated="true"
android:allowBackup="true"
android:icon="#drawable/stfi"
android:label="#string/app_name"
android:largeHeap="true"
android:theme="#style/MyActionBarTheme" >
<meta-data
android:name="android.app.default_searchable"
android:value=".activities.SearchActivity" />
<activity
android:name=".StartingToFeelIt"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
...other activities listed
<service
android:name=".helpers.MyNotificationService"
android:enabled="true"
android:label="MyNotificationServiceLabel" >
</service>
<service
android:name=".music.MusicService"
android:exported="false" >
<intent-filter>
<action android:name="com.stfi.music.action.PLAY" />
</intent-filter>
<intent-filter>
<action android:name="com.example.android.musicplayer.action.URL" />
<data android:scheme="http" />
</intent-filter>
</service>
<receiver
android:name=".music.MediaButtonReceiver"
android:exported="false" >
</receiver>
</application>
Right now my MediaButtonReceiver doesn't really do much of anything. I'm just trying to get the hooks set up. If you want, this is my MediaButtonReceiver class...
public class MediaButtonReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
System.out.println("Receiving something.");
if (intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON))
{
final KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event != null && event.getAction() == KeyEvent.ACTION_UP)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)
{
System.out.println("You clicked pause.");
}
else if(event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY)
{
System.out.println("You clicked play.");
}
else if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_NEXT)
{
System.out.println("You clicked next.");
}
else if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PREVIOUS)
{
System.out.println("You clicked previous.");
}
}
}
}
}
if you can't see remoteControlClient on lock screen you must implement audio focus. You can look here

Get variable other class java Android

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.
}
}

Categories