I am extending a thread class and from that class I want to start an activity. How to do this?
You need to call startActivity() on the application's main thread. One way to do that is by doing the following:
Initialize a Handler and associate it with the application's main thread.
Handler handler = new Handler(Looper.getMainLooper());
Wrap the code that will start the Activity inside an anonymous Runnable class and pass it to the Handler#post(Runnable) method.
handler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent (MyActivity.this, NextActivity.class);
startActivity(intent);
}
});
you can use Something like this.
public class MyActivity extends Activity
{
Handler hander = new Handler(){
public void handleMessage(Message m){
Intent intent = new Intent (MyActivity.this, Next.class);
startActivity(intent);
}
};
pubilc void onCreate(Bundle ic)
{
//your code setContentView() etc....
Thread toRun = new Thread()
{
public void run()
{
hander.sendMessage(1);
}
}
toRun.start();
}
}
Well to start an activity of an class, a class should extends with activity according to me.
But if you want to start activity with some threading function you can do these things.
Instead of extends Thread, use implements Runnable. After that some class that have an Activity you just call the start thread and put your logic and that start Intent.
I think this is the good solution for you.
Related
I'm trying to launch another activity from a fragment, but I'm getting an error that sais me "the class ... cannot be referenced from static context".
I'm doing the call from a handler, inside of a PlaceholderFragment
public void wait_launch_handler(int secs){
handler.postDelayed(new Runnable() {
#Override
public void run()
{
Animation fadeout = AnimationUtils.loadAnimation(getActivity(), R.anim.fadeout);
rl_container.startAnimation(fadeout);
Intent main_menu = new Intent(SplashscreenOptimizedActivity.this, MainActivity.class);
startActivity(main_menu);
}
}, secs * 1000 );
}
The error is given by "Intent main_menu = new Intent(SplashscreenOptimizedActivity.this, MainActivity.class);"
Thank you.
inside a Fragment you have to use getActivity() in place of SplashscreenOptimizedActivity.this to retrieve the context of the Activity that hosts your Fragment
Try to use Fragment.getActivity() method instead of SplashscreenOptimizedActivity.this
INTRODUCTION
I have a sub-class inside my main activity's class, which extends thread and is started every time the camera detectecs movement.
Inside this thread, when it dectects movement continuosly, it must start another thread which belongs to the main Activity's class.
I now it can be a bit messy but i'l explain it now in detail
CODE
This is a simplified version of my code that shows exactly what I mean:
public class MainActivity extends Activity {
//...
public Runnable SpeechWhenMotion = new Runnable() {
#Override
public void run() {
// Do stuff here
}
}
private static final class DetectionThread extends Thread {
//...
#Override
public void run() {
//...
//START "SpeechWhenMotion" HERE!
}
}
}
QUESTION
So the doubt I have is, how do I start the Runnable inside the thread of the DetectionThread class?
I've tryed using a handler but I think I'm not doing it right cause it doesn't get started.
If you really need SpeechWhenMotion runnable to be nester class of MainActivity you need to provide link of MainActivity or SpeechWhenMotion instance to DetectionThread class:
private static final class DetectionThread extends Thread {
private Runnable mSpeechWhenMotionRunnable;
//...
}
then, when you create DetectionThread assign SpeechWhenMotion to it from main activity
DetectionThread detectionThread = new DetectionThread();
detectionThread.mSpeechWhenMotionRunnable = SpeechWhenMotion;
And finally, call start new thread inside DetectionThread:
//START "SpeechWhenMotion" HERE!
new Thread(mSpeechWhenMotionRunnable).start();
I tried it out and this works rather smoothly:
new Thread(SpeechWhenMotion).start();
First, I am an android rookie, so my solution ways can be found awkward, and i am open to suggestions.
I am trying to create a game manager object that handles all transitions between activities. And my purpose is that while in an activity, menuOut method will call the changeActivity method of GameManager object with nextActivity argument and changeActivity will start that Activity. I am getting errors consistently, and did not find a solution.
Here is my source codes:
GameManager:
public class GameManager{
public SplashScreen splash = new SplashScreen();
public MainScreen main = new MainScreen();
public LoadingScreen load = new LoadingScreen();
Context tempContext;
public GameManager(Context base) {
super();
tempContext = base;
}
public void start(){
createScreens();
Intent intent = new Intent(tempContext, splash.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
tempContext.startActivity(intent);
}
public void createScreens() {
//here is the method that i am trying to find a solution
((SplashScreen)splash.getContext()).setGameClass(this);
((MainScreen)main.getContext()).setGameClass(this);
((LoadingScreen)load.getContext()).setGameClass(this);
}
public void changeMenu(MenuType nextMenu, MenuType previousMenu){
Intent intent2;
switch(nextMenu){
case MAIN_SC:
tempContext = main.getContext();
intent2.setClass(tempContext, main.getClass());
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
tempContext.startActivity(intent2);
case GAME_LOADING_SC:
tempContext = load.getContext();
intent2.setClass(tempContext, load.getClass());
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
tempContext.startActivity(intent2);
default:
break;
}
}
}
And here is SplashScreen activity:
public class SplashScreen extends Activity {
public Context context = this;
public GameManager gameman;
private static final int SPLASH_DURATION = 4000;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
splash();
menuOut();
}
public Context getContext() {
return this;
}
public void splash() {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setBackgroundResource(R.drawable.game_loop_splash);
setContentView(ll);
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, SPLASH_DURATION);
}
public void setGameClass(GameManager game){
gameman = game;
}
private void menuOut(){
gameman.changeMenu(MenuType.GAME_LOADING_SC, MenuType.GAME_SPLASH_SC);
this.onDestroy();
}
}
I can not return to the GameManager and call the changeMenu method.
I am very exhausted to get null pointer exceptions.
Any idea?
From what I read, you are trying to implement a singleton pattern. There are two ways I'd recommend to do that on android:
Extend the Application class, register your class in the manifest and use getApplication() in your activities to get access to it:
// In MyApplicationSubclass.java:
public final class MyApplicationSubclass extends Application {
/* ... */
public void myMethod() {
// insert some code here
}
/* ... */
}
// From your Activity:
((MyApplicationSubclass) this.getApplication()).myMethod();
Use a "normal" java singleton pattern, e.g. use a private constructor and keep one static instance within your GameManager class (this is the way the Android docs recommend, but I personally prefer the first way when having something that is logically bound to the Application).
Also, if you're only using your central class to do static stuff, you can just mark all its method as static and access them directly. Transfer Context objects as parameters to these methods, and you should be able to start activities without any static variables (which are sometimes hard to implement properly in Android, as your VM might get restarted from time to time).
I have a MainActivity the default start up Activity which creates a TCP worker thread.
This TCP thread receives some data from the server and passes it to the current Activity on display say there are two more Activities called Activity1 and Activity2 which will display the received data.
How do i achive this using Handlers ?
Here is a outline of what I have...please suggest solution or change everything if I am completely wrong.
public class MainActivity extends Activity
{
public static TCPFunctions tcp = null;
public static Handler handler;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler = new Handler();
tcp = new TCPFunctions(this, handler);
tcp.start();
}
}
----------------------------------------TCP Thread Class---------------------------------
public class TCPFunctions extends Thread
{
public Handler handler;
//socket and io streams are here and they work properly
Public TCPFunctions(MainActivity main, Handler _handler)
{
this.main = main;
handler = _handler;
}
public void run()
{
Intent showActivity1 = new Intent(main, Activity1.class);
main.startActivity(showActivity1);
while(true)
{
directories = new Vector<String>();
directories = (Vector<String>) inputStream.readObject();
Message msg = Message.obtain();
msg.obj = directories;
handler.sendMessage(msg);
directories = null;
}
}
}
now say in Activity1 I want this directories object...
Lets say my Activity1 has a button which when pressed sends a request to the server to get the directories object...which is received by the TCP thread...now how do I get this in Activity1 and update the UI...
Basically the directories object is a Vetor of Strings and I want to display the strings on a ListView contained in the Activity1/Activity2
public class Activity1 extends Activity implements OnClickListener,OnItemClickListener
{
private ListView directoryList;
private Button rootButton;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fileexplorer);
directoryList = (ListView) findViewById(R.id.directories);
rootButton.setOnClickListener(this);
directoryList.setOnItemClickListener(this);
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.root_button:
Log.d(TAG, "FileExplorer: Root Button Pressed");
//request for directories made here
break;
}
}
// What should be the Handler code to get the directories ?
}
First: The handler executes runnables and handles messages in the thread that created it. So if you want Activity1 to react to data from TCPFunctions, you have two options. Either:
-MainActivity, which created the handler in your current code, needs to react to the message, get the data, and send it along to Activity1
-Or Activity1 needs to be the one to create the handler.
In either case, the core answer to your question of how to react to a sent message, is that you need to override the handleMessage() method by subclassing the handler. Here's a boilerplate snippet you can use (pulled from one of the sample apps on the Android developer website)
mUpdateHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String chatLine = msg.getData().getString("msg");
addChatLine(chatLine);
}
};
I have registered ProximityAlert in MapActivity. No problem with catching alerts in BroadcastReceiver and starting new Activity.
Beside starting new activity I want to notify MapActivity to clear overlay, proximity alert and stop count up timer.
Because broadcast receiver is in separate thread I was make a handler
public class MyHandler extends Handler {
private ProximityMapActivity MainActivity;
MyHandler(ProximityMapActivity a) {
this.MainActivity = a;
}...
in MapActivity
public void onCreate(Bundle savedInstanceState) {
handler = new MyHandler(this);
I have no problem with Handler from runOnFirstFix runnable I can start a count up timer.
But broadbast receiver is in separate class and I have no clue what to do
private MyHandler handler;
...
handler.sendEmptyMessage(11);
is give me null pointer exeption. When I add
handler= new MyHandler(new ProximityMapActivity());
Uncaught handler comes out.
Can you give me a hint or comment? Thank You in forward.
I forgot to add setter to my object. Now I can pass on the pointer of handler.
in MapActivity
public void onCreate(Bundle savedInstanceState) {
handler = new MyHandler(this);
ProximityAlertHelper.setHandler(handler);