I'm having some problems trying to set togglebutton (LeftLightButton) state and text after receiving value 1 at novo.charAt(0) for example. The main idea is, i click the button, it makes webview.loadUrl, and if the page changes to what i expected the toggle button state should be on, if not, it must stay off and vice versa. The way it is now, doesnt change the text neither state in case the site didnt update to the value that i was expecting.
public class MainActivity extends Activity {
private WebView webView;
private ToggleButton LeftLightButton;
private Thread webviewthread;
private String baseURL;
private boolean LeftLightButtonState;
public void onCreate(Bundle savedInstanceState) {
final Context context = this;
baseURL = "http://192.168.1.4/i.php";
LeftLightButton = (ToggleButton) findViewById(R.id.toggleButton1);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runOnUiThread(new Runnable() {
public void run()
{
synchronized(this) {
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(context, "HTMLOUT");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
webView.loadUrl(baseURL);
}
}
});
showToast("Getting current status...");
}
public void notify(final boolean state, final ToggleButton buttonName) {
Thread thread = new Thread() {
#Override
public void run() {
synchronized (this) {
try {
wait(1000);
final ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton1);
if (!state && button.isChecked()) {
showToast("Couldnt turn OFF");
// UI
runOnUiThread(new Runnable() {
#Override
public void run() {
button.setChecked(false);
button.setTextOff("OFF");
}
});
// end of UI
}
if (state && !button.isChecked()) {
showToast("Couldnt turn ON");
// UI
runOnUiThread(new Runnable() {
#Override
public void run() {
button.setChecked(true);
button.setTextOn("ON");
}
});
// end of UI
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
thread.start();
}
public void showToast(final String toast)
{
runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
}
});
}
public void onClick(View arg0) {
final int id = arg0.getId();
switch (id) {
case R.id.toggleButton1:
if (LeftLightButtonState == true) {
webView.loadUrl(baseURL+"?L=0");
notify(false, LeftLightButton);
} else {
webView.loadUrl(baseURL+"?L=1");
notify(true, LeftLightButton);
}
break;
// even more buttons here
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void processHTML(String html) { // <html> <body> 1 0 0 0 </body> </html>
LeftLightButton = (ToggleButton) findViewById(R.id.toggleButton1);
String novo = android.text.Html.fromHtml(html).toString();
System.out.println("RECEIVED: "+novo);
if (novo != null) {
if (novo.charAt(0) == '0') {
LeftLightButtonState = false;
LeftLightButton.setTextOff("OFF");
LeftLightButton.setChecked(false);
}
if (novo.charAt(0) == '1') {
LeftLightButtonState = true;
LeftLightButton.setTextOn("ON");
LeftLightButton.setChecked(true);
}
System.out.println("CHEGUEI");
}
}
}
Use different string in the xml files itself. Then based on the state appropriate text will be displayed. You can call setChecked(true/false) to select or unselect the Toggle Button.. It is working fine in my project.
android:textOff="#string/dontshowtraffic"
android:textOn="#string/showtraffic"
Related
I want to use Rewarded video ads (Admob) but I want to show a progress bar while the video ads is loading
I already try to did it with async task just to see if the video will load but it didn't work
#SuppressLint("StaticFieldLeak")
public class videoAd extends AsyncTask<Void, Void, Void> {
#Override
protected void doInBackground(Void... voids) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
});
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (mRewardedVideoAd.isLoaded()){
Toast.makeText(SetFullWallpaper.this, "Video loaded", Toast.LENGTH_SHORT).show();
mRewardedVideoAd.show();
}
}
}
Now I want to load a progress bar if the video is not loaded yet
Thank you
This is how I did it:
I had a button, which when clicked showed the ad, so I had a boolean variable which tracked whether the button has been clicked:
boolean buttonClicked = false
These lines were in my onCreate function:
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(getContext());
rewardedVideoAdListener = new RewardedVideoAdListener() {
#Override
public void onRewardedVideoAdLoaded() {
if(buttonClicked) {
showAd();
}
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
if(buttonClicked) {
progressBar.setVisibility(View.INVISIBLE);
Toast toast = Toast.makeText(getContext(), "Please try again later", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onRewardedVideoCompleted() {
}
};
mRewardedVideoAd.setRewardedVideoAdListener(rewardedVideoAdListener);
loadRewardedVideoAd();
pointsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAd();
}
});
This was my showAd function:
public void showAd(){
if (mRewardedVideoAd.isLoaded()) {
progressBar.setVisibility(View.GONE);
mRewardedVideoAd.show();
buttonClicked = false;
} else {
loadRewardedVideoAd();
progressBar.setVisibility(View.VISIBLE);
buttonClicked = true;
}
}
How this works is, the app tries to load the ad in the background by calling the loadRewaredVideoAd() function when the activity/fragment is created. Then when the user clicks the button,showAd() function is called and one of two things happen:
1) If the ad was successfully loaded, it shows the ad.
2) If not, it calls loadRewardedVideoAd() again and shows a progressbar this time. It also sets buttonClicked to true. Then if the ad loads, the onRewardedVideoAdLoaded() function is called which calls showAd() again and this time the 1st option happens.
If the ad didn't load this time as well, then onRewardedVideoAdFailedToLoad(int i)is called and it shows a toast saying the user to try again later.
add OnProgressUpdate() in your class that extends AsyncTask and add progress dialog in this.
I am placing an admob video, which is executed when you enter the activity. In my case, I put an executable loop to start the video when it is already loaded.
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}else{
loadRewardedVideoAd();
}
This is part of all my code
private boolean started = false;
private Handler handler = new Handler();
private void initializeAdMob() {
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
private void loadRewardedVideoAd() {
if (!mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.loadAd(getString(R.string.id_block_activity), new AdRequest.Builder().build());
}
}
private void showRewardedVideoAd() {
if (BaseInteractor.isNetworkAvailable(this)) {
showProgressBar(true);
start();
}
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}else{
loadRewardedVideoAd();
}
if (started) {
start();
}
}
};
public void stop() {
started = false;
handler.removeCallbacks(runnable);
}
public void start() {
started = true;
handler.postDelayed(runnable, 2000);
}
finally I stop the runnable in
#Override
public void onRewardedVideoAdOpened() {
showProgressBar(false);
stop();
}
I hope this helps you.
My DeviceList.java code is as below :-
import com.technomentis.led.R;
public class DeviceList extends ActionBarActivity
{
//widgets
Button btnPaired;
ListView devicelist;
//Bluetooth
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
//Calling widgets
btnPaired = (Button)findViewById(R.id.btnOn);
devicelist = (ListView)findViewById(R.id.listView);
//if the device has bluetooth
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else if(!myBluetooth.isEnabled())
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
btnPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
pairedDevicesList();
}
});
}
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(DeviceList.this, ledControl.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
startActivity(i);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_device_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My ledcontrol.java is as follow
package com.technomentis.led;
public class ledControl extends ActionBarActivity {
Button btnOn, btnOff, btnDis;
SeekBar brightness;
TextView lumn;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgtes
btnOn = (Button)findViewById(R.id.button2);
btnOff = (Button)findViewById(R.id.button3);
btnDis = (Button)findViewById(R.id.button4);
brightness = (SeekBar)findViewById(R.id.seekBar);
lumn = (TextView)findViewById(R.id.lumn);
new ConnectBT().execute(); //Call the class to connect
//commands to be sent to bluetooth
btnOn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
btnDis.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
brightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser==true)
{
lumn.setText(String.valueOf(progress));
try
{
btSocket.getOutputStream().write(String.valueOf(progress).getBytes());
}
catch (IOException e)
{
}
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TF".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TO".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_led_control, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}
My ongoing R.java is as below
package com.technomentis.led;
public final class R {
public static final class attr {
}
public static final class mipmap {
public static final int cxemnet_logo=0x7f020000;
public static final int ic_action_search=0x7f020001;
public static final int ic_launcher=0x7f020002;
}
public static final class id {
public static final int btnOff=0x7f060000;
public static final int btnOn=0x7f060001;
public static final int listView=0x7f060002;
}
public static final class layout {
public static final int activity_device_list=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int btn_OFF=0x7f040003;
public static final int btn_ON=0x7f040002;
public static final int title_activity_main=0x7f040001;
}
public static final class style {
public static final int AppTheme=0x7f050000;
}
}
Can anybody help me in creating complete R.java file. I am unable to complete it.
Btw I am new to android studio.
I encounter this issue periodically. Build -> Rebuild Project and Build -> Clean Project always take care of the problem for me.
Thanks everyone,
Done with this problem. Simply create new project and copy pasted all files.
Rebuild done all the work.
Now need help in
Error:(53, 43) error: cannot find symbol variable lumn
I am trying to find when and where CH34xAndroidDriver.isConnected() value becomes true.
I have tried to find out and display its value in a toast. can anybody explain it clearly.
public class UartLoopBackActivity extends Activity {
public static final String TAG = "com.wch.wchusbdriver";
private static final String ACTION_USB_PERMISSION = "com.wch.wchusbdriver.USB_PERMISSION";
/* thread to read the data */
public readThread handlerThread;
protected final Object ThreadLock = new Object();
/* declare UART interface variable */
public CH34xAndroidDriver uartInterface;
// byte timeout; // time out
public Context global_context;
public boolean isConfiged = false;
public boolean READ_ENABLE = false;
public SharedPreferences sharePrefSettings;
Drawable originalDrawable;
public String act_string;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* create editable text objects */
readText = (EditText) findViewById(R.id.ReadValues);
// writeText = (EditText) findViewById(R.id.WriteValues);
global_context = this;
configButton = (Button) findViewById(R.id.configButton);
originalDrawable = configButton.getBackground();
readBuffer = new char[512];
baudRate = 9600;
stopBit = 1;
dataBit = 8;
parity = 0;
flowControl = 0;
configButton.setOnClickListener(new OpenDeviceListener());
// writeButton.setOnClickListener(new OnClickedWriteButton());
// writeButton.setEnabled(false);
//
uartInterface = new CH34xAndroidDriver(
(UsbManager) getSystemService(Context.USB_SERVICE), this,
ACTION_USB_PERMISSION);
act_string = getIntent().getAction();
if (-1 != act_string.indexOf("android.intent.action.MAIN")) {
Log.d(TAG, "android.intent.action.MAIN");
} else if (-1 != act_string
.indexOf("android.hardware.usb.action.USB_DEVICE_ATTACHED")) {
Log.d(TAG, "android.hardware.usb.action.USB_DEVICE_ATTACHED");
}
if (!uartInterface.UsbFeatureSupported()) {
Toast.makeText(this, "No Support USB host API", Toast.LENGTH_SHORT)
.show();
readText.setText("No Support USB host API");
uartInterface = null;
Toast.makeText(global_context,
"148k" + ((Boolean) uartInterface.isConnected()),
Toast.LENGTH_SHORT).show();
}
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if (READ_ENABLE == false) {
READ_ENABLE = true;
handlerThread = new readThread(handler);
handlerThread.start();
Toast.makeText(global_context,"155k" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();
}
}
public class OpenDeviceListener implements View.OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean flags;
Toast.makeText(global_context,"170" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();
Log.d("onClick", "12");
if (false == isConfiged) {
Log.d("onClick", "58");
isConfiged = true;
Log.d("onClick", "98");
// writeButton.setEnabled(true);
if (uartInterface.isConnected()) {
Log.d("onClick", "100");
flags = uartInterface.UartInit();
if (!flags) {
Log.d(TAG, "Init Uart Error");
Toast.makeText(global_context, "Init Uart Error",
Toast.LENGTH_SHORT).show();
} else {
if (uartInterface.SetConfig(baudRate, dataBit, stopBit,
parity, flowControl)) {
Log.d(TAG, "Configed");
}
}
}
if (isConfiged == true) {
Toast.makeText(global_context,"193" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();
Log.d("onClick", "200");
configButton.setEnabled(false);
}
}
}
}
public void onHomePressed() {
onBackPressed();
}
public void onBackPressed() {
super.onBackPressed();
}
protected void onResume() {
super.onResume();
if (2 == uartInterface.ResumeUsbList()) {
uartInterface.CloseDevice();
Log.d(TAG, "Enter onResume Error");
}
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
if (READ_ENABLE == true) {
READ_ENABLE = false;
}
super.onStop();
}
protected void onDestroy() {
if (uartInterface != null) {
if (uartInterface.isConnected()) {
uartInterface.CloseDevice();
}
uartInterface = null;
}
super.onDestroy();
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (actualNumBytes != 0x00) {
readText.append(String.copyValueOf(readBuffer, 0,
actualNumBytes));
Toast.makeText(global_context,"269k" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();
actualNumBytes = 0;
}
}
};
/* usb input data handler */
private class readThread extends Thread {
Handler mHandler;
/* constructor */
Handler mhandler;
readThread(Handler h) {
mhandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
public void run() {
while (READ_ENABLE) {
Message msg = mhandler.obtainMessage();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
// Log.d(TAG, "Thread");
synchronized (ThreadLock) {
if (uartInterface != null) {
actualNumBytes = uartInterface.ReadData(readBuffer, 64);
if (actualNumBytes > 0) {
mhandler.sendMessage(msg);
}
}
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.uart_loop_back, menu);
return true;
}
}
upto line 74 (Toast.makeText(global_context,"155k" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();) i found it returns false but when the onClick() is called it return true. why if any body has answer pls check it.
Thanks
the method ResumeUsbList() enables usb connection and changes isConnected() to true. if ResumeUsbList() fails it returns 2
Check your Activity's onResume()
I'm developing an application. When i exit from the application, it will be opened again (The first activity is called again and again). So i couldn't able to exit from it.
In some other activities I use EXIT button and proper code to exit. Even when I click the EXIT button on those activities, it will start login activity. (login page is opened)
In my application, I use
1) Main
2) ScreenActivity
3) Login
flow: (from main->screenActivity->login)
The start page (1st activity) is posted below
public class main extends Activity {
static ConnectivityManager conMgr;
BackgroundThread backgroundThread;
TextView myText;
boolean myTextOn = true;
Cursor cursor;
String response="";
public SQLiteAdapter mySQLiteAdapter;
private SQLiteDatabase sqLiteDatabase;
SimpleCursorAdapter cursorAdapter;
public class BackgroundThread extends Thread {
boolean running = false;
void setRunning(boolean b){
running = b;
}
#Override
public void run() {
// TODO Auto-generated method stub
//super.run();
while(running){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
handler.sendMessage(handler.obtainMessage());
}
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread);
myText = (TextView)findViewById(R.id.mytext);
}
#Override
protected void onStart() {
conMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
// TODO Auto-generated method stub
super.onStart();
if(isInternetAvailable())
{
Toast.makeText(this, "online", Toast.LENGTH_LONG).show();
startActivity(new Intent(main.this, ScreenActivity.class));
}
else{
startActivity(new Intent(main.this, splashscreen.class));
Toast.makeText(this, "offline", Toast.LENGTH_LONG).show();
}
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}
private boolean isInternetAvailable() {
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
backgroundThread.setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
}
}
public void onDEstroy()
{
super.onDestroy();
}
}
ScreenActivity:
public class ScreenActivity extends Activity implements AnimationListener {
private TextView animatedView3;
//ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
/* Animation animation1 = AnimationUtils.loadAnimation(this,
R.anim.anima);
animation1.setAnimationListener(this);
View animatedView1 = findViewById(R.id.aet1);
animatedView1.startAnimation(animation1);
/** set time to splash out */
final int welcomeScreenDisplay = 9000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
/**
* Called after splash times up. Do some action after splash
* times up. Here we moved to another main activity class
*/
startActivity(new Intent(ScreenActivity.this,
login.class));
}
}
};
welcomeThread.start();
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
//Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
if (animatedView3.getVisibility() == View.VISIBLE) {
animatedView3.setVisibility(View.INVISIBLE);
} else {
animatedView3.setVisibility(View.VISIBLE);
}
}
public void onAnimationRepeat(Animation animation) {
// Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
}
}
Please can anyone explain about the problem and how to solve it? I didn't understand.
Place finish() in your loginActivity and for other Activities as well else stack will store the list of visited Activities.
I have a video view that is full screen and would like to trigger a popupMenu when a certain key is pressed. The log shows that the key event is captured, but the popup view will not show. Any ideas why?
#Override
public boolean onKeyDown(int keyCode , KeyEvent event ){
switch(keyCode){
case KeyEvent.KEYCODE_DPAD_CENTER:
Log.i("POP uP MENU","Show");
mVideoView.pause();
showPopupMenu(new View(VideoPlayer.this));
case KeyEvent.KEYCODE_D:
popupMenu.dismiss();
}
return true;
}
private void showPopupMenu(View v){
popupMenu = new PopupMenu(VideoPlayer.this, v);
if(bitRates != null){
for(int i=0;i<bitRates.size();i++){
int menuItem = i;
popupMenu.getMenu().add(0,menuItem, 0,qualityList.get(i)+" : "+bitRates.get(i));
}
}
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem item) {
progressDialog = ProgressDialog.show(VideoPlayer.this, "", "Loading video...");
final int position = mVideoView.getCurrentPosition();
new Thread() {
public void run() {
try{
runOnUiThread(new Runnable() {
public void run() {
play(streamUrls.get(item.getItemId()),position);
}
});
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
}
progressDialog.dismiss();
}
}.start();
return true;
}
});
}
It seems that
KeyEvent.KEYCODE_DPAD_CENTER
is an event that is set to be triggered by the VideoView by default. So when I pressed that key VideoView triggered its event event instead of the event I was requesting it to. I changed the KeyEvent KEYCODE to another key(One not used by Videoview) and it worked.