How to keep IOIO connected when android screen goes off? - java

I am using the following code with IOIO to act as a motion detector, the problem is the IOIO is disconnected whenever my phone screen goes off! I do not want the screen to stay on all the time to keep the IOIO connected!
any solution please?
package com.LookHin.ioio_pir_motion_sensor;
import ioio.lib.api.AnalogInput;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends IOIOActivity {
private ToggleButton toggleButton1;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_about:
//Toast.makeText(getApplicationContext(), "Show About", Toast.LENGTH_SHORT).show();
Intent about = new Intent(this, AboutActivity.class);
startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class Looper extends BaseIOIOLooper {
private DigitalOutput digital_led0;
private AnalogInput deigital_input;
int i = 0;
private float InputStatus;
#Override
protected void setup() throws ConnectionLostException {
digital_led0 = ioio_.openDigitalOutput(0,true);
deigital_input = ioio_.openAnalogInput(45);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "IOIO Connect", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void loop() throws ConnectionLostException {
try{
digital_led0.write(!toggleButton1.isChecked());
InputStatus = deigital_input.getVoltage();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView1.setText(String.format("%.02f",InputStatus)+" v.");
if(InputStatus >= 3.0){
textView1.setBackgroundColor(Color.RED);
if (i == 0){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
i = 1;
};
}else{
textView1.setBackgroundColor(Color.TRANSPARENT);
i = 0;
}
}
});
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
}

Option 1) Lock the screen so it always stays awake
public void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Option 2) Fix your response to onPause().
When the screen goes off the onPause() method is called and you should handle it as otherwise your activity will be closed.
#Override
protected void onPause() {
// Your code
super.onPause();
}
The onPause() normally calls the ioio.disconnect() so this should be overrode.

IOIOService let´s you run your code on the background even if application goes to the background.

Related

Media Player not playing sound properly in Android on charger connection

I am new to software developing and i am trying to make an application that will play a sound when it charges. The first time i connect it to the charging cable, it plays the sound two times, which is not expected. Also, when i connect and disconnect the cable too quick, it also plays it twice.
Does anyone know the solution to this problem?
package com.mccharginggimmick;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
IntentFilter intentFilter;
BroadcastReceiver broadcastReceiver;
MediaPlayer mediaPlayerOff;
MediaPlayer mediaPlayerOn;
boolean playedOnceOn;
boolean playedOnceOff;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging){
onCharge();
}
else{
onDisconnect();
}
}
};
MainActivity.this.registerReceiver(broadcastReceiver, intentFilter);
}
public void onCharge(){
if(!playedOnceOn){
imageView.setVisibility(View.INVISIBLE);
mediaPlayerOn = MediaPlayer.create(this, R.raw.btnon);
mediaPlayerOn.start();
mediaPlayerOn.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayerOn.stop();
playedOnceOn = true;
playedOnceOff = false;
}
});
}
}
public void onDisconnect(){
if(!playedOnceOff){
imageView.setVisibility(View.VISIBLE);
mediaPlayerOff = MediaPlayer.create(this, R.raw.btnoff);
mediaPlayerOff.start();
mediaPlayerOff.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayerOff.stop();
playedOnceOff = true;
playedOnceOn = false;
}
});
}
}
}
define isCabelConnected inside class
boolean isCabelConnected = false;
then in your onClick
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
boolean isFullCharged = status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging && !isCabelConnected){
onCharge();
isCabelConnected = true;
} else if (isFullCharged && isCabelConnected){
onCharge();
}
else{
onDisconnect();
isCabelConnected = false;
}
this code will make a sound when cable connected and another sound when full charge

android error :ViewRootImpl$CalledFromWrongThreadException [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i know it has been asked before for a different program but I am still getting error given below for my program
Thread [Thread-15956] (Suspended (exception ViewRootImpl$CalledFromWrongThreadException))
Please HELP!!
This is my MainActivity class
package a.example.na;
import java.util.Scanner;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private static TextView inputtext;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private BluetoothDevice mDevice;
private Button findBtn;
private String address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
findBtn.setEnabled(false);
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
inputtext = (TextView) findViewById(R.id.text);
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View v, int pos,
long arg3) {
// Add the name and address to an array adapter to show in a ListView
String i = (String) adapterView.getItemAtPosition(pos);
B b=new B(inputtext);
b.start();
Scanner scanner = new Scanner(i);
if(scanner.hasNextLine()) {
address =scanner.nextLine();
}
mDevice = myBluetoothAdapter.getRemoteDevice(address);
scanner.close();
}
});
}
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add( device.getAddress()+ "\n" +device.getName() );
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
This is my separate Thread class
package com.bt;
import android.widget.TextView;
public class B extends Thread {
TextView inputtext;
public B(TextView x){
inputtext=x;
}
public void run(){
inputtext.setText("hero");
}
}
Your are touching the views(widgets) in the Non UI Thread.
public class B extends Thread {
TextView inputtext;
Activity activity;
public B(Activity activity, TextView x) {
inputtext = x;
this.activity = activity;
}
public void run() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
inputtext.setText("hero");
}
});
}
}
While starting the Thread
B b=new B(MainActivity.this, inputtext);
b.start();

How to make Android method work recurrently?

