To launch an Android application I use below code which works for fine for every application
installed on phone except for the "Phone" application itself. When I attempt to launch "Phone" the
app is not launced and no error message or displayed or exception thrown.
This is the code I'm using to launch the application :
launchApp(context, packageManager,
"com.android.phone");
/*
* Launch an application
*
* #param c Context of application
*
* #param pm the related package manager of the context
*
* #param pkgName Name of the package to run
*/
public static boolean launchApp(Context c, PackageManager pm, String pkgName) {
// query the intent for lauching
Intent intent = pm.getLaunchIntentForPackage(pkgName);
// if intent is available
if (intent != null) {
try {
// launch application
c.startActivity(intent);
// if succeed
return true;
// if fail
} catch (ActivityNotFoundException ex) {
// quick message notification
Toast toast = Toast.makeText(c, "Application Not Found",
Toast.LENGTH_LONG);
// display message
toast.show();
}
}
// by default, fail to launch
return false;
}
Is this the correct method to use for launching an Android application and/or is the "Phone"
app a special case which does not allow other applications to launch/use it ?
Try with this code:
Intent intent = new Intent(Intent.ACTION_DIAL);
startActivity(intent);
Related
Some Android phones don't do anything when the the code below is ran. It's supposed to open the "About device" page in Settings.
For example, I know for a fact that it has no effect on the Huawei Y9 Prime 2019 running Android 10.
startActivity(new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS));
What's the best way to safeguard against this issue when it occurs? (In my app, I open this page to ask the user to perform a specific action there)
Use PackageManager.resolveActivity() to check whether such an Activity exists. If that returns null, there is no activity that matches the Intent and you have to guide your customers to the settings in another way:
Intent intent = new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS);
ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, 0);
if (resolveInfo == null) {
// help customers by describing how to get to the device info settings
} else {
startActivity(intent);
}
If an activity is not found, the method startActivity will throw android.content.ActivityNotFoundException. You should catch this exception and notify the user:
try {
startActivity(new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS));
} catch (ActivityNotFoundException e) {
// Notify the user, eg. using a popup so they can open settings manually
}
I want to create an app,that's use to only allow access specific apps in a device.So I tried to pinned the device.Now I want to open another application that is in my specific apps list.
I can't open another app while pinned.
This is the code I used to pinned
startLockTask();
and this is the code to I tried to open another appilication in kiosk mode
ComponentName deviceAdmin = new ComponentName(KioskActivity.this, MyAdmin.class);
if (myDevicePolicyManager.isDeviceOwnerApp(getPackageName()))
{
myDevicePolicyManager.setLockTaskPackages(deviceAdmin, new String[]{getPackageName(), "com.example.pan.pocmdmhelper"});
try
{
PackageManager pm = KioskActivity.this.getPackageManager();
Intent it = pm.getLaunchIntentForPackage("com.example.pan.pocmdmhelper");
it.addCategory(Intent.CATEGORY_LAUNCHER);
if (null != it) {
KioskActivity.this.startActivity(it);
Toast.makeText(KioskActivity.this, "Started activity for this package", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
Toast.makeText(KioskActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
finish();
}
}
At the moment I tried to open single app by using it's package name.It's open if I unpinned only
I have created an app that runs a service to read which app/activity user have opened and using it at the current time. The problem is that the service reads only the launcher application. It doesn't return me the cirrently open app/activity. Can you help? The code i write is below. Thanks in advance.
#Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
Runnable runable = new Runnable() {
public void run() {
try{
ActivityManager am2 = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
String packageName = am2.getRunningTasks(1).get(0).topActivity
.getPackageName();
Log.w("RunningTask", packageName);
handler.postDelayed(this, 8000);
}
catch (Exception e){
}
}
};
handler.postDelayed(runable, 8000);
}
If you use Android 5.0 or above, getRunningTasks() is deprecated and will only return a small subset, including the caller's own tasks, and possibly some other tasks such as home.
You may check out getRunningAppProcesses() which worked before Android 5.1.1. See Cannot get foreground activity name in Android Lollipop 5.0 only and Android 5.1.1 and above - getRunningAppProcesses() returns my application package only
Example using getRunningAppProcesses:
ActivityManager am2 = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
String processName = am2.getRunningAppProcesses().get(0).processName;
Log.w("Running process", processName);
I am developing an Android App which requires speech to text conversion. Currently I have used Google voice search for this purpose but using google requires internet connection and moreover it gives highly inaccurate results for eg. when I say '1' it prints "when"..
Therefore, I want to define my own grammar such that when I give a voice command it searches the grammar defined by me to find the best possible match instead of searching the internet. Using grammar for speech recognition can be done easily for windows 8 phone but I want to know how I can make this work for Android phones.
Kindly take a look at below codes!..
**Using Intent:::**
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
Without Using Intent::
Step 1: Implement RecognitionListener in your class.
Step 2. Add the Below codes:
private SpeechRecognizer speech = null;
private Intent speechIntent=null;
/**
* Speech Result is used to Store the Voice Commands
*/
private ArrayList<String> speechResult;
inside onCreate() --- >
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
Trigger this after your button Click:
if (SpeechRecognizer.isRecognitionAvailable(this)) {
if(speechIntent==null ){
speechIntent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
speechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
speechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,12);
speech.startListening(speechIntent);
}else{
if(speech!=null){
speech.startListening(speechIntent);
}
}
}
Replace the onResults link this:
public void onResults(Bundle results) {
speechResult = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(speechResult!=null){
if(speechResult.size()>0 ){
String command=speechResult.get(0).toString();
}
}
}
I have an android app which stores information in an SQLite DB. On the activity I can open the Gallery, select a video, and then click on the "Watch Video" button and play that video.
HOWEVER, if I leave that activity and come back later, the saved URI IS in my DB, but loading it through the SAME onclick function produces this Exception error. ANY IDEAS WHY??
public void launchVideo(View view) {
if (my_video != null) {
Uri uri = Uri.parse(my_video);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "video/*");
startActivity(intent);//THROWS ILLEGAL ACTIVITY WHEN WORKING FROM SAVED URI
}
else{...
Using debugger I see the following...
#Override
public void onClick(#NonNull View v) {
if (mResolvedMethod == null) {
resolveMethod(mHostView.getContext());
}
try {
mResolvedMethod.invoke(mResolvedContext, v);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Could not execute non-public method for android:onClick", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(
"Could not execute method for android:onClick", e);
}
}
Similar posts have mentioned issues being the xml or use of methods with the same name. I do not have any methods with the same name and the xml is below for the button:
<Button
android:id="#+id/watchVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="launchVideo"
android:text="#string/watch_my_video"
app:layout_constraintStart_toStartOf="#+id/youtube_link"
app:layout_constraintTop_toBottomOf="#+id/youTubeEditText" />
The URI being passed in both the working and non working case is: "content://com.android.providers.media.documents/document/video%3A595"
Finally in my Debugger I see the following which I take a confirmation everything is public:
mResolvedMethod = {Method#6254} "public void com.android.mybrazilianjiu_jitsudictionary.Controller.AttackDetail.launchVideo(android.view.View)"
accessFlags = 134742017
artMethod = 3966325964
declaringClass = {Class#6043} "class com.android.mybrazilianjiu_jitsudictionary.Controller.AttackDetail"
declaringClassOfOverriddenMethod = {Class#6043} "class com.android.mybrazilianjiu_jitsudictionary.Controller.AttackDetail"
dexMethodIndex = 555
hasRealParameterData = false
parameters = null
override = false
shadow$_klass_ = {Class#3637} "class java.lang.reflect.Method"
shadow$_monitor_ = -2092042593
My latest guess is it is related to:
try {
mResolvedMethod.invoke(mResolvedContext, v);
However, I am just trying to have the video appear in the user's video player via implicit intent which IS what happens until I leave the activity and come back. Note: via checking the database and Debugger the SAME URI is present and being passed to the method in all scenarios.
THANK YOU FOR YOUR INSIGHTS!
By the following, I was able to fix the problem:
IllegalStateException: Could not execute method for android:onClick when trying to migrate to another page? was VERY helpful. On this advice I replaced my Button on click method with the following IN the OnCreate:
Button watchVideoButton = findViewById(R.id.watchVideo);
watchVideoButton.setOnClickListener(new View.OnClickListener() {...
The problem that then surfaced was lack of persistent permissions for the Uri when returning to the activity.
Persistent permission was taken via the following:
getContentResolver().takePersistableUriPermission(uri, FLAG_GRANT_READ_URI_PERMISSION);
...which I placed BEFORE the onCreate in:
androidx.activity.result.ActivityResultLauncher<String> mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
my_video = uri.toString();
getContentResolver().takePersistableUriPermission(uri, FLAG_GRANT_READ_URI_PERMISSION);
Move move;
move = new Move(MoveID,PositionTableID, MoveName, MoveStatus, GiY,AttackY, DefenseY, Description, internetVideoLink, my_video);
myJiuJitsuDictionaryRepository.insert(move);
}
});