Connection between Activity and Service - java

I have an Activity with an EditText and some checkboxes. After the user inserts a text the text should be sent to the Service and the Service will run in background showing a Toast from time to time.
I am having a really hard time trying to figure out how to send the data(Strings and Boolean values that user inputs through the Activity) to the Service .

Use Intent on Activity put values in puExtra
Intent intent = new Intent(current.this, YourClass.class);
intent.putextra("keyName","value");
and then call StartService so the OnStart method call be called..
in service get the values in OnStart by using intent
Bundle extras = getIntent().getExtras();
if (extras != null)
{
String value = extras.getString("key");
}

Have you taken a look at the Android Documentation For Services?
It explains everything you need to know and more :)
(hint: you must pass an Intent to OnStartCommand())
If you google "pass an intent to a service in android" among the first results you'll find:
Pass data from Activity to Service using an Intent

Related

Which is considered better to pass information between Activities on Android project, send a model or only an id?

I have an android app and I have 3 screens that the user must fill some fields. Each screen have 7 fields to be filled. At the end of the process, I submit the information to the server using Retrofit with an API.
This is how I pass the information between Activities in my first project
// first activity
AutoDados autuacaoDados = new AutoDados(... a lot of parameters ...);
Intent intent1 = new Intent(AutoInf_Lista_Generica.this, AutoInf_Menu.class);
intent1.putExtra("PARAM_ENV_DADOS", autuacaoDados);
startActivity(intent1);
// second activity
Bundle extras = intent.getExtras();
if (extras == null) {
return "";
}
AutoDados autuacaoDados = (AutoDados) extras.getSerializable("PARAM_ENV_DADOS");
I have another project that I use the following code to pass data between activities.
// first activity
Intent intent1 = new Intent(AutoInf_Lista_Generica.this, AutoInf_Menu.class);
intent1.putExtra("ID_AUTOS", myId);
startActivity(intent1);
// second activity
intent.getIntExtra("ID_AUTOS", 0);
// code that recover the data from a SQLite database based in the "ID_AUTOS"
These both ways I was able to recover data between activities, but which way is considered better and why is it better?
Another question, is there a better way to pass data between activities ?
If possible, talk about the pros and cons about each approach.
The main difference between the tow ways is that in the first method you are passing an Object to the second activity while in the second method you are passing a primitive type.
which is better ? each way has its own use case, there is no better way, it depends on your use case

how can forward data form i activity to 3 activity via 2 activity

I am making my own project but I am stuck.
Getting the information from the user in the first activity is working just fine.
But when I try to get those numbers, ints, in the third activity via a second activity, it is showing me the default value.
I am trying it using an Intent, but it is not working.
Intent intent = new Intent(this, active.class);
Intent intent2 = new Intent(this, BMR_Active.class);
intent.putExtra(EXTRA_TEXT_height,height );
intent.putExtra(EXTRA_TEXT_weight,weight);
intent.putExtra(EXTRA_TEXT_age,age);
startActivity(intent);
It is giving me a default value i.e. 0(I have given) in BMR activity then i am going via active activity.
Your putExtra method via intent would work fine, but are you also running putExtra BEFORE starting the third activiy?
The data is first passed from first activity to second activity, then from second activity is passed to third activity using the same method.
Additional Note:
In cases like this, I would usually use fragments instead, I would store the data in the activity and fragments will obtain the datas via getActivity(). This will eliminate the needs of multiple passing of data around.
Based on what you said in your comment about passing data straight from Activity 1 to Activity 3, then what you can do is the following:
Page1.class:
Intent toPage3 = new Intent(Page1.this, Page3.class);
int myNum = 5;
toPage3.putExtra("Number", myNum);
startActivity(toPage3);
Page3.class:
Intent receiveIntent = getIntent();
int numFromPage1 = receiveIntent.getIntExtra("Number");
I believe that this should answer your question. numFromPage1 will be an int containing the value from Page1.

How to detect if my app is called by another

