I have an Activity class.
public class A extends Activity
{
}
Then I have a class that is not an Activity but I want it to start the Activity A.
public class B
{
public B()
{
Intent I = new Intent(null, A.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
The code is take from this question which should work: Calling startActivity() from outside of an Activity?
However, when I run it I never change from my first activity to activity A. What am I doing wrong? Should I be listening to the FLAG_ACTIVITY_NEW_TASK inside A?
Something like this should work:
public class B {
Context context;
public B(Context context) {
this.context = context;
}
public void startNewActivity(String str) {
try {
Intent i = new Intent(context, Class.forName(str));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Use case of class B:
B b = new B(A.this);
b.startNewActivity("MainActivity");//the "MainActivity" is the className of the java class
Note I find this way wierd and a overkill.
Related
public class QRProductActivityPageObject {
public static void testProductDetail() throws InterruptedException {
ActivityTestRule<ProductInfoActivity> rule = new ActivityTestRule<ProductInfoActivity>(ProductInfoActivity.class, true, false);
Intent intent = new Intent();
intent.setClass(getActivity(), ProductInfoActivity.class);
rule.launchActivity(intent);
Thread.sleep(2000);
}
}
The above syntax show error that you cant access getActivity() in static method .
But i want to call this new Activity(ProductInfoActivity) through static method only.Any suggestion??
Pass context when method call in Activity or fragment and get Activity from context in static method
public static void testProductDetail(Context context) throws InterruptedException {
ActivityTestRule<ProductInfoActivity> rule = new ActivityTestRule<ProductInfoActivity>(ProductInfoActivity.class, true, false);
Intent intent = new Intent();
Activity activity = (Activity) context;
intent.setClass(activity , ProductInfoActivity.class);
rule.launchActivity(intent);
Thread.sleep(2000);
}
Call static method In activity
testProductDetail(getApplicationContext());
In fragment
testProductDetail(getActivity().getApplicationContext());
Or use the solution I found around here a few weeks ago, it's pretty awesome and elegant. You'd be able to use it anywhere in your APP!
Create a class MyApplication (you could name it differently):
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Go to your app Manifest file and add to the <application... tag the android:name attribute with the value of the name of the class we created:
<application
android:allowBackup="true"
android:icon="#drawable/appico"
android:label="#string/app_name"
android:name="MyApplication"
Now you can get the context for your app from any class like that
MyApplication.getAppContext();
You don't need to call getActivity(). Instead of using setClass() method which requires you to give a context object, you can use setClassName(String packageName, String className) method. Try this:
Intent intent = new Intent();
intent.setClassName("package.name.of.your.app",
ProductInfoActivity.class.getName());
There are two Activities..
1. Open SecondActivity from MainActivity
2. When event comes into MainActivity, call testMethod of SecondActivity
But how to do call this testMethod?
public class MainActivity extends Activity implements someListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Launch SecondActivity here!!
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, ID_PlayerActivity);
}
//trigger by JNI, it's in the other thread, not main thread.
void onEventCome() {
//How to call testMethod() in SecondActivity?
}
}
public class SecondActivity extends Activity {
void testMethod() {
//execute something...
}
}
If you open the SecondActivity, your MainActivity becomes inactive. I don't believe it is a good idea to call some activity method from other inactive/stopped activity.
I suggest to use observer pattern. Create a global long-lived object like EventProducer and register all activities as observer. So your EventProducer can inform all Activities about new event.
Example:
public class SecondActivity extends Activity implements MyEventListener {
#Override
public void onResume(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventProducer.instance().register(this);
}
#Override
public void onPause(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventProducer.instance().unregister(this);
}
void testMethod(){
//just doit
}
#Override
void onMyEventCome() {
testMethod();
}
}
First you need an event aware listener that will capture such an event happening. Your class seems ill equipped to do so.
Since you have a valid question, here goes:
void onEventCome() {
SecondActivity secondActivity = new SecondActivity();
secondActivity.testMethod();
}
There are many ways.
For eg:
Create the method as static and use class name and call it.
public static void onEventCome() {
}
In MainActivity:
MainActivity.onEventCome();
This is one method. Another method is create an object for MainActivity.
public void onEventCome() {
}
MainActivity main;
main = new MainActivity();
main.onEventCome();
You don't have a content view for your second activity. If you don't need to see the operation happen, you could remove your
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, ID_PlayerActivity);
remove extends Activity in SecondActivity and add a constructor public SecondActivity(Context context) and invoke the test method from your first activity like #Dragan example:
void onEventCome() {
SecondActivity secondActivity = new SecondActivity(MainActivity.this);
secondActivity.testMethod();
}
I have a menu and 5 activities. To avoid repeating the menu code, I have created a public class and call it in every activity:
Testclass testclass = new Testclass(Main.this);
...but unfortunately I can't use startActivity() in the class. This is my class code:
public class Testclass extends Activity {
public Testclass(Activity cc) {
Intent intent = new Intent(cc,Next.class);
startActivity(intent);
}
}
Try this and tell me if it helped you.
public class Testclass extends Activity {
public Testclass(Activity cc) {
final Context context = Testclass.this.getContext();
Intent intent = new Intent(context , Next.class);
context.startActivity(intent);
}
}
You misunderstood the concept of an Activity and its life cycle. You DON'T instantiate the Activity, the Activity has callback mechanisms (onCreate, onResume, etc.) that tell you exactly what to do. You never ever have to call new Activity().
The fact that you're doing
Testclass testclass = new Testclass(Main.this); shows that you have a misunderstanding of this concept: http://developer.android.com/training/basics/activity-lifecycle/index.html
To fix your error, read the docs and then it will be clear what is wrong with your approach.
Hint: Your Testclass already IS an Activity, because you inherit from Activity.
And next time please provide the whole error log to your problem, so it can give the whole picture of what can be wrong with your code.
Why not use this code?
startActivity(new Intent(Main.this, Next.class));
// "Main" is your current Activity
// "Next" is your next Activity to be opened.
I think, it's very simple to use without create a new public class. Please compare your codes with my code above, only one line.
I think you don't use the correct Context to start the Intent.
Instead try
{
public Testclass() {
Intent intent = new Intent(this,Next.class);
startActivity(intent);
}
}
if the this doesn't work either, try getApplicationContext() instead.
#you can used Weak Reference Objects to store Context of Activity class#
##in activity class##
public class Activity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
findViewById(R.id.toNext).setOnClickListener(this);
}
#Override
public void onClick(View v) {
Testclass thread = new Testclass(Activity.this,v);
new Thread(thread).start();
}
}
}
// in sub class
public class Testclass extends Activity implements Runnable {
View landingPage;
private Activity activity;
public Testclass (Activity activity, View landingPage){
WeakReference<Activity> ActivityWeakReference = new WeakReference<>(Activity);
this.landingPage = landingPage;
this.activity = activityWeakReference.get();
}
#Override
public void run() {
Intent activityIntent = new Intent(activity, Next.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
runOnUiThread(new Runnable() {
#Override
public void run() {
switch (landingPage.getId())
{
case R.id.Next.class:
activity.finish();
activity.startActivity(activityIntent);
break;
}
}
});
}
}
after been searching stackoverflow to see if there was a question to this, there none that helped me on this.
On my main activity I have this:
if (GlobalVars.espera == 0)
{
GlobalVars.espera = 1;
try
{
bgIntent = new Intent(this, Loadscreen.class);
startService(bgIntent);
}
catch (Exception e)
{
GlobalFunctions.toast_message(context, "nao");
}
}
When i start the application it should load the intend to work on background but it isn't.
Here is the class of loadscreen:
public class Loadscreen extends IntentService{
MainActivity teste;
private static final String intService = "loadscreen";
public Loadscreen()
{
super(intService);
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent)
{
teste = new MainActivity ();
try
{
teste.inic();
}
catch (Exception e)
{
}
}
}
and manifest I have put
<service android:name=".Loadscreen"></service>
on it too, as a child of application
Even that I have the try, it doesn't go into the catch AKA error, but still doesn't go into the class Loadscreen.
Thanks for the help and time
You have
teste = new MainActivity (); // assuming MainActivity is a Activity class
You are instantiating Activity class which is wrong.
I'm trying to send data from an overlay to other activity with this class
public class Capas extends ItemizedOverlay<OverlayItem>
{
MapView Map;
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
#SuppressWarnings("unused")
private Context mContext;
public Capas(Drawable defaultMarker, Context context)
{
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint puntoTocado = mapView.getProjection().fromPixels((int) event.getX(),(int) event.getY());
Intent nuevoLugar=new Intent(Capas.this,editarLugar.class);
nuevoLugar.putExtra("latitud",puntoTocado.getLatitudeE6());
nuevoLugar.putExtra("longitud",puntoTocado.getLongitudeE6());
StartActivity()
}
return false;
}
}
But this return me the next error The constructor Intent(Capas, Class) is undefined.
I try with Intent nuevoLugar=new Intent(Capas.class,editarLugar.class); Intent nuevoLugar=new Intent(this,editarLugar.class); but anoone works
In this case this should work:
Intent nuevoLugar = new Intent(mContext, editarLugar.class);
Provided that editarLugar extends Activity and is declared in AndroidManifest.xml.
And to start the activity:
mContext.startActivity(nuevoLugar);
the first argument should be a Context. please try Intent nuevoLugar=new Intent(mContext,editarLugar.class);
To create a a new intent you need to get access to a Context instance. ItemizedOverlay doesn't extend from it.
You have you initialize the intent like this:
Intent nuevoLugar=new Intent(mContext, editarLugar.class);
You need to make sure that editarLugar is an Activity.
But also, you need access to the activity. Since I think we can assume that you are creating it from an Activity you can launch it like this:
if(mContext instanceof Activity) {
((Activity)mContext).startActivity(nuevoLugar);
}
My bad, you can just call:
mContext.startActivity(nuevoLugar);