Show toast soon as activity is visible - android

I'm trying to show a toast whenever the activity is visible to user but the message is not displaying at all.
I've the activity X which at certain point calls:
Intent t = new Intent(this, MainActivity.class);
t.putExtra( "toast", getString(R.string.subscribingInBackground));
t.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(t);
finish();
And at MainActivity besides lots of other stuff I've:
#Override
public void onResume() {
super.onResume();
if (this.adView != null) {
this.adView.resume();
}
String toast = getIntent().getStringExtra("toast");
if (toast != null)
Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
}
but toast is always null
what am i doing wrong?

Your FLAG_REORDER_TO_FRONT suggests that you believe that the activity already exists. If so, that activity will be called with onNewIntent(), and the Intent delivered to onNewIntent() will have your extra. getIntent() returns the Intent that was used to create the activity initially.

use this code
package com.example.abc.introscreen;
import android.content.Intent;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent t = new Intent(this,MainActivity.class);
t.putExtra( "toast", "Hello");
startActivity(t);
}
#Override
public void onResume() {
String toast = getIntent().getStringExtra("toast");
if (toast != null)
Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
super.onResume();
}
}
enter code here

You can override onNewIntent() to get the Intent which you used in ActivityX to start MainActivity.
Quoting from the documentation on Activity
Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.
So you can override onNewIntent() as follows:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
Then your Toast will be displayed.

Related

Button doesn't work on a new thread

Previously I had error - something about some loop, I've seen info that it is necessary in that case to start a new thread for button, but still nothing happens, thought logs show no errors now.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int CAPTURE = 9003;
Button button;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.capture);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, "BUTTON clicked", Toast.LENGTH_LONG).show();
Log.d("BUTTON","CLICKED");
}
});
}
});
Intent intent = new Intent(this, CaptureActivity.class);
intent.putExtra(CaptureActivity.AutoFocus, true);
startActivityForResult(intent, CAPTURE);
}
}
runOnUiThread mean you are telling the UI thread to execute the passed Runnable as instruction so it won't create a new thread.
Solution : I assume you this code is for demo purpose for threading and UI updation so one of best alternative is to AsyncTask
and remove runOnUiThread function , no need of it
You need to remove this code or move it inside run method
Intent intent = new Intent(this, CaptureActivity.class);
intent.putExtra(CaptureActivity.AutoFocus, true);
startActivityForResult(intent, CAPTURE);
Because you are currently in CaptureActivity not on MainActivity.
OnCreate will directly take you to the CaptureActivity where you are expecting the code of MainActivity to run (probably they have same UI)

Bring the another App in the front when receiving the broadcast

I am sending a broadcast from App A to App B and I am already receiving it in app B. After receiving the broadcast I want to bring the App B to the front. How can I bring the App B to the front after receiving the broadcast from the App A?
package com.mysender;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Intent intent=new Intent();
intent.setAction("com.mysender.Data");
intent.putExtra("path", "/Download/income_tax_return.pdf");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
}
}
In the App B I am doing the following in the MainActivity:
package com.example.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Receive broad Cast fromn External App
IntentFilter filter = new IntentFilter("com.mysender.Data");
registerReceiver(myReceiver, filter);
}
private MyReceiver myReceiver =new MyReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String path = intent.getStringExtra("path");
Toast.makeText(context,"Data Received from External App: " + path, Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
}
}

Android - changing textview from other activity

