need to access the system permission - java

I am trying to access the folder of my app from data/data but it need to change the permission to 0777. So, I had used some code that can change at run time but the permissions are not changing. It gives me error open failed: EACCES (Permission denied). I also put this permission in manifest file below Marshmallow i need to give like in root explorer where we change the folder rwxrwxrw
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here this is my code
String[] command = new String[]{"/system/bin/ls", "0777",
"/data/data/com.ayub.android.baba" };
process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
String output = "";
String line;
while ((line = reader.readLine()) != null) {
output.concat(line + "\n");
Log.w("myApp", "[[output]]:" + line);
process.waitFor();
}
reader.close();
process.waitFor();
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
Log.d(TAG,e.toString());
}

Here, I developed one class for to give granted permission on marshmallow device.
Getpermission.java
public class GetPermission extends Activity {
private static final int REQUEST_CODE = 2;
private static final int REQUEST_PERMISSIONS = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >=23)
{
getPermission();
}
else
{
startService();
}
}
private void getPermission()
{
if (ContextCompat.checkSelfPermission(GetPermission.this, Manifest.permission.READ_EXTERNAL_STORAGE)
+ ContextCompat.checkSelfPermission(GetPermission.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(GetPermission.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
},
REQUEST_PERMISSIONS);
}
else
{
startService();
}
}
private void startService()
{
//In this intent add your starting first activity
Intent in = new Intent(getApplicationContext(),HomeScreen.class);
startActivity(in)
finish();
}
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String[] permissions, #NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if ((grantResults.length > 0) && (grantResults[0]+grantResults[1]+grantResults[2])
== PackageManager.PERMISSION_GRANTED) {
getWindowOverLayPermission();
} else {
Toast.makeText(GetPermission.this, "All Permission is required to use xyz", Toast.LENGTH_LONG).show();
finish();
}
}
}
#TargetApi(Build.VERSION_CODES.M)
private void getWindowOverLayPermission()
{
if (!Settings.canDrawOverlays(GetPermission.this))
{
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_CODE);
}
else
{
startService();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE)
{
Toast.makeText(GetPermission.this, "Windows Overlay Permission is required",Toast.LENGTH_LONG).show();
getWindowOverLayPermission();
}
else
{
startService();
}
}
}
After that change your Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xyz.christmashdwallpaper" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/icon_256"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/MyMaterialTheme" >
<activity android:name=".Permission.GetPermission" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activity.HomeScreen"/>
</application>
Hope,It will help you...

Related

Cannot scan BLE devices around

