Android - New Intent starts particular method - java

I want to start one of my existing activities and force the activity to call a specific method after it starts. Is this possible?
Can I define a method that should be called after creating the activity inside my Intent?
For example, something like:
Intent intent = new Intent(this, com.app.max.Home.class.myMethod);

No, I don't think you can have something like this:
Intent intent = new Intent(this, com.app.max.Home.class.method);
but you can do this:
Intent intent = new Intent(this, com.app.max.Home.class);
intent.putExtra("methodName","myMethod");
startActivity(intent);
and then in the called activity (where you need to start the method), you can take the intent and decide which method to call like this:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if(intent.getStringExtra("methodName").equals("myMethod")){
mymethod();
}
}

Hello You can't call a particular method from intent but alternately you can use a service from intent and your requirement will be done.
Intent intent = new Intent(this, MyService.class);
and in MyService.class
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
yourParticularMethod(); //do your task and stop the service when your task is done for battery saving purpose
context.stopService(new Intent(context, MyService.class));
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and register this service in your manifest file like this
<application>
<service android:name=".MyService" />
.
.
</application>

I solve this issue by using onCreate instead of onNewIntent.
Activity A:
Intent intent = new Intent(this, com.app.max.Home.class);
intent.putExtra("methodName","myMethod");
startActivity(intent);
com.app.max.Home Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
if(savedInstanceState == null)
{
Bundle extras = getIntent().getExtras();
if (extras == null)
{
//Extra bundle is null
}else{
String method = extras.getString("methodName");
if (method.equals("myMethod"))
{
//Call method here!
}
}
}
Hope this solution solve your problem

You question seems interesting, but there is no way you can do it using Intent. You have to understand that when you start an activity, it goes through a life cycle which is : onCreate()->onStart()->OnResume(). So what you can do is start that method from onResume() like this:
#Override
protected void onResume() {
super.onResume();
myMethod();//start your method from here
}
I'm just trying to help,give me some more information about your problem if this approach does not solve your problem.

Related

ActivityNotFoundException: No Activity found to handle Intent { (has extras) }

I have an activity, let's call it MainActivity which has an SomeAdapter.
In the adapter's code I have
#Override
public void onBindViewHolder(#NonNull OptionViewHolder holder, final int position) {
final Option o = values.get(position);
holder.textView.setText(o.getOption());
holder.foreGround.setBackgroundColor(o.getOptionLayout().getBackGroundColor());
holder.editOptionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("option",o);
context.startActivityForResult(intent,1);
}
});
}
When actually clicking the editOptionButton, I get the following stack trace
Process: com.company.app, PID: 20916
android.content.ActivityNotFoundException: No Activity found to handle Intent { (has extras) }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2007)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at com.company.app.adapters.OptionsAdapter$1.onClick(OptionsAdapter.java:86)
the context that calls startActivityForResult is the MainActivity and is not null and alive (visible) at the time of calling because the adapter runs in it.
Therefor, I have no idea why this error pops up nor what I could do about it. Do any of you may know why or have experienced it before?
You have to include the Activity name like this
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra("option",o);
context.startActivityForResult(intent,1);
First
you are initlizing the intent in wrong way, you need init it as below:
Intent intent = new Intent(context, SecondActivity.class);
Second
If the result do not return to your MainActivity then you need to cast the context to activity before starting the second activity as:
((Activity) context).startActivityForResult(intent,1);
This means that intent doesn't know where to go. So give the context and the activity name where u want to go.
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra("Key",value);
startActvity(intent);

How to destroy/kill a service?

I have my application running a service for shake detect, however in my MainActivity, I have button for log out user, in which I must log out and terminate the service that detects the shake event.
my method for log out in my MainActivity is:
public void signOutAndFinish(){
//Stop Shakeservice
Intent intent = new Intent(this, ShakeService.class);
stopService(intent);
//Go to login activity
Intent iLoginView = new Intent(this, LoginActivity.class);
startActivity(iLoginView);
}
however if I shake my device after logging out, the service recognizes the shake, it is as if it will not kill it immediately:
Intent intent = new Intent(this, ShakeService.class);
stopService(intent);
The code in the method onDestroy is:
#Override
public void onDestroy() {
super.onDestroy();
}
How can I terminate the service so that when I log out the service dies?
Thanks for your help!
You can send a broadcast back your activity in the onDestroy() method of your service and then do the logout.
Here is some sample code of the above idea:
This for your service:
#Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_NOTIFICATION");
intent.putExtra("data","Notice for logout!");
sendBroadcast(intent);
}
And this is for your activity:
private BroadcastReceiver br = new MyBroadcastReceiver();
#Override
public void onCreate() {
IntentFilter filter = new IntentFilter("com.example.broadcast.MY_NOTIFICATION");
registerReceiver(br, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(br);
}
// An inner class at your activity
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
YourActivity.this.finish();
// or do anything you require to finish the logout...
}
}
however if I shake my device after logging out, the service recognizes the shake
Then presumably you did not clean up your Sensor stuff in the service's onDestroy() method.
How can I terminate the service so that when I log out the service dies?
You are doing that now. However, if you set up something in the service, such as listening to events from SensorManager, you need to clean that up, typically in onDestroy() of the service.