I'm quite new to programming.
I'm trying to make a simple app with two activities, where the second activity can change the text of the first. I know it can be done using intents, but I was wondering if there is a more direct way of doing it, for example using the second activity to call a function from the first activity?
Here's the code I have so far:
The MainActivity, which contains a TextView and a button to open the second activity:
public class MainActivity extends Activity {
TextView textview;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.et2);
button = (Button) findViewById(R.id.b1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, ChangeText.class);
startActivity(intent);
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
public void changetext(String message) {
textview.setText(message);
}
}
And the second activity, ChangeText, which contains an EditText and a button which should change the text of the TextView in MainActivity and then finish itself:
public class ChangeText extends Activity{
EditText edittext;
Button button;
private MainActivity mainclass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.change_text);
edittext = (EditText)findViewById(R.id.et2);
button = (Button)findViewById(R.id.b2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String message = edittext.getText().toString();
mainclass.changetext(message);
finish();
}
});
}
}
As you can see I tried to make the app work by making a public function in MainActivity which receives a string and sets the TextView with it, and then I call this function from the ChangeText activity.
The problem: it keeps crashing! Can anyone tell me how I can make this work?
Seems like I answered almost exactly the same question a week or so ago, so this is probably a duplicate, but I can't seem to find the original question.
The short answer is no - you can't call a method in an Activity from another Activity. The issue is that for normal programming purposes, only one Activity exists at a time*.
If you do something to circumvent this, then you're risking causing some major issues, including high memory usage, null pointer exceptions, etc.
The correct way to do this is indeed through the Intent system.
* Activities may or may not actually get destroyed when they become inactive, depending on things like how you use the back stack.
However, you should always program is if they do get destroyed when they become inactive - read, understand, and respect the Activity lifecycle.
For something as simple as your app, the "most direct" approach is to use the intent and startActivityForResult and them implement an onActivityResult in your main activity.
The problem you'll run into, even if you correctly pass you Activity references around is they are not guaranteed to be running at the same time.
Other ways aside from Intents, is to use a class(s) not involved with the Activity. Either a background service or a static variable in a class that extends Application. I rarely use Application classes anymore in favor of services and binding Activities them.
If I use an EventBus in projects, they can send Sticky events, which will hold the data until cleared.
Android uses a messaging mechanism to communicate between its components. This messaging mechnism is essential to Android, so you should use it. And as you already said, the messaging is implemented by Intents. ;-)
If you want something more complex, use an EventBus or implement a your own subscribe/publish mechanism that does what you want.
Use static variable
Example
In your MainActivity define
public static String msg = null;
then in your ChangeText activity assign changed text to it like
MainActivity.msg = edittext.getText().toString();
now in your main activity override the onResume() methode
if(msg != null){
textview.setText(msg);
msg = null;
}
You must LocalBroadCast Manager to do so
Here is the MainActivity which has the TextView which has to updated by another Activity
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.txt1);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String s1= intent.getStringExtra("myString");
getIt(s1);
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
public void getIt(String s)
{
System.out.println(s);
txt.setText(s);
}
public void go(View view)
{
Intent intent = new Intent(this,WriteText.class);
startActivity(intent);
}
}
And This is the Activity which contains the EditText which updates the TextView in the previous activity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class WriteText extends Activity {
EditText ed1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_text);
ed1 = (EditText)findViewById(R.id.textView);
}
public void come(View view){
Intent intent = new Intent("custom-event-name");
intent.putExtra("myString", ed1.getText().toString());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
This Worked for me , Hope it works for you too

startActivityForResult can't work well when setResult is placed in onPause(), onStop() or onDestroy()

When I put setResult() in the onClickListener of a button, that works. However, if I put it in onPause(), onStop() or onDestroy(), that never works.
I got really confused about that.
Here is the code of MainActivity.
package com.example.hellotest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(getApplicationContext(), SecondActivity.class), 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "hello world", Toast.LENGTH_SHORT).show();
Log.d(TAG, "RESULT_OK");
} else {
Toast.makeText(getApplicationContext(), "result not ok", Toast.LENGTH_SHORT).show();
Log.d(TAG, "RESULT_CANCELED");
}
}
}
Here is the SecondActivity.
package com.example.hellotest;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SecondActivity extends Activity {
private static final String TAG = SecondActivity.class.getSimpleName();
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// setResult(RESULT_OK);
Log.d(TAG, "button on click");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
protected void onDestroy() {
setResult(RESULT_OK);
Log.d(TAG, "onDestroy");
super.onDestroy();
}
#Override
protected void onPause() {
// setResult(RESULT_OK);
Log.d(TAG, "onPause");
super.onPause();
}
#Override
protected void onStop() {
// setResult(RESULT_OK);
Log.d(TAG, "onStop");
super.onStop();
}
}
And here is the Log of which I put setResult() in the onClick()
11-21 00:07:54.243: D/SecondActivity(4790): button on click
11-21 00:07:56.364: D/SecondActivity(4790): onPause
11-21 00:07:57.813: D/SecondActivity(4790): onStop
11-21 00:07:57.813: D/SecondActivity(4790): onDestroy
11-21 00:07:56.404: D/MainActivity(4790): RESULT_OK
But if in onDestroy()
11-21 00:10:08.125: D/SecondActivity(4846): onPause
11-21 00:10:09.456: D/SecondActivity(4846): onStop
11-21 00:10:09.456: D/SecondActivity(4846): onDestroy
11-21 00:10:08.176: D/MainActivity(4846): RESULT_CANCELED
I have no idea about that.
You can also override finish() and set the result before calling into the super class:
#Override
public void finish() {
setResult(...);
super.finish();
}
Call setResult() when the user performs the operation that selects the result. onPause() or later lifecycle events are too late.
startActivityForResult() is designed for "picker" sorts of activities, where the user is picking something. The typical pattern is for you to call setResult() and finish() once the user has picked their item.

