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>
Related
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);
}
}
I recently developed an android app that streams radio online using a URL. It has been working well in other android versions that is 6,7and 8 the ones i tested in emulators.
But last week i published the app to play store, and my reports show that it crashes in android 9 phones. It keeps on throwing java.lang.SecurityException.
I have tried what i could to resolve the error but i have failed.
The users keep reporting multiple app crashes on their phones
This is the stack trace from the play console
java.lang.RuntimeException:
at android.app.ActivityThread.handleServiceArgs (ActivityThread.java:3903)
at android.app.ActivityThread.access$1700 (ActivityThread.java:236)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1815)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:214)
at android.app.ActivityThread.main (ActivityThread.java:7032)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:965)
Caused by: java.lang.SecurityException:
at android.os.Parcel.createException (Parcel.java:1966)
at android.os.Parcel.readException (Parcel.java:1934)
at android.os.Parcel.readException (Parcel.java:1884)
at android.app.IActivityManager$Stub$Proxy.setServiceForeground (IActivityManager.java:5043)
at android.app.Service.startForeground (Service.java:695)
at com.premar.radiomunabuddu.RadioMediaPlayerService.play (RadioMediaPlayerService.java:120)
at com.premar.radiomunabuddu.RadioMediaPlayerService.onStartCommand (RadioMediaPlayerService.java:50)
at android.app.ActivityThread.handleServiceArgs (ActivityThread.java:3884)
Caused by: android.os.RemoteException:
at com.android.server.am.ActivityManagerService.enforcePermission (ActivityManagerService.java:12159)
at com.android.server.am.ActiveServices.setServiceForegroundInnerLocked (ActiveServices.java:1289)
at com.android.server.am.ActiveServices.setServiceForegroundLocked (ActiveServices.java:969)
at com.android.server.am.ActivityManagerService.setServiceForeground (ActivityManagerService.java:24839)
at android.app.IActivityManager$Stub.onTransact$setServiceForeground$ (IActivityManager.java:11378)
This is the HomeActivity.java
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FancyButton listenRadio;
ImageView facebook, twitter, instagram, linkedin;
RadioSettings settings;
Context context;
public static final int REQUEST_CODE =123;
private Button stopButton = null;
private Button playButton = null;
private Button phoneCall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ButterKnife.bind(this);
settings = new RadioSettings();
//views
phoneCall = (Button)this.findViewById(R.id.phoneBtn);
//Allow hardware audio buttons to control volume
setVolumeControlStream(AudioManager.STREAM_MUSIC);
clickListeners(); //Start click listeners
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void openFacebookProfile() {
try {
String facebookURL = getFacebookPageUrl();
Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
facebookIntent.setData(Uri.parse(facebookURL));
startActivity(facebookIntent);
} catch (Exception e){
e.printStackTrace();
}
}
private String getFacebookPageUrl() {
final String facebookUrl = settings.getFacebookAddress();
String fbURL = null;
PackageManager packageManager = getPackageManager();
try {
if (packageManager != null){
Intent fbIntent = packageManager.getLaunchIntentForPackage("com.facebook.katana");
if (fbIntent != null){
int versionCode = packageManager.getPackageInfo("com.facebook.katana",0).versionCode;
if (versionCode >= 3002850){
fbURL = "fb://page/1993598950880589";
}
} else {
fbURL = facebookUrl;
}
}
else {
fbURL = facebookUrl;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
fbURL = facebookUrl;
}
return fbURL;
}
private void openTwitterProfile(){
Intent intent = null;
try {
this.getPackageManager().getPackageInfo("com.twitter.android", 0);
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("twitter://user?user_id=USERID"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} catch (Exception e){
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/profilename"));
}
this.startActivity(intent);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.watch_webcam: {
launchWebcam();
break;
}
case R.id.playstore_share: {
/*
Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName())));
}
break;
*/
}
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_share) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareMessage= "\nPlease download our Radiomunnabuddu USA app from the Play Store\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID +"\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT , shareMessage);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Radio Munnabuddu USA");
startActivity(Intent.createChooser(shareIntent, "Share via..."));
}
else if (id == R.id.nav_email){
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto: "+settings.getEmailAddress()));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Radio Munnabuddu USA");
if (emailIntent.resolveActivity(getPackageManager()) != null){
startActivity(Intent.createChooser(emailIntent, "Send email via"));
}
}
else if(id == R.id.nav_report){
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto: denis#premar.tech"));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Crash or Bug report");
if (emailIntent.resolveActivity(getPackageManager()) != null){
startActivity(Intent.createChooser(emailIntent, "Send email via."));
}
}
else if(id == R.id.nav_about){
Intent aboutIntent = new Intent(HomeActivity.this, AboutActivity.class);
startActivity(aboutIntent);
}
else if(id == R.id.nav_fb){
openFacebookProfile();
}
else if(id == R.id.nav_twitter){
openTwitterProfile();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* Listens for contact button clicks
*/
private void clickListeners(){
//Play button
playButton = (Button)findViewById(R.id.PlayButton);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
RadioMediaPlayerService.class);
intent.putExtra(RadioMediaPlayerService.START_PLAY, true);
startService(intent);
}
});
//Stop button
stopButton = (Button)findViewById(R.id.StopButton);
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get new MediaPlayerService activity
Intent intent = new Intent(getApplicationContext(),
RadioMediaPlayerService.class);
stopService(intent);
}
});
//Email Button click list
final View EmailPress = (Button)this.findViewById(R.id.emailBtn);
EmailPress.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto: "+settings.getEmailAddress()));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Radio Munnabuddu");
if (emailIntent.resolveActivity(getPackageManager()) != null){
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(HomeActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
});
//Website Button
final View WWWPress = (Button)this.findViewById(R.id.websiteBtn);
WWWPress.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(settings.getWebsiteURL())); //URL
startActivity (browserIntent);
}
});
//SMS Button
final View TxtPress = (Button)this.findViewById(R.id.txtBtn);
TxtPress.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Uri uri = Uri.parse(settings.getSmsNumber());
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "Hello Presenter,");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
/*
if (ActivityCompat.checkSelfPermission(HomeActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED){
Toast.makeText(HomeActivity.this, "Please grant the permission to call", Toast.LENGTH_SHORT).show();
requestSMSPermission();
}
else {
startActivity (smsIntent);
}*/
}
});
}
/**
* Launches webcam from external URL
*/
public void launchWebcam(){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(settings.getRadioWebcamURL()));
startActivity (browserIntent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
onCall();
} else {
Log.d("TAG", "Call Permission Not Granted");
//Toast.makeText(this, "Call Permission Not Granted", Toast.LENGTH_SHORT).show();
}
return;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public void onCall() {
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.CALL_PHONE},
REQUEST_CODE);
} else {
phoneCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
/*
String phoneNum = settings.getPhoneNumber();
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
phoneIntent.setData(Uri.parse("tel:"+ phoneNum));
if (phoneIntent.resolveActivity(getPackageManager()) != null) {
startActivity(phoneIntent);
}
*/
startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:" + settings.getPhoneNumber())));
}
});
}
}
This is the RadioMediaPlayerService.java
public class RadioMediaPlayerService extends Service implements
AudioManager.OnAudioFocusChangeListener {
//Variables
private boolean isPlaying = false;
private MediaPlayer radioPlayer; //The media player instance
private static int classID = 579; // just a number
public static String START_PLAY = "START_PLAY";
AudioManager audioManager;
//Media session
MediaSession mSession;
//Settings
RadioSettings settings = new RadioSettings();
#Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Starts the streaming service
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getBooleanExtra(START_PLAY, false)) {
play();
}
//Request audio focus
if (!requestAudioFocus()) {
//Could not gain focus
stopSelf();
}
return Service.START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
/**
* Starts radio URL stream
*/
private void play() {
//Check connectivity status
if (isOnline()) {
//Check if player already streaming
if (!isPlaying) {
isPlaying = true;
//Return to the current activity
Intent intent = new Intent(this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// mSession.setSessionActivity(pi);
//Build and show notification for radio playing
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
R.drawable.buddu3);
Notification notification = new NotificationCompat.Builder(this, "ID")
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setTicker("Radio Munnabuddu USA")
.setContentTitle(settings.getRadioName())
.setContentText(settings.getMainNotificationMessage())
.setSmallIcon(R.drawable.ic_radio_black_24dp)
//.addAction(R.drawable.ic_play_arrow_white_64dp, "Play", pi)
// .addAction(R.drawable.ic_pause_black_24dp, "Pause", pi)
.setLargeIcon(largeIcon)
.setContentIntent(pi)
.build();
//Get stream URL
radioPlayer = new MediaPlayer();
try {
radioPlayer.setDataSource(settings.getRadioStreamURL()); //Place URL here
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
radioPlayer.prepareAsync();
radioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
radioPlayer.start(); //Start radio stream
}
});
startForeground(classID, notification);
//Display toast notification
Toast.makeText(getApplicationContext(), settings.getPlayNotificationMessage(),
Toast.LENGTH_LONG).show();
}
}
else {
//Display no connectivity warning
Toast.makeText(getApplicationContext(), "No internet connection",
Toast.LENGTH_LONG).show();
}
}
/**
* Stops the stream if activity destroyed
*/
#Override
public void onDestroy() {
stop();
removeAudioFocus();
}
/**
* Stops audio from the active service
*/
private void stop() {
if (isPlaying) {
isPlaying = false;
if (radioPlayer != null) {
radioPlayer.release();
radioPlayer = null;
}
stopForeground(true);
}
Toast.makeText(getApplicationContext(), "Radio stopped",
Toast.LENGTH_LONG).show();
}
/**
* Checks if there is a data or internet connection before starting the stream.
* Displays Toast warning if there is no connection
* #return online status boolean
*/
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
public void onAudioFocusChange(int focusChange) {
//Invoked when the audio focus of the system is updated.
switch (focusChange) {
/*
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
// if (radioPlayer == null) initMediaPlayer();
if (radioPlayer.isPlaying()){
radioPlayer.release();
stopForeground(true);
}
radioPlayer.setVolume(1.0f, 1.0f);
break;*/
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (radioPlayer.isPlaying()) radioPlayer.stop();
radioPlayer.release();
//radioPlayer = null;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Lost focus for a short time, but we have to stop
// playback. We don't release the media player because playback
// is likely to resume
if (radioPlayer.isPlaying()) radioPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (radioPlayer.isPlaying()) radioPlayer.setVolume(0.1f, 0.1f);
break;
}
}
/**
* AudioFocus
*/
private boolean requestAudioFocus() {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//Focus gained
return true;
}
//Could not gain focus
return false;
}
private boolean removeAudioFocus() {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
audioManager.abandonAudioFocus(this);
}
}
This is the Manifest.xml
<!--uses-permission android:name="android.permission.SEND_SMS" /-->
<uses-permission android:name="android.permission.INTERNET" />
<!--uses-permission android:name="android.permission.CALL_PHONE" /-->
<!--tools:node="remove"-->
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
<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"
tools:ignore="GoogleAppIndexingWarning">
<service
android:name="com.premar.radiomunabuddu.RadioMediaPlayerService"
android:enabled="true" >
</service>
<receiver android:name="com.premar.radiomunabuddu.IntentReceiver">
<intent-filter>
<action android:name="android.media.AUDIO_BECOMING_NOISY" />
</intent-filter>
</receiver>
<activity
android:name="com.premar.radiomunabuddu.HomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.premar.radiomunabuddu.AboutActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.premar.radiomunabuddu.HomeActivity" />
</activity>
</application>
Android 9 introduced a new FOREGROUND_SERVICE permission. From the docs:
Note: Apps that target Android 9 (API level 28) or higher and use foreground services must request the FOREGROUND_SERVICE permission. This is a normal permission, so the system automatically grants it to the requesting app.
If an app that targets API level 28 or higher attempts to create a foreground service without requesting FOREGROUND_SERVICE, the system throws a SecurityException.
Just add that permission to your manifest and you should be good to go.
The setServiceForegroundInnerLocked method will check based on the targetSdkVersion level。lack FOREGROUND_SERVICE permission
code:
if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
mAm.enforcePermission(
android.Manifest.permission.FOREGROUND_SERVICE,
r.app.pid, r.appInfo.uid, "startForeground");
}
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);
}
I am trying to attach a pdf file with my Gmail. But the problem is, it always shows a toast message which says "PERMISSION DENIED FOR THE ATTACHMENT". I tried on some different emails like Yahoo, but the file is still not being attached.
This is my Code for the Attachment:
case R.id.emailPdf:
try {
String filename = "SampleFile1.pdf";
File filelocation = new File(Environment.getDataDirectory() + "/data/" + getPackageName() + "/files/", filename);
filelocation.setReadable(true, false);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("vnd.android.cursor.dir/email");
String to[] = {""};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(emailIntent, "Send email..."), 12);
break;
}catch (Exception e){
e.printStackTrace();
}
These are the permissions in the AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I used the debugger, and I observed that the file is being read from the file location but dont know why its not getting attached.
Any help would be appreciated.
Thanks in advance.
Try like below:
Create method to check runtime permission.
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkExternalPermission() {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write external storage permission is necessary to read gallery pictures!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
Now on attach button click:
boolean result = checkExternalPermission();
if (result) {
activeGallery();
}
Create method to open gallery like below:
/**
* to gallery
*/
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
Now handle permission result like below:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
activeGallery();
} else {
Toast.makeText(getActivity(), "Permission not granted", Toast.LENGTH_LONG).show();
//code for deny
}
break;
}
}
Now handle activity result like below for your selected attachment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (resultCode == RESULT_OK && null != data) {
try {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// MyImage image = new MyImage();
// image.setTitle("Test");
// image.setDescription(
// "test choose a photo from gallery and add it to " +
// "list view");
// image.setDatetime(System.currentTimeMillis());
File file = new File(picturePath);
Uri imageUri = Uri.fromFile(file);
Product product = new Product(catID, "custom", "#1111", imageUri.toString(), "15000", "30%", 0);
dBhelper.createPRODUCT(product);
imageList.add(0, product);
// imageList.add(0, imageUri);
setimage(imageUri.toString(), imgview, true);
// imageList.add(0, picturePath);
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
// images.add(image);
}
break;
}
}
And finally declare below global variable:
private static final int RESULT_LOAD_IMAGE = 1;
public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 3;
Make sure below permission you have define in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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...