I am learning Android. I learned to use my app to start another app I wrote. Using this code below:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button appOpener = (Button) findViewById(R.id.button1);
appOpener.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent i = new Intent(Intent.ACTION_MAIN);
PackageManager firstApp = getPackageManager();
i = firstApp.getLaunchIntentForPackage("com.assignment.projecttomiko");
}
});
}
It's pretty straight-forward and I am happy wit it. But now I want to start apps already on the Android platform itself, like browser, calender, calculator, etc. From the above, I see I just have to put in the package name of my other apps. I am assuming I can do the same thing to say start a calculator. Or maybe not. What is the best way to do this? If I can use package names, then what are the package names of these in-built apps. If there's a better way I would like someone to help me out.
I read this: Opening System Application Using Intent and realised there's an introduction of an extra LaunchComponent I don't know what that is but the main thing is I see on that thread that they are also putting in some package names to call system apps. What'll be your best way to get this done? :)
EDIT:
I searched for hours and tried this code but doesn't work :(
// activity name and package for stock calculator
private static final String CALCULATOR_PACKAGE_NAME = "com.android.calculator2";
private static final String CALCULATOR_CLASS_NAME = "com.android.calculator2.Calculator";
public void launchCalculator() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new ComponentName(CALCULATOR_PACKAGE_NAME,
CALCULATOR_CLASS_NAME));
try {
this.startActivity(intent);
} catch (ActivityNotFoundException noSuchActivity) {
// handle exception where calculator intent filter is not registered
}
}
Related
i have this AccessibilityService class for the USSD
public class USSDService extends AccessibilityService {
public static String TAG = "USSDService";
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.d(TAG, "onAccessibilityEvent");
String text = event.getText().toString();
if (event.getClassName().equals("android.app.AlertDialog")) {
performGlobalAction(GLOBAL_ACTION_BACK);
Log.d(TAG, text);
Intent intent = new Intent("com.times.ussd.action.REFRESH");
intent.putExtra("message", text);//this is the value that i want to return to MainActivity
Toast.makeText (this,text,Toast.LENGTH_LONG).show();
}
}
#Override
public void onInterrupt() {
}
#Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.d(TAG, "onServiceConnected");
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.flags = AccessibilityServiceInfo.DEFAULT;
info.packageNames = new String[]{"com.android.phone"};
info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
setServiceInfo(info);
}}
and i invoke in main activity like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////////////////USSD////////////////////
Intent mIntent = new Intent(this, USSDService.class);
startService(mIntent);
}
and this is a function that dial ussd
private void dailNumber(String code) {
String ussdCode = "*" + code + Uri.encode("#");
Intent callIntent = new Intent(Intent.ACTION_CALL)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callIntent.setData(Uri.parse("tel:" + ussdCode));
callIntent.putExtra("simSlot", 0);
startActivity(callIntent);
}
when i call this function by clicking a button, every thing is ok and the response of ussd call show in Toast as i code it in function onAccessibilityEvent
what i want is return the response value to MainActivity
Accessibility services cannot be started in the manner you are attempting to start them. They can only be managed from the Accessibility Settings menu. This is for good reason. Accessibility services can read screen contents. OH, you downloaded my app, that's nice. NOW I'm going to launch an Accessibility Service that watches all of your screen content for things that look like Credit Card numbers.
Intent mIntent = new Intent(this, USSDService.class);
startService(mIntent);
The lines of code above ARE NOT accomplishing what you think they are. The accessibility service will launch (call your service's onCreate), but it will launch in a functionally limited state that does not allow it to bind to applications and the Android Operating System in the way an Accessibility Service normally would.
Once properly configured, go to Settings -> Accessibility and find your service listed next to TalkBack. Then turn it on. Once you do this, in order to communicate between your two processes you're going to need some type of interprocess communication mechanism. For simple communication you can consider using SharePreferences. Otherwise, you're probably going to have to look into BroadCastReceivers.
See how far that gets you, and ask another question if you need!
Below is the code which I'm using to return a number which should be 1 when the button is clicked. However when I try to get that number from another class, it always stays 0.
As you might recognize, I tried to change the number in the onClickListener and returned it below.
I also tried to use the onPause command so that it will return the number onPause but it still doesn't work.
public class MainActivity extends Activity {
public int number;
Button btnAngled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
btnAngled = (Button) findViewById(R.id.btnAngled);
final Intent intent = new Intent(this, angledForeheadActivity.class);
btnAngled.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
number = 1;
startActivity(intent);
}
});
}
#Override
protected void onPause() {
super.onPause();
}
public int getNumber() {
return number;
}
}
I try to get the code in another class with:
MainActivity a = new MainActivity();
int number = a.getNumber();
Sorry for the noob question..
declare the variable as static variable. Then you can simply obtain the result you want since there is only one copy of that variable. If you want to pass the value using intent, you can call putExtra() of intent to carry information to another activity.
Intent reference page
What you actually want is getting the number from another Class. Don't mix the job with button click together. You should setup the concept of model to store data and seperate UI and data, UI just change/get the data.
I suggest you either of the two ways
Store the number in some global model, then you can get the number from another Class.
User Android Broadcast to transfer the data
Use static variable in Activity is not a good idea, it may cause memroy leak, though it can solve your problem.
I am a newbie to android development, trying to get buttons working. every time i use this code below, the error message "unfortunately the app has stopped". but when i remove the code the app runs but obviously the buttons do nothing. here is the code ive tried
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.ExerciseButton);
button1.setOnClickListener (new View.OnClickListener(){
public void onClick(View v) {
setContentView(R.layout.exercises);
}
});
}
}
anybody able to help me out there? thanks
Don't try to load another View in the current activity. Navigate to a new ExercisesActivity.
Use:
public void onClick(View v) {
Intent intent = new Intent(ExercisesActivity.this, WcActivity.class);
startActivity(intent);
}
You can't call setContentView anymore after the view has loaded (which it obviously has to receive button clicks). Use a different approach, like showing and hiding views or using a ViewFlipper (see Calling setContentView() multiple times), using fragments (see Fragments) or starting a new activity.
Well, from your code, I see a couple of things:
I am usually familiar to using the onClickListener of the Button class if I want to use it for a button. Makes sense, doesn't it?
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
}
Second thing:
Start a new Activity (if that is what you want) by using an Intent:
Intent myIntent = new Intent(this, exercises.class);
startActivity(myIntent);
You CAN absolutaly call setContentView on any event, even after the view has loaded
I tried your code in a demo project and it is working fine. So, i think the error will be some where in your layout.(Let me know more if you need more help on this)
I am a beginner in developing and I know the question may sounds very basic but, let me cut to the chase: here is my class
public class MainActivity extends Activity {
private ListView lvPhone;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvPhone = (ListView)findViewById(R.id.listPhone);
List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
"blah_blah", "384765345667", "something#someprovider.com"));
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
"blah_blah", "34856834796", "something#someprovider.com"));
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
"blah_name", "868734633", "something#someprovider.com"));
PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook);
lvPhone.setAdapter(adapter);
}
}
and here I'd like it to be "attached" so then when the button is clicked the phone book comes up.
public void addListenerOnButton(){
imageButton = (ImageButton) findViewById(R.id.pb_button);
imageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(MyAndroidAppActivity.this,//phone_book goes here
"ImageButton is clicked!", Toast.LENGTH_SHORT).show();//no toaster instead
}
});
}
Would any of you please help? This is going to be really helpful for me. And please if you do answer, try to explain as you're explaining to a "Java_moron" :) (as through as possible please)
[Now I did try the chat room, no reputation point so that didn't happen and I tried to google as much as possible couldn't find anything helpful; maybe there was answer but my lack of knowledge failed me.]
Thank you,
[EDIT: Or instead of using the phone book class, how can I call contacts from phone's native contact list? Anything would be helpful really.]
The best option to start would be to activate a native activity that will bring up phone book contacts and show them to the user as a list. Selected contacts is then passed to starting activity.
Explanation:
You can learn how to start an activity and receive result from the following link:
http://developer.android.com/training/basics/intents/result.html
Basically the main code do that is as follows:
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, new Uri("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
Note that the user will be calling the startActivityForResult method this will start a new activity and once that activity is finished the System will call onActivityResult() method of the original Activity and here you will receive results to which contacts has been selected.
I am new to Android and Java. I have constructed an app using HTML/Javascript that is working great.
I now need to create an activity that launches the email client, fills in subject and body, and (the tough part) adds a file attachment. I have not been able to do this from within JavaScript, mailto: will not attach the file.
So I need to accomplish this through Java and execute it from JavaScript. I think this can be done by using addJavaScriptInterface but I cannot find any detailed documentation or examples to go off of.
How could I do this?
Here is what I have so far after reading the documentation:
2nd update to code:
MainActivity.java
public class MainActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty( "splashscreen", R.drawable.splash );
super.loadUrl("file:///android_asset/www/index.html", 1000);
WebView mWebView;
mWebView = (WebView)findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
}
}
JavaScriptInterface.java
public class JavaScriptInterface {
public void doEmail(){
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/html");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT,"test text");
sendIntent.putExtra(Intent.EXTRA_SUBJECT,"test subject");
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://test co.html"));
startActivity(Intent.createChooser(sendIntent, "Send email..."));
}
}
Then I would reference the intent through JavaScript by using Android.doEmail().
With the above code I am getting 2 errors in Eclipse
1. The method startActivity(Intent) is undefined for the type - JavaScriptInterface
2. webview cannot be resolved or is not a field - MainActivity
What am I doing wrong?
This documentation tells you exactly how to do it.
It looks like there are three main steps:
Create your 'interface' class in Android
Add an instance of this 'interface' to the WebView you are using.
Call the interface from your JavaScript.
public class MainActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty( "splashscreen", R.drawable.splash );
JavaScriptInterface jsi = new JavaScriptInterface(this, appView);
appView.addJavascriptInterface(jsi, "Android");
super.loadUrl("file:///android_asset/www/index.html", 1000);
}
}
and
public class JavaScriptInterface {
private WebView mAppView;
private DroidGap mGap
public JavaScriptInterface (DroidGap gap, WebView view)
{
mAppView = view;
mGap = gap;
}
public void doEmail(){
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/html");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT,"test text");
sendIntent.putExtra(Intent.EXTRA_SUBJECT,"test subject");
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://test co.html"));
startActivity(Intent.createChooser(sendIntent, "Send email..."));
}
}
Using addJavaScriptInterface will extend the DOM inside the embedded browser, and allow JS to access a Java object, which is exactly what you want.
There are too many steps to outline here, that have already been documented. This link has a good overview.
I used WebIntents from Boris Smus (http://smus.com/android-phonegap-plugins) and it works like a charm. You can also peruse his code a little to understand better the approach he took with plugins.
NOTE: you do need to update the code provided as is a little (see comments) and the plugin architecture has changed a little.