Value of Toast to TextView of second activity

This is my MainActivity.java and I want the results in a text view of another activity? How can I achieve it? Can you Show me with an example please.
public class MainActivity extends AppCompatActivity {
private Button scan_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scan_btn=(Button)findViewById(R.id.btnQr);
final Activity activity =this;
scan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator intentIntegrator = new IntentIntegrator(activity);
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
intentIntegrator.setPrompt("Scan");
intentIntegrator.setCameraId(0);
intentIntegrator.setBeepEnabled(false);
intentIntegrator.setBarcodeImageEnabled(false);
intentIntegrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null){
if (result.getContents()==null){
Toast.makeText(this,"You cancelled scanning",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this,result.getContents(),Toast.LENGTH_LONG).show();
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
This is my Second Activity. Where I want to show the result.
public class DetailActivity extends AppCompatActivity {
private TextView qrResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
qrResult= findViewById(R.id.qrResult);
}
}
If you want I can post my Layout file as well. Thankyou.
You need to create a new Intent object, and add it extra data with intent.putextra(). This method can take a String object as an argument. You need to specify a unique key for that string.Then start the new activity. For example
Intent i = new Intent(context, nextactivity.class)
i.putextra(“stringKey”,yourSstring)
startActivity(i)
Then, in the second activity, you need to get the intent that started that activity (with getIntent), you can use it as early as onCreate.
The getIntent function returns the intent object that started the new activity.
When you have the new intent, you can get the extra string you passed from the old activity, with intent.getStringExtra(“stringKey”)
This allows you to pass simple data between activities. Make sure to use the same key.
You can put data into the intent from your main acivity and the get the intend from the second activity for the data.
For example:
In your MainActivity.class
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("result", "Your result text here");
startActivity(intent);
In Your DetailsActivity.class:
Intent intent = getIntent();
String result = intent.getStringExtra("result");
qrResult.setText(result);
You can even send any type of object through intent. Please google it for further information.

Switch Screens in Android not working

I have a "Play Now" button for a simple android game. When I click the button it calls start, but it doesn't do anything.
Here is start():
public void start(View view) {
Intent myIntent = new Intent(this, Game.class);
startActivity(myIntent);
}
and Game.java:
public class Game extends MainActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
}
Also, I didn't forget to put it into the manifest
<activity android:name=".Game"></activity>
I'm new to android and this is all very confusing. I tried putting an intent filter although I probably did it wrong.
I looked at this How to switch between screens? but it didn't work for me.
You are finishing the activity just when you create it (onCreate). Try deleting or commenting finish(); and good luck!
remove following lines, we use them with startActivityForResult , after removing it should work other than this everything is fine
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
Actually,your start function is working fine.But the problem is with onCreate() method in Game activity.You are calling finish() method in this which is killing the activity.Get rid of this method and then check.One thing more,I don't understand what is the purpose of setResult in your context.It is actually used for startActivityForResult() method.Refer to this link for further information:
https://developer.android.com/training/basics/intents/result.html
public class Game extends MainActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
//Intent intent = new Intent();
//setResult(RESULT_OK, intent);
//finish();
}
}

Android: How do I call an activity when service is destroyed (onDestroy)?

Does anyone know how to call an activity when a service is destroyed? I have tried with the code below, but it doesn't work and geves me a force close.
#Override
public void onDestroy() {
Intent goToAbout = new Intent(this, AboutForm.class);
startActivity(goToAbout);
}
Anyone have an idea?
public void onDestroy(){
Intent myIntent = new Intent(this,
MyACtivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(myIntent);
}

Categories

Resources