I'm working on Android Studio chipmunk using java language. Trying to discover Bluetooth Low Energy devices. Relevant Permissions are granted to the app but it still is not discovering devices around it. mLeDevices array size being zero returning null.
I am using Pixel 3 device to run my code with Android 12.
private boolean scanning;
private Handler handler = new Handler();
private static final long SCAN_PERIOD = 10000;
private LeDeviceListAdapter leDeviceListAdapter=new LeDeviceListAdapter();
private ScanCallback leScanCallback =
new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
LayoutInflater i = getLayoutInflater();
leDeviceListAdapter.addDevice(result.getDevice());
leDeviceListAdapter.notifyDataSetChanged();
}
};
public void checkbluetooth(View view) {
//Intent i =new Intent(this, DeviceScanActivity.class);
//startActivity(i);
getpermissions();
BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
} else if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivityForResult(enableBtIntent, REQUEST_CODE_ASK_PERMISSIONS);
}
//findBle(bluetoothManager, bluetoothAdapter);
BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
LeDeviceListAdapter leDeviceListAdapter = new LeDeviceListAdapter();
leDeviceListAdapter.setLayoutInflater(getLayoutInflater());
for (int i=0;i<2;i++){
if (!scanning) {
// Stops scanning after a predefined scan period.
handler.postDelayed(new Runnable() {
#Override
public void run() {
scanning = false;
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
return;
}
bluetoothLeScanner.stopScan(leScanCallback);
}
}, SCAN_PERIOD);
scanning = true;
bluetoothLeScanner.startScan(leScanCallback);
} else {
scanning = false;
bluetoothLeScanner.stopScan(leScanCallback);
}}
}
LeDeviceList Class:
public class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
}
public LayoutInflater getmInflator(){
return mInflator;
}
public void setLayoutInflater(LayoutInflater li) {
mInflator=li;
}
public void addDevice(BluetoothDevice device) {
if (!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder = new ViewHolder(view);
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
//viewHolder = new RecyclerView.ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.textView4);
viewHolder.deviceName = (TextView) view.findViewById(R.id.textView5);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
if (ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return view;
}
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView deviceAddress;
public TextView deviceName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
}
}
This is my Manifest:
<?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.navigation" >
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission-group.NEARBY_DEVICES" />
<uses-feature
android:name="android.hardware.bluetooth"
android:required="false" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="false" />
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Navigation"
tools:targetApi="32" >
<activity
android:name=".DeviceScanActivity"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop" >
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Get Permissions Method:
public void getpermissions(){
// if ( Build.VERSION.SDK_INT >= 31) {
if ((ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) !=
PackageManager.PERMISSION_GRANTED) || (ActivityCompat.checkSelfPermission(this,
Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) ||
(ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED)
|| (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED)
|| (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
|| (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED)||
(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) !=
PackageManager.PERMISSION_GRANTED)||
(ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_PRIVILEGED) !=
PackageManager.PERMISSION_GRANTED)||
(ActivityCompat.checkSelfPermission(this, Manifest.permission_group.NEARBY_DEVICES) != PackageManager.PERMISSION_GRANTED)
) {
requestPermissions(new String[]{Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN
, Manifest.permission.BLUETOOTH_ADVERTISE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.ACTIVITY_RECOGNITION,
Manifest.permission.BLUETOOTH_SCAN, Manifest.permission_group.NEARBY_DEVICES,
Manifest.permission.BLUETOOTH_PRIVILEGED}, 1);
//requestPermissions(new String[]{Manifest.permission_group.NEARBY_DEVICES}, 1);
return;
}
// }
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int i=0; i<permissions.length; i++){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
int a =1;
} else {
// Permission Denied
Toast.makeText( this,"Try Again" , Toast.LENGTH_SHORT)
.show();
}}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

Android Studio access files

