I need to show a floating icon only along with a started maps activity and stop it when the map activity is gone.(when the user navegates back from the maps to my app) floating service over maps
mIntent = new Intent(MainActivity.this, FloatingIconService.class);
public void startTrip(String s , String d)
{
Uri gmIntentUri = Uri.parse("https://www.google.co.in/maps/dir/" + s + "/" + d);
Intent mapIntent = new Intent(Intent.ACTION_VIEW,gmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
mapIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(mapIntent,4000);
//view floating notes icon
startService(mIntent);
}
onPause is necessary to keep the service runnig along with maps and onActivityResult doesnot do what I want
#Override
protected void onPause() {
super.onPause();
// To prevent starting the service if the required permission is NOT granted.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(this)) {
startService(new Intent(MainActivity.this, FloatingIconService.class).putExtra("activity_background", true));
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DRAW_OVER_OTHER_APP_PERMISSION) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Toast.makeText(this, "Premission not granted", Toast.LENGTH_SHORT).show();
finish();
}
}
} else if (requestCode==4000 && (resultCode == Activity.RESULT_CANCELED || resultCode == Activity.RESULT_OK)){
stopService(mIntent);
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startTrip("USA", "Alexandria");
}
});
Related
Presently, in my application, when the user is asked to provide "Access all files" permission, the dialog opens and remains on screen even when the user has allowed permission. Below provided screenshot shows the dialog I am referring to:-
I would like to add something in my code, which closes this dialog and opens target activity screen as soon as the user enables the toggle of "Allow access to all files".
GrantPermissionsActivity :-
public class GrantPermissionsActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
MaterialButton cancelMaterialButton, grantMaterialButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grant_permissions);
findViews();
initViews();
}
private void findViews() {
cancelMaterialButton = findViewById(R.id.materialButtonCancel);
grantMaterialButton = findViewById(R.id.materialButtonGrant);
}
private void initViews() {
if (checkPermission()){
Intent intent = new Intent(GrantPermissionsActivity.this,PasswordActivity.class);
}
cancelMaterialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(GrantPermissionsActivity.this, "Need to give permission!", Toast.LENGTH_SHORT).show();
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
grantMaterialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
Toast.makeText(GrantPermissionsActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show();
} else if (!checkPermission()) {
requestPermission();
}
}
});
}
private boolean checkPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
return Environment.isExternalStorageManager();
} else {
int result = ContextCompat.checkSelfPermission(GrantPermissionsActivity.this, READ_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(GrantPermissionsActivity.this, WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
}
private void requestPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
startActivityForResult(intent, 2296);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2296);
}
} else {
//below android 11
ActivityCompat.requestPermissions(GrantPermissionsActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// perform action when allow permission success
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Allow permission for storage access!", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.d(TAG, "onActivityResult: Reachedinresult");
if (requestCode == 2296 && resultCode == RESULT_OK) {
Log.d(TAG, "onActivityResult: Reached request code");
if (SDK_INT >= Build.VERSION_CODES.R) {
Log.d(TAG, "onActivityResult: Reached SDKINT");
if (Environment.isExternalStorageManager()) {
// perform action when allow permission success
/*Intent intent = new Intent(GrantPermissionsActivity.this,PasswordActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);*/
Log.d(TAG, "onActivityResult: Reached");
} else {
checkPermission();
Toast.makeText(this, "Permission not granted", Toast.LENGTH_SHORT).show();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Please let me know the changes in the above code.
Also, check the below sample for reference:-
Replace the method requestPermission() to
private void requestPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
startActivityForResult(intent, 2296);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2296);
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if(Environment.isExternalStorageManager()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// perform action when allow permission success in android 11
}
});
this.cancel();
}
}
},2000,1000);
}
} else {
//below android 11
ActivityCompat.requestPermissions(GrantPermissionsActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}}
If you want to start an activity from there, add flag Intent.FLAG_ACTIVITY_NEW_TASK in the Intent object, otherwise it may not work.
Issue:
I have a Listview in Mainactivity. Each row of listview has two buttons say SET and RUN.
Pressing SET will take you to SET activity and if the user clicks save button in SET Activity, I need to disable the SET button in the corresponding row position of the listview in mainactivity.
So Far Done:
For that I have a refresh function on a onclicklistener to requery the list with updated values. How to call that refresh function without keypress in the Mainactivity or is there any other way?
Activity MAIN :
viewHolder.ButtonSET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = v.getTag().toString();
if (title.equals("SET")) {
if (Integer.parseInt((String) viewHolder.TDNQTY.getText()) > 0) {
if(scanoverornot(pos)<=0) {
Intent s = new Intent(DN.this, SETActivity.class);
s.putExtra("position", pos);
s.putExtra("mode", "SET");
try{
startActivityForResult(s, saverequestcode);
// getContext().startActivity(s);
}
catch(Exception e){
Toast.makeText(getContext(),""+e,Toast.LENGTH_LONG).show();
}
}
}
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case saverequestcode:
if (resultCode == RESULT_OK) {
String SItem= data.getStringExtra("SItem");
int SPos= data.getIntExtra("SPos", 0);
saved = 700;
Toast.makeText(getApplicationContext(), ""+ SItem+ SPos, Toast.LENGTH_LONG).show();
//btnvalidate.performClick();
}
}
}
Activity SET :
Intent sav = new Intent();
sav.putExtra("SItem", String.valueOf(itemno));
sav.putExtra("SPos", String.valueOf(pos));
setResult(RESULT_OK, sav);
finish();
You can use startActivityForResult to nail this purpose:
startActivityForResult(new Intent(this, DestinationActivity.class), MY_RESULT);
And then in your MainActivity:
public int MY_RESULT = 10;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_RESULT) {
if (resultCode == Activity.RESULT_OK) {
//refresh the list according to your logic
}
}
}
Don't forget to call setResult(Activity.RESULT_OK); when user clicks save button.
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setResult(Activity.RESULT_OK);
}
});
Issue Lines:
Have to add super.onActivityResult(requestCode, resultCode, data);
Removed switch case and used if condition for requestCode check
Solution:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null)
return;
if (requestCode == saverequestcode) {
if (resultCode == Activity.RESULT_OK) {
String SItem = data.getStringExtra("SItem");
String SPos = data.getStringExtra("SPos");
Toast.makeText(getApplicationContext(), "Item :" + SItem + "Position :" + SPos, Toast.LENGTH_LONG).show();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Any methods
}
}
else if (requestCode == importrequestcode){
}
}
Activity SET :
Intent sav = new Intent();
sav.putExtra("SItem", String.valueOf(itemno));
sav.putExtra("SPos", String.valueOf(pos));
setResult(Activity.RESULT_OK,sav);
finish();
I'm trying to deal with the new Android Lollipop MediaProjection API.
I have found that (at least on my stock Samsung Galaxy S4 jfltexx) when I start the intent to get permission to capture the screen (ProjectionManager.createScreenCaptureIntent()), I won't have a result in onActivityResult unless I have checked "Don't ask again" on the preceding try ...
private static final int ALLOW_SCREENSHOT_REQ = 102;
{
...
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
System.out.println("request permission");
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), ALLOW_SCREENSHOT_REQ);
}
...
}
And the result handling:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("RebootActivity.onActivityResult(" + requestCode + "," + resultCode + ", data)");
}
The permission dialog is showing well, but my activity gets hidden and it never goes to onActivityResult.
Any idea of what's going wrong?
Have you tried like this: See Full Example android-ScreenCapture
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_MEDIA_PROJECTION) {
if (resultCode != Activity.RESULT_OK) {
Log.i(TAG, "User cancelled");
Toast.makeText(getActivity(), R.string.user_cancelled, Toast.LENGTH_SHORT).show();
return;
}
Activity activity = getActivity();
if (activity == null) {
return;
}
Log.i(TAG, "Starting screen capture");
mResultCode = resultCode;
mResultData = data;
setUpMediaProjection();
setUpVirtualDisplay();
}
}
Hope it will helps you.
This code working properly on lollypop version, But, when i use it on Kitkat, it always returns 0 when i choose "Yes/No" option from dialog.
btnSMSRestore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (currentapiVersion >= android.os.Build.VERSION_CODES.KITKAT){
defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(SMSActivity.this);
if (!getPackageName().equals(defaultSmsApp))
{
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
//startActivity(intent);
startActivityForResult(intent, DEF_SMS_REQ);
}
}
else
{
new RestoreSMS().execute();
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case DEF_SMS_REQ:
if(resultCode == Activity.RESULT_OK)
{
new RestoreSMS().execute();
}
}
}
Activity.RESULT_OK value is -1 and resultCode in onActivityResult is always 0 when use with kitkat.
From the Android documentation:
onActivityResult Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it
returned, and any additional data from it. The resultCode will be
RESULT_CANCELED if the activity explicitly returned that, didn't
return any result, or crashed during its operation.
RESULT_CANCELED value is 0, probably on KitKat is not set a result value and the default one is returned.
As workaround on KitKat, you can try to check if your app is the default one when onActivityResult is fired. Try this code:
btnSMSRestore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if (!isDefaultSmsApp(SMSActivity.this)) {
{
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivityForResult(intent, DEF_SMS_REQ);
}
} else {
new RestoreSMS().execute();
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case DEF_SMS_REQ:
if (Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT && isDefaultSmsApp(this) ||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && resultCode == Activity.RESULT_OK) {
new RestoreSMS().execute();
}
break;
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public static boolean isDefaultSmsApp(Context context) {
return context.getPackageName().equals(Telephony.Sms.getDefaultSmsPackage(context));
}
The first time I call startActivityForResult() with requestCode x it return to onActivityResult().But the second time I call startActivityForResult() within the same activity with diffrent requestCode it doesnt return to the onActivityResult() and just proceed
with the code.
I have tried to add this property to the manifest andter the activity
android:noHistory
Why it doesnt return to onActivityResult()?And how i can fix it?
Thanks a lot,
Leon
Edit: Here is my code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
myTTS = new TextToSpeech(this, this);
}
else {
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
else if(RESULT_SPEECH == requestCode)
{
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
textFromSpeech = text.get(0);
}
}
}
private void getTextFromSpeech()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Ops! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tts_);
/*
* New Intent purely for the purposes of checking the user data
*/
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}