Android - Starting a service with extra information through put/getExtra

I've really tried to get through the intent.putExtra() and getIntent().getExtras() and apply them to one of the SimpleService tutorials. I know a lot of people have already asked "why is bundle extras always null?" I promise I tried to hack through the answers I found here for several hours before I considered posting but I don't think I'm advanced enough to really understand what it is I must be doing wrong with the minor snippets people are posting. As such I put in the full code of my activity and my service.
I think my issue is the that my starting intent (the one I create in my activity) doesn't exist in the context of my service. I wonder if maybe I'm using Intents in the wrong direction/purpose entirely? I did try an intent.putExtra in my service, to try to send a string the other direction, but those extras are always null, too. So at the risk of repetition, why is bundle extras always null? How do I make a single intent that exists both in the context of my activity and my service?
I should note that the code as displayed below obviously will have a null extras because I've commented out a few of my attempts to .getExtras() that have failed. I deleted the rest for the sake of cleanliness.
EDIT: The answer thanks to the replies, in code for the sake of those who have also been Googling for hours. Put this in your service (please note that the return START_REDELIVER_INTENT may be wrong):
#Override
public int onStartCommand( Intent intent , int flags , int startId )
{
super.onStartCommand(intent, flags , startId);
extras = intent.getExtras();
//just checking
if( extras != null )
Toast.makeText(this,extras.getString("extratoservice"), Toast.LENGTH_SHORT).show();
return START_REDELIVER_INTENT;
}
My activity (based on Sai Geetha's blog):
package com.example.BroadcastIntent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class BroadcastIntentActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button)findViewById(R.id.buttonStart);
start.setOnClickListener(startListener);
Button stop = (Button)findViewById(R.id.buttonStop);
stop.setOnClickListener(stopListener);
//the intent I'm using to start and stop the service -- the extras don't go anywhere....
intent = new Intent(BroadcastIntentActivity.this,BroadcastService.class);
intent.putExtra("extratoservice", "if you can read this, it made it to the service" );
}
Boolean serviceRunning;
Intent intent;
//Clicks from Geetha's Blog
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v){
startService(intent);
serviceRunning = true;
}
};
private OnClickListener stopListener = new OnClickListener() {
public void onClick(View v){
try
{
stopService(intent);
serviceRunning = false;
}
catch( Exception e)
{
Toast.makeText(getApplicationContext(), "Service was not running...",Toast.LENGTH_SHORT).show();
}
}
};
}
And this is my service:
package com.example.BroadcastIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class BroadcastService extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
//extras = arg0.getExtras(); <-- this has null extras, too...
return null;
}
Bundle extras;
#Override
public void onCreate() {
super.onCreate();
// extras = getIntent().getExtras(); <-- this is undefined?
if( extras == null )
Toast.makeText(this,"Service created... extras still null", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this,extras.getString("extratoservice"), Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_SHORT).show();
}
}
you need to look at the onStartCommand() function (I'm not at a desktop so I can't conveniently link to the javadoc). This will receive the intent you passed and your extras should be available there.
I think you need to do this in your service..
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
to get the intent you're passing in... but I'm not 100% on this, so double check
http://developer.android.com/reference/android/app/Service.html

Categories

Resources