want to open up text documents as text in an android app. I am working in Android Studio using Java. I have permissions set to allowed an I request user permissions, I researched a lot and could not find anything more than what I have. An error comes up that permission is not granted. I am using an android 7 or higher. Please help!
My code in MainActivity is:
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
//for asking permission
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE};
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu (menu);
}
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.open_note){
//get txt from file and send as text to textEditor action
//pick the file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(
Intent.createChooser(intent, "Choose a file"),
8778
);
}
if (item.getItemId() == R.id.new_note){
//New Note
Intent intent = new Intent (getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
//get the file path as string
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8778 && resultCode == Activity.RESULT_OK){
checkPermissions();
if (ContextCompat.checkSelfPermission(
MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
//build the uri
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
verifyStoragePermissions(MainActivity.this);
String baseDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
StringBuilder text = new StringBuilder();
//request permission
final int REQUEST_CODE_ASK_PERMISSIONS = 1;
final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE};
try {
BufferedReader br = new BufferedReader(new
FileReader(("/storage/emulated/0/download/paperclip.txt")));
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("File
Name").setMessage("YAY").show();
String line=br.readLine();
while (!((line).equals(null))) {
text.append(line);
text.append('\n');
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("File
Name").setMessage(line + "great").show();
}
br.close();
} catch (IOException e) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("File
Name").setMessage("In the catch!" + e).show();
}
String result = text.toString();
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("File Info")
.setMessage(result + "result")
.show();
// You can use the API that requires the permission.
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert) .setTitle("File
Name").setMessage("GRANTED").show();
//performAction(...);
}
}
}
protected void checkPermissions() {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert) .setTitle("File Name").setMessage("In
Check Permissions").show();
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listVeiw);
SharedPreferences sharedPreferences =
getApplicationContext().getSharedPreferences("com.example.notepadr", Context.MODE_PRIVATE);
//Dealing with saving and stuff!!!!!
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if (set==null){
notes.add("Example note");
}else{
notes = new ArrayList(set);
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
My xml in activity_main.xml is:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="-16dp"
tools:layout_editor_absoluteY="-69dp">
<Button
android:id="#+id/storage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Storage"
android:layout_marginTop="16dp"
android:padding="8dp"
android:layout_centerHorizontal="true"/>
<ListView
android:id="#+id/listVeiw"
android:layout_width="400dp"
android:layout_height="732dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="false"
android:layout_marginTop="3dp"
android:layout_marginEnd="7dp"
android:layout_marginBottom="-3dp"
android:scrollbarSize="5dp"
android:scrollbarStyle="outsideInset" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Code in AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notepadr">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:requestLegacyExternalStorage="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.NotePadR">
<activity android:name=".NoteEditorActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
enter code here <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Service doesn't work with Oreo 8.1 - The Detector does not work, nor does the process in the background

My call detector app is running fine on all android version except 8 Oreo. I get a deadlock paradigm: My detector is not called, and when I close the application the system kills it, not leaving it in the background.
I have already read the documentation from cable to tail https://developer.android.com/about/versions/oreo/background, I already looked a lot in google, and here in stack over flow, but no solution applied to my case, because of the required "dangerous" permissions.
My case seems simple: I have a detector, a service and the main with a button. I want it when the user calls a certain number, my main open.
What is the right way to fix this issue?
manifest.xml :
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.ACTION_MANAGE_OVERLAY_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">
<service
android:name=".CallDetectionService"
android:enabled="true"
android:exported="false"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</activity>
</application>
CallDetectionService.java
public class CallDetectionService extends Service {
private CallDetector callDetector;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
callDetector = new CallDetector(this);
int r = super.onStartCommand(intent, flags, startId);
callDetector.start();
return r;
}
#Override
public void onDestroy() {
super.onDestroy();
callDetector.stop();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
CallDetector.java
public class CallDetector {
public static final String MY_PREF = "MY_PREF";
public static final String NUMBER_KEY = "NUMBER_KEY";
private SharedPreferences sharedPreferences;
public class OutgoingDetector extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
String compare_num = "12345678";
if (number.equals(compare_num)) {
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
setResultData(null);
context.startActivity(i);
}
}
}
private Context ctx;
private OutgoingDetector outgoingDetector;
public CallDetector(Context ctx) {
this.ctx = ctx;
outgoingDetector = new OutgoingDetector();
}
public void start() {
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
ctx.registerReceiver(outgoingDetector, intentFilter);
}
public void stop(){
ctx.unregisterReceiver(outgoingDetector);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button button;
private TextView textView;
private boolean detecting = false;
private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 0;
public boolean isPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG", "Permission is granted");
return true;
} else {
Log.v("TAG", "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1);
return false;
}
} else {
Log.v("TAG", "Permission is granted");
return true;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
/* button.setOnClickListener(this); */
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CALL_PHONE)) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
}
}
String action = "START";
final Intent intent = new Intent(this, CallDetectionService.class);
intent.setAction(action);
startService(intent);
}
#Override
public void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(CallDetector.MY_PREF, MODE_PRIVATE);
String number = sharedPreferences.getString(CallDetector.NUMBER_KEY, "URA VISUAL");
textView.setText(number);
}
}
What am I doing so wrong? I've been looking for a solution for 4 days and I still have not found anything.

textRecognizer.isOperational() return false