I have designed an app that displays text when tapped once and displays it differently on a Long Press and on a Double Tap. However, I observe that the methods are called once. That is once I either long press or tap once or double tap, the corresponding method is called and then on subsequent tapping or press does not do anything. What can be done to make the app work not just once?
package com.example.hello;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.ViewGroup.LayoutParams;
import android.view.View.OnTouchListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnClickListener;
public class MainActivity extends ActionBarActivity implements OnTouchListener {
private TextView shownamecenter;
private TextView shownamecustom;
private RelativeLayout myimage;
int x, y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shownamecenter = (TextView)findViewById(R.id.shownamecenter);
shownamecustom = (TextView)findViewById(R.id.shownamecustom);
myimage = (RelativeLayout)findViewById(R.id.myimage);
shownamecenter.setText("");
shownamecustom.setText("");
myimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showNameOnSingleTap();
return;
}
});;
myimage.setOnTouchListener(this); //{
myimage.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showNameInCustomPosition(shownamecustom, x, y);// TODO Auto-generated method stub
return true;
}
});
return;
}
private void showNameOnSingleTap() {
Timer countdown = new Timer(false);
countdown.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
shownamecenter.setVisibility(View.INVISIBLE);
}
});
}
},3000);
shownamecustom.setText("");
shownamecenter.setText("My Text");
shownamecenter.setTextColor(0xff00ff00);
RelativeLayout.LayoutParams layoutparameters = (RelativeLayout.LayoutParams)shownamecenter.getLayoutParams();
layoutparameters.addRule(RelativeLayout.CENTER_IN_PARENT, -1);
shownamecenter.setLayoutParams(layoutparameters);
findViewById(R.id.myimage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shownamecenter.setText("");
return;
}
});
return;
}
private void showNameInCustomPosition(TextView customview, int x, int y) {
Timer countdown = new Timer(false);
countdown.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
shownamecustom.setVisibility(View.INVISIBLE);
}
});
}
},3000);
RelativeLayout.LayoutParams relout = (RelativeLayout.LayoutParams) customview.getLayoutParams();
relout.leftMargin = x-50;
relout.topMargin = y-50;
customview.setLayoutParams(relout);
shownamecenter.setText("");
shownamecustom.setText("My Text");
shownamecustom.setTextColor(0xff00ff00);
class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDoubleTap(MotionEvent e) {
shownamecustom.setText("");
showNameOnSingleTap();
return true;
}
}
return;
}
//}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
x = (int)event.getRawX();
y = (int)event.getRawY();
return false;
}
}
The problem is because you are redefining what happens when you click on the image, which isn't terribly good practice because it makes it difficult to keep track of what should be going on. A View can only ever have one Listener of each type, so when you do
private void showNameOnSingleTap() {
//...
findViewById(R.id.myimage).setOnClickListener (new View.OnClickListener() {
#Override public void onClick(View v) {
shownamecenter.setText(""); return;
}
});
}
You are changing what happens every time that you click the image after that. Rather than calling your method showNameOnSingleTap() when it's clicked, it is only setting the text and not calling your method. Instead of reassigning the onClickListener, just keep a boolean variable to determine what you want to do.
boolean textIsVisible = false;
private void showNameOnSingleTap() {
if(textIsVisible) {
//hide text
textIsVisible = false;
shownamecenter.setText(View.INVISIBLE);
}
else {
Timer countdown = new Timer(false);
countdown.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
shownamecenter.setVisibility(View.INVISIBLE);
textIsVisible = false;
}
});
}
},3000);
//show text
textIsVisible = true;
}
}

Performing stop of activity that is not resumed?

I am making a simple Android app just to become familiar with the concept. I have an app with two activities, the first should just be a splash screen that displays for one second, the second is a canvas w/ a black square that turns cyan when you click it. When I run it, it stops with an error in the log saying "performing stop of activity that is not resumed".
Main Activity:
package com.example.test;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
Thread.sleep(1000);
}catch(Exception e){}
Intent in = new Intent(this, Afspl.class);
startActivity(in);
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Next Activity:
package com.example.test;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class Afspl extends Activity {
public DrawView vi;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
vi = new DrawView(this);
}
class DrawView extends View{
Paint paint = new Paint();
public DrawView(Context context){
super(context);
}
public void onDraw(Canvas c){
paint.setColor(col);
c.drawRect(40, 40, 200, 200, paint);
}
private int col = Color.BLACK;
public void setToColor(int c){
col=c;
}
}
public boolean onTouchEvent(MotionEvent me){
if(me.getX()>=30 && me.getX() <= 320 && me.getY() >=30 && me.getY() <= 320)vi.setToColor(Color.CYAN);
return super.onTouchEvent(me);
}
}
Do you have any idea why I'm getting this error or what it means or how I can fix this? All help is appreciated.
Insted of using:
try{
Thread.sleep(1000);
}catch(Exception e){}
Intent in = new Intent(this, Afspl.class);
startActivity(in);
You could try using new
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent in = new Intent(getApplicationContext(), Afspl.class);
startActivity(in);
}
}, 1000);
You should never put to sleep the main thread. If you want to do something in the future use a Handler and a Runnable.
Also, you should declare a View on both Activities, not just the first one. Create a View and set it with "setContentView()" on your second activity.

Why Is My Progress Bar Not Working?

package com.example.progressdialog;
import com.example.progressdialog.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);
}
public void open(View view){
progress.setMessage("Start This Baby Up!");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(false);
progress.show();
final int totalProgressTime = 100;
final Thread t = new Thread(){
#Override
public void run(){
int jumpTime = 0;
while(jumpTime < totalProgressTime){
try {
sleep(500);
jumpTime += 1;
progress.setProgress(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I cannot seem to get my progress bar to actually progress forward. It simply displays a static 0/100 bar. I am trying to get it to move forward in a smooth manner taking approximately 30-45 seconds to complete. Could someone tell me what I am doing wrong? I am very new to java! Thanks!
Citation:
progress.setProgress(0);
this should be
progress.setProgress(jumpTime);
I suppose?
Also I guess, this will lead to a problem. You cannot access UI-Components from background Threads. You need to use a Handler. See this Example.

Categories

Resources