I have two entrnces to my app: from menu and using Intent.
In the second case I need to return some EXTRA_OUTPUT by
setResult(Activity.RESULT_OK, myIntentWithData)
finish()
so I need to detect if my app was called by another(finish in that case or continue work otherwise)
If your activity was called using startActivityForResult(), you can use getCallingActivity() method in your Activity. It will return a ComponentName of the activity that started yours (or null if your activity wasn't started with startActivityForResult() method). Then you can get getCallingActivity().getPackageName() or getCallingActivity().getClassName().
More info here getCallingActivity, https://stackoverflow.com/a/5336612/3569545
Use getIntent() method to get the intent that was the reason to start your activity.
Then if it was launched from the apps menu the intent will have action MAIN.
val intent = getIntent();
if (intent.getAction() != "android.intent.action.MAIN") {
setResult(Activity.RESULT_OK, myIntentWithData)
finish()
}

android remove data from getintent

I have an activity for handling deeplink which is a browsable activity
suppose user clicks a link on another app and my browsable activity handles that intent
and start the app, , then user minimise the app by pressing back button
class code for handling intent data
Uri link = getIntent().getData();
if user reopen app from running tasks getIntent() still have data
onDestroy method of browsable activity
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
setIntent(null);
}
setIntent(null) not working
so my question is how can i remove data from intent permanently
I am a little late on the answer here but I was dealing with a similar issue and found a solution. The reason you are still seeing data in the intent is because your app was originally started with an intent that contained data. That original intent is stored somewhere in Androids' ActivityManager and is immutable, to my understanding. When user reopens the app from "recent tasks", Android uses that original intent to recreate the application.
There is a workaround to this, however. In your apps onCreate() method, you can check to see if the Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY is set, which would allow your app to distinguish if it is being started from "recent tasks" or not, and therefore, you can avoid using the data contained in the intent.
Putting the following snippet in your onCreate() method would return true if the app is being opened from "recent tasks"
(getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0)
you have to remove data one by one key. i think you can't remove all data with one line.
if you want to remove specific key than you should use ==> getIntent().removeExtra("key"); or
getIntent().setAction("");
it will remove your data.
for more ==> Clearing intent
To remove the content it works best for me with the following lines of code.
//Clear DATA intent
intent.setData(null);
intent.replaceExtras(new Bundle());
intent.setFlags(0);
After that they can verify that the intent does not contain data

Intent putExtra(String,String) inside of AsyncTask

I'm simply trying to carry a string onto the next activity without having to define an entire object for the task. I've seen similar solutions and gotten them to work BUT without using AsyncTask to create the intent.
protected void onPostExecute(Boolean result) {
if (loggedIn && hasPin) {
Intent intent = new Intent(UniteActivity.this,
WebViewActivity.class);
intent.putExtra(PASSED_USERNAME, passUser);
startActivity(intent);
}
if (loggedIn && !hasPin) {
Intent intent = new Intent(UniteActivity.this,
CreatePinActivity.class);
intent.putExtra(PASSED_USERNAME, passUser);
startActivity(intent);
PASSED_USERNAME is a public static constant to hold the package name, just as the putExtra() method requires. I then try to pull the value out in the next activity.
Intent extras = getIntent();
String username = extras.getStringExtra(UniteActivity.PASSED_USERNAME);
// carry username to next activity
Intent intent = new Intent(CreatePinActivity.this,WebViewActivity.class);
intent.putExtra(PASSED_USERNAME, username);
startActivity(intent);
There is never a String to pull out, the value of username is always null. I've gone through the debugger and found that the Eclipse IDE debugger shows different intent ID's between the activities, they are never consistant. Is it possible that AsyncTask is interfereing somehow because it splits into a seperate thread?
I don't know if this applies to your problem, because I can't see from your code snippet if the intermediary activity is freshly created or not.
BUT: the getIntent()-method always returns the first Intent that started the activity. If the activity remains in the background and receives a new Intent this value does not get updated automatically. You have to override onNewIntent(...) and manually call setIntent(...) for this to work (or do all your stuff directly there).
So just for the case that you do not run your posted code in the onCreate() method please check if you did not miss to fetch the real intent you are interested in.
Not sure of the exact answer for you solution.
You calling startActivity on the UI since it's in postExecute().
If all else fails you can just save that value to a sharedpreference.
The way you have handled the variable PASSED_USERNAME seems incorrect. You have used it in some palaces as simple PASSED_USERNAME whereas in some other places you have used it with the class named prefixed UniteActivity.PASSED_USERNAME. Since it is a Public Static Constant always use it prefixed with the class name.

Categories

Resources