i run the app in emulator it works but run it in phone api 17 and api 22 textRecognizer.isOperational() return false
what is the problem?
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.CAMERA"/>
<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>
<meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="ocr"/>
</application>
MainActivity
public class MainActivity extends AppCompatActivity {
SurfaceView CameraView;
TextView textView;
CameraSource cameraSource;
final int RequestCameraPermissionID = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraView = (SurfaceView) findViewById(R.id.surface_view);
textView = (TextView) findViewById(R.id.textview);
final TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
if (!textRecognizer.isOperational()) {
Log.w("MainActivity", "dependencies are not available");
} else {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 1024)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
CameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA},RequestCameraPermissionID);
return;
}
try {
cameraSource.start(CameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> item = detections.getDetectedItems();
if(item.size() != 0){
textView.post(new Runnable() {
#Override
public void run() {
StringBuilder stringBuilder = new StringBuilder();
for (int i=0;i<item.size();i++){
TextBlock items = item.valueAt(i);
stringBuilder.append(items.getValue());
stringBuilder.append("\n");
}
textView.setText(stringBuilder.toString());
}
});
}
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case RequestCameraPermissionID:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(CameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
please help thanks
emulator api 25
phone huawei g730 u10 api 17
Imet api 22
Everytime I launch the apk, "Text recognizer could not be set up : is displayed. Even though I have set all dependencies but still i am getting this error. Please help why TextRecognizer.isOperational() is always false.

Voice recognition dialog says network not connected

I'm making an app that uses Voice Recognition. And it works perfectly with Android KitKat 4.4.4 (API 19). But when I try it on Nouget 7.0 (API 24) or Lollipop voice recognition dialog box says Network not connected.
I have internet connection, and I have added permissions in Manifest.
What might be the issue?
Here's my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.woop.loudness">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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>
<activity android:name=".WebList" android:label="#string/app_name" />
<activity android:name=".AddWeb" android:label="#string/app_name" />
<!--<service android:enabled="true" android:name=".UartService" />-->
</application>
</manifest>
As requested, my main activity:
public class MainActivity extends AppCompatActivity {
DBHelper myDb;
public int i;
public int b;
private static final int sampleRate = 44100;
private static final int bufferSizeFactor = 10;
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private final int MY_PERMISSIONS_RECORD_AUDIO = 1;
private AudioRecord audio;
private int bufferSize;
private ProgressBar level;
private Handler handler = new Handler();
private int lastLevel = 0;
Button btnView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DBHelper(this);
btnView = (Button) findViewById(R.id.button2);
level = (ProgressBar) findViewById(R.id.progressbar_level);
level.setMax(32676);
bufferSize = AudioRecord.getMinBufferSize(sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT) * bufferSizeFactor;
requestAudioPermissions();
//audio.startRecording();
Thread thread = new Thread(new Runnable() {
public void run() {
readAudioBuffer();
}
});
thread.setPriority(Thread.currentThread().getThreadGroup().getMaxPriority());
thread.start();
handler.postDelayed(update, 100);
btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, WebList.class);
startActivity(intent);
}
});
}
private void readAudioBuffer() {
try {
short[] buffer = new short[bufferSize];
int bufferReadResult;
do {
bufferReadResult = audio.read(buffer, 0, bufferSize);
for (int i = 0; i < bufferReadResult; i++){
if (buffer[i] > lastLevel) {
lastLevel = buffer[i];
}
}
// if sound level is over 20000 start voice recognition
if (lastLevel > 20000){
lastLevel = 0;
startVoiceRecognitionActivity();
Thread.sleep(7000);
}
} while (bufferReadResult > 0 && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);
} catch (Exception e) {
e.printStackTrace();
}
}
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Kalbėkite");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
i = 0;
if (matches.contains("Add") || matches.contains("add") || matches.contains("Pridėti") || matches.contains("pridėti")) {
startActivity(new Intent(this, WebList.class));
}
if (matches.contains("List") || matches.contains("list") || matches.contains("Sąrašas") || matches.contains("sąrašas")) {
startActivity(new Intent(this, AddWeb.class));
}
// Atidaro internetini puslapi
Cursor web = myDb.getAllData();
while (web.moveToNext()) {
if (matches.contains(web.getString(2))) {
b = i;
goToUrl();
}
i++;
}
}
}
private void goToUrl () {
int temp = 0;
WebView webview = new WebView(this);
setContentView(webview);
Cursor web = myDb.getAllData();
while (web.moveToNext()) {
if (temp == b) {
webview.loadUrl("https://" + web.getString(1));
}
temp++;
}
}
//delete this in final product
private Runnable update = new Runnable() {
public void run() {
MainActivity.this.level.setProgress(lastLevel);
lastLevel *= .5;
handler.postAtTime(this, SystemClock.uptimeMillis() + 500);
}
};
private void requestAudioPermissions() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
//When permission is not granted by user, show them message why this permission is needed.
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.RECORD_AUDIO)) {
Toast.makeText(this, "Please grant permissions to record audio", Toast.LENGTH_LONG).show();
//Give user option to still opt-in the permissions
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_RECORD_AUDIO);
} else {
// Show user dialog to grant permission to record audio
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_RECORD_AUDIO);
}
}
//If permission is granted, then go ahead recording audio
else if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO)
== PackageManager.PERMISSION_GRANTED) {
audio = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
bufferSize);
//Go ahead with recording audio now
audio.startRecording();
}
}
}
I have copied your code, you are getting an error, take debug off of the "Selected App"
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393237 | Error code: 393222 | couldn't start recording, state is:1
This is because you are still recording/capturing data in your main activity without releasing the audio, I added it here and it works fine, but do not forget to restart it again
public void startVoiceRecognitionActivity() {
audio.stop();
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Kalbėkite");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}

Categories