Its a week yet and I still get problems integrating the cordova into ana ndroid webview!
Before the onPause and onResume were working fine but after integration they dont trigger anymore.
Even though I see this in my console:
07-15 17:01:21.880: D/CordovaActivity(5635): Paused the application!
07-15 17:01:21.880: D/CORDOVA_ACTIVITY(5635): onPause
but the code inside the opPause function isn't executing!! I'm really tired of this.. I tried a week non stop to get it working.
This is my main java file:
package com.Snap.What;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import org.apache.cordova.*;
public class WhatSnap extends CordovaActivity implements CordovaInterface
{
private CordovaWebView cordova_webview;
private String TAG = "CORDOVA_ACTIVITY";
private final ExecutorService threadPool = Executors.newCachedThreadPool();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.cordova_layout);
cordova_webview = (CordovaWebView) findViewById(R.id.cordova_web_view);
// Config.init(this);
cordova_webview.loadUrl("file:///android_asset/www/index.html");
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
cordova_webview.getSettings().setJavaScriptEnabled(true);
cordova_webview.addJavascriptInterface(jsInterface, "JSInterface");
}
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
#JavascriptInterface
public void showLog(){
Log.v("blah", "blah blah");
}
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
#Override
public void onDestroy() {
super.onDestroy();
if (this.cordova_webview != null) {
this.cordova_webview
.loadUrl("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};");
this.cordova_webview.loadUrl("about:blank");
cordova_webview.handleDestroy();
}
}
#Override
public Activity getActivity() {
return this;
}
#Override
public ExecutorService getThreadPool() {
return threadPool;
}
#Override
public Object onMessage(String message, Object obj) {
Log.d(TAG, message);
if (message.equalsIgnoreCase("exit")) {
super.finish();
}
return null;
}
//
//
// #Override
// public void setActivityResultCallback(CordovaPlugin cordovaPlugin) {
// Log.d(TAG, "setActivityResultCallback is unimplemented");
// }
// #Override
// public void startActivityForResult(CordovaPlugin cordovaPlugin,
// Intent intent, int resultCode) {
// Log.d(TAG, "startActivityForResult is unimplemented");
// }
}
I tried also to comment the onPause and onresume from java but than I only get this in console:
07-15 17:01:21.880: D/CordovaActivity(5635): Paused the application!
In my js I have these lines:
document.addEventListener("resume", onResume, false);
document.addEventListener("pause", punish, false);
and the coresponding functions wich WONT EXECUTE!
I really don't know why they're not executing.. Please take a look and you you have any idea pls tell me.
Its an old post, still if some one is following
Change
document.addEventListener("pause", punish, false);
to
document.addEventListener("pause", onPause, false);
Related
I am trying to implement 360 Video Viewer in my project but I am getting an error for the line:
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
This is the error
Method loadVideoFromAsset must be called from the UI thread, currently inferred
thread is worker
Following is my code:
package com.example.jal.jp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import com.google.vr.sdk.widgets.video.VrVideoEventListener;
import com.google.vr.sdk.widgets.video.VrVideoView;
import java.io.IOException;
public abstract class VR_Video extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private VrVideoView mVrVideoView;
private SeekBar mSeekBar;
private Button mVolumeButton;
private boolean mIsPaused;
private boolean mIsMuted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vr__video);
initViews();
}
public void onPlayPausePressed() {
}
public void onVolumeToggleClicked() {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}
class VideoLoaderTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
return true;
}
}
public void playPause() {
}
#Override
protected void onPause() {
super.onPause();
mVrVideoView.pauseRendering();
mIsPaused = true;
}
#Override
protected void onResume() {
super.onResume();
mVrVideoView.resumeRendering();
mIsPaused = false;
}
#Override
protected void onDestroy() {
mVrVideoView.shutdown();
super.onDestroy();
}
private class ActivityEventListener extends VrVideoEventListener {
#Override
public void onLoadSuccess() {
super.onLoadSuccess();
}
#Override
public void onLoadError(String errorMessage) {
super.onLoadError(errorMessage);
}
#Override
public void onClick() {
super.onClick();
}
#Override
public void onNewFrame() {
super.onNewFrame();
}
#Override
public void onCompletion() {
super.onCompletion();
}
}
}
Please help. I tried my best but couldn't fix.
Remove AsyncTask Implementation And Call Required Methods From UI Thread
Use Below Code :
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}
I dont know much about videoview but I show in your code that you are trying to access some the features in doInbackground method. The doINbackground method runs on a separate thread from the UI thread so that complex ant time consuming tasks do not block the UI thread. You can implement the features you are implementing in doINbackground method in the onCreate method or if you still need to use doInbackground you can access the UI thread inside doInbackground using runOnUiThread as follows
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code here
}
});
I like to exit my application immediately after starting a service.
The code below causes the activity to finish before the service is started.
How do I set a listener to prompt me when the service is started?
btn = (ImageButton) findViewById(R.id.button );
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(new Intent(MainActivity.this, MyService.class));
//I want to exit the activity here.
finish(); // this exits the activity before the service is started
}
});
The following are the codes I used, based on the proposal by #Er.Arjunsaini
on the ACTIVITY file, I register to listen for an "Exit App" broadcast.
private final BroadcastReceiver exitAppReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//activity exits when "exit app" broadcast received.
finish();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//REGISTER TO LISTEN FOR THE BROADCAST
LocalBroadcastManager.getInstance(this).
registerReceiver(exitAppReceiver, new IntentFilter(getString(R.string.exit_app)));
btn = (ImageButton) findViewById(R.id.my_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService( new Intent(this, MyService.class));
}
});
}
#Override
public void onDestroy() {
//UNREGISTER THE RECEIVER
LocalBroadcastManager.getInstance(this).
unregisterReceiver(exitFloatingWindowReceiver);
super.onDestroy();
}
on the SERVICE file, I send an "Exit APP" broadcast.
#Override
public void onCreate() {
super.onCreate();
//... do the rest of the Service initializing
//CLOSE ACTIVITY
LocalBroadcastManager.getInstance(this).
sendBroadcast(new Intent(getString(R.string.exit_app)));
}
check out ServiceConnection, onServiceConnected may be method you are looking for to call finish()
HERE you have example
If you use bindService() instead of startService(), you can use the Message based communication system between Activity and Service.
This is explained in this reference.
At the end of the section there's a link to sample classes:
-MessengerService.java
-MessengerServiceActivities.java
Here an example of an Activity with 2 button, one for starting the Service and one for sending a message to the Service that will resend a message to the Activity to close it.
MainActivity.java
package com.pasquapp.brodcasttest01;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public final static int WHAT_CLOSE_ACTIVITY=1;
private Button startServiceButton;
private Button closeButton;
private Messenger activityMessenger;
private Messenger serviceMessenger;
private MyServiceConnection serviceConnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activityMessenger =new Messenger(new ActivityHandler());
initView();
}
#Override
protected void onDestroy() {
super.onDestroy();
if(serviceConnection!=null)
unbindService(serviceConnection);
}
private void initView(){
startServiceButton=findViewById(R.id.button_start_service);
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService();
}
});
closeButton=findViewById(R.id.button_close);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(serviceMessenger!=null){
Message msg=Message.obtain();
msg.replyTo=activityMessenger;
msg.what=MyService.WHAT_CLOSE_ACTIVITY;
try {
serviceMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
});
}
private class MyServiceConnection implements ServiceConnection{
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
serviceMessenger=new Messenger(iBinder);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
serviceMessenger=null;
}
}
private void startService(){
serviceConnection=new MyServiceConnection();
bindService(new Intent(this,MyService.class),serviceConnection,BIND_AUTO_CREATE);
}
private class ActivityHandler extends Handler{
#Override
public void handleMessage(#NonNull Message msg) {
int what=msg.what;
switch (what){
case WHAT_CLOSE_ACTIVITY:
MainActivity.this.finish();
break;
default:
super.handleMessage(msg);
}
}
}}
MyService.java
package com.pasquapp.brodcasttest01;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import androidx.annotation.NonNull;
public class MyService extends Service {
public static final int WHAT_CLOSE_ACTIVITY=1;
private Messenger mMessenger;
public MyService() {
}
#Override
public void onCreate() {
super.onCreate();
mMessenger=new Messenger(new ServiceHandler());
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
private class ServiceHandler extends Handler{
#Override
public void handleMessage(#NonNull Message msg) {
int what=msg.what;
switch (what){
case WHAT_CLOSE_ACTIVITY:
Messenger messenger=msg.replyTo;
Message closeMsg=Message.obtain();
closeMsg.what=MainActivity.WHAT_CLOSE_ACTIVITY;
try {
messenger.send(closeMsg);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
}
I have a broadcast receiver in my app which is fired every time the user gets an incoming call. Now, when it happens, I need the broadcast receiver to invoke a specific method in a specific activity. Now, I tried to make this method static and therefore available, but something tells me it is a very bad idea.
Accordingly, I tried to instantiate the broadcast receiver inside my activity without declaring it in my manifest but the problem is - when the app is off, the activity dosn't exist and therefore I can't invoke my method.
So my question is - How can I invoke this method when the broadcast receiver is fired up, without making it "public static"?
Here is my activity code(I have deleted the irrelevant parts)
package com.silverfix.ringo.activities;
import com.silverfix.ringo.R;
import com.silverfix.ringo.activities.fragments.DataManagerFragment;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class RingtonesActivity extends Activity{
private DataManagerFragment dataManagerFragment;
private IntentFilter filter;
private BroadcastReceiver phoneCall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtones);
ActionBar ab = getActionBar();
ab.setDisplayShowTitleEnabled(false);
ab.setDisplayHomeAsUpEnabled(true);
dataManagerFragment = new DataManagerFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(dataManagerFragment, "DataManagerFragment");
ft.commit();
filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
phoneCall = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
dataManagerFragment.act();
}
};
registerReceiver(phoneCall, filter);
}
}
You can use observers , like
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
ObservableObject.getInstance().updateValue(intent);
}
}
public class MainActivity extends Activity implements Observer {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObservableObject.getInstance().addObserver(this);
}
#Override
public void update(Observable observable, Object data) {
Toast.makeText(this, String.valueOf("activity observer " + data), Toast.LENGTH_SHORT).show();
}
}
public class ObservableObject extends Observable {
private static ObservableObject instance = new ObservableObject();
public static ObservableObject getInstance() {
return instance;
}
private ObservableObject() {
}
public void updateValue(Object data) {
synchronized (this) {
setChanged();
notifyObservers(data);
}
}
}
Receiver can be used via manifest.
ObservableObject - must be singleton.
This might help: how can I notify a running activity from a broadcast receiver?
Also, you can try using Observers
Something like:
public class BroadcastObserver extends Observable {
private void triggerObservers() {
setChanged();
notifyObservers();
}
public void change() {
triggerObservers();
}
}
In your broadcast receiver:
#Override
public void onReceive(Context context, Intent intent) {
BroadcastObserver bco = new BroadcastObserver();
bco.change();
}
and the Activity:
public class YourActivity extends Activity implements
Observer {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BroadcastObserver bco = new BroadcastObserver();
bco.addObserver(this);
}
#Override
public void update() {
//TODO: call your desired function
}
}
If anyone needs two-way communication between a BroadcastReceiver and a Activity, I wrote this utility class which simplifies invoking Methods on each other while still being memory-safe.
https://gist.github.com/Jenjen1324/4a0c03beff827082cb641fc8fe2c4e71
I'm developing a simple game where 3 activities (menu, settings and ranking list) needs one background music that should play smoothly in the background even if for example user leaves menu and goes into settings and then back.
For that I created service which works perfectly. There is only one major problem: when app is closed (user press home button for example), music doesn't stop playing.
I have tried with onDestroy, onStop, onPause but the problem is not solved.
Service:
package com.android.migame;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
public class Meni_music extends Service implements OnCompletionListener {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.menu);
player.setLooping(true); // Set looping
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
player.stop();
player.release();
stopSelf();
}
#Override
public void onLowMemory() {
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
}
}
Menu:
package com.android.migame;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Meni extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.meni);
startService(new Intent(Meni.this,Meni_music.class));
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
}
I think this behavior is most logically addressed by creating your own application class. Register this class in your manifest using:
<application
android:name="MyApplication"
Let the MyApplication class look something like this:
public class MyApplication extends Application
implements ActivityLifecycleCallbacks, Runnable
{
private Handler h;
#Override public void onCreate()
{
h = new Handler();
registerActivityLifecycleCallbacks(this);
}
public void onActivityCreated(Activity activity, Bundle savedInstanceState) { }
public void onActivityStarted(Activity activity) { }
public void onActivityStopped(Activity activity) { }
public void onActivitySaveInstanceState(Activity activity, Bundle outState) { }
public void onActivityDestroyed(Activity activity) { }
public void onActivityResumed(Activity activity)
{
h.removeCallbacks(this);
startService(new Intent(this, Meni_music.class));
}
public void onActivityPaused(Activity activity);
{
h.postDelayed(this, 500);
}
public void run()
{
stopService(new Intent(this, Meni_music.class));
}
}
Try this it will work .Make a ActivityLifecycleCallback class that will check if your application is in background or running.On onActivityStopped call stop your service.
public class MyLifecycleHandler implements ActivityLifecycleCallbacks {
private int resumed;
private int paused;
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
public void onActivityDestroyed(Activity activity) {
}
public void onActivityResumed(Activity activity) {
++resumed;
}
public void onActivityPaused(Activity activity) {
++paused
if(resumed == paused)
stopService(new Intent(this, Meni_music.class));
}
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
public void onActivityStarted(Activity activity) {
}
public void onActivityStopped(Activity activity) {
}
}
register your callback class -
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
I had a similar requirement, and here's how I solved it:
Create a class that implements Application.ActivityLifecycleCallbacks, and have your application register it with registerActivityLifecycleCallbacks in it's onCreate method. This class will be notified every time an activity is paused or resumed.
Have this class maintain a count of the number of active activities - start at 0, add one for each resumed activity, and subtract one for each paused activity. In practice, your counter will always be zero or one.
In your onActivityPaused method, after decrementing the counter, check to see if the count is zero. Note that there is a short period of time between an Activity being paused and the next one being resumed when you transition between activities, during which the count will be zero. If, after waiting some reasonable amount of time from the onActivityPaused, your count is still zero, then your application has been put completely into the background, and you should stop your service.
This is what you can do,
Create a static helper class, add a static variable msActivityCount in it and add following 2 methods in it.
increaseActivityCount() - increment the msActivityCount value. If msActivityCount == 1 start the service. Call this function from onStart() of each activity.
decreaseActivityCount() - decrement the msActivityCount value. If msActivityCount == 0 stop the service. Call this function from onStop() of each activity.
This should solve your issue without any problems.
Easy solutions:
Just use one activity! Use Fragments for each screen that you are displaying.
Use a static counter. Increment the counter when you call startActivity(). Decrement the counter onPause() of all activities. When an activity pauses, and your counter is 0, then stop the music.
Start your service when Menu activity resumes and stop it when the activity stops. So the Menu activity should look like something like this:
package com.android.migame;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Meni extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.meni);
}
#Override
protected void onPause() {
super.onPause();
stopService(new Intent(Meni.this,Meni_music.class));
}
#Override
protected void onResume() {
super.onResume();
startService(new Intent(Meni.this,Meni_music.class));
}
}
You declare your Intent outside the function in activity class and stop the service inside this class, call stop or ondestroy
like this:
public class Meni extends Activity {
private Intent i=new Intent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.meni);
i=new Intent(Meni.this,Meni_music.class);
startService(i);
}
#Override
protected void onDestroy() {
stopService(i);
super.onDestroy();
}
#Override
protected void onStop() {
stopService(i);
super.onStop();
}
}
Background Music without using Services:
http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion
I have this code:
package org.example.Threading;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ThreadingActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private doinback background = new doinback();
Handler handle= new Handler(){
#Override
public void handleMessage(Message msg) {
Log.e("INSIDE HANDLER", "About to stop the thread.");
background.stopThread();
}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e("ONCREATE", "BEFORE Thread");
background.start();
Log.e("ONCREATE", "AFTER Thread started");
View button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
class doinback extends Thread{
private volatile boolean isRunning = false;
public void run() {
while(isRunning){
Log.e("INSIDE THREAD", "about to sleep");
handle.sendMessage(handle.obtainMessage());
}
}
public void stopThread()
{
isRunning = false;
}
public void startThread(){
Log.e("INSIDE StartThread","MAKING isRunning True");
isRunning = true;
}
}
public void onClick(View v) {
background.startThread();
Log.e("INSIDE ONCLICK", "made isRunning true, about to leave");
}
}
I am trying to understand why it does not go back to the thread and if there is something I am doing wrong and if so what is the best way to go back and forth from a thread, for instance with the stopThread() function I change the value of the while variable to stop the thread from running. When I run the code and press the button it does not start the thread. Any ideas why?
When background.start() is called, isRunning is still false, so the thread is started(but didn't enter the while loop) and stopped immediately.
To ensure the thread to enter the while loop when startThread is called, you can put the following code in the startThread() method:
public void startThread(){
isRunning = true;
start();
}
And you don't call background.start() in onCreate(), just remove that line.
EDIT
If you want to keep a single thread alive, so you can "start" it and "stop" it as many times as you like, you can use the following code:
public void run () {
while (isRunning) {
if(!isWorking) {
try { Thread.sleep(10); } catch (InterruptedException ex) { }
continue;
}
//.. do your work here.
}
}
You control the running state of the thread with isRunning, and the working state with isWorking.