We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I've actually managed to use hudson_m4000 code to confirm what the path of my video file should be. Problem even with this info, my processing sketch won't find my file. The following code (even if I know it can't show the video image) compile on my device, but return to the console "error loading transit.mp4":
import android.media.MediaPlayer;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
MediaPlayer mp ;
Context context ;
Activity activity ;
String statusText = "VIDEO INITIALIZING";
String SDCard = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
//String SDCard = "/storage/3E07-120C/";
void setup() {
size(400,400);
activity = this.getActivity();
context = activity.getApplicationContext();
mp = new MediaPlayer();
println( SDCard);
try {
mp.setDataSource(SDCard + "machine.mp4");
mp.prepare();
mp.start();
statusText = "VIDEO PLAYING";
}
catch (IOException e) {
println("error loading transit.mp4");
}
fill(255);
textAlign(CENTER, CENTER);
}
This code can't compile:
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.app.Activity;
import android.view.ViewGroup;
import android.view.View;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.content.res.Resources;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.Context;
AssetFileDescriptor afd;
Context context;
Activity act;
SurfaceView mySurface;
SurfaceHolder mSurfaceHolder;
MediaMetadataRetriever metaRetriever;
MediaPlayer mMediaPlayer;
void setup() {
size(400, 400, P2D);
act = this.getActivity();
context = act.getApplicationContext();
Looper.prepare();
mMediaPlayer = new MediaPlayer();
try {
afd = context.getAssets().openFd("machine_compr.mp4");
MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
metaRetriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
String height = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
if (int(height) < 2) {
throw new IOException();
}
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
mySurface = new SurfaceView(act);
mSurfaceHolder = mySurface.getHolder();
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
mMediaPlayer.setDisplay(surfaceHolder);
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
mMediaPlayer.setDisplay(surfaceHolder);
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
}
);
startVideo();
}
void startVideo() {
act.runOnUiThread(new Runnable() {
public void run() {
try {
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mSurfaceHolder = mySurface.getHolder();
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mMediaPlayer.prepare();
// act.addContentView(mySurface, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
act.addContentView(mySurface, new ViewGroup.LayoutParams(400,400));
if (mMediaPlayer.isPlaying() == false) {
mMediaPlayer.start();
}
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
);
};
void draw() {
}
void onPause() {
if (mMediaPlayer!=null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
super.onPause() ;
}
void onStop() {
if (mMediaPlayer!=null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
super.onStop() ;
}
void onDestroy() {
if (mMediaPlayer!=null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
super.onDestroy() ;
}
void onResume() {
super.onResume() ;
}
and the console says it's because file couldn't be loaded
OpenGL error 1280 at bot beginDraw(): invalid enum
java.io.FileNotFoundException: machine_compr.mp4
at android.content.res.AssetManager.openAssetFd(Native Method)
at android.content.res.AssetManager.openFd(AssetManager.java:334)
at processing.test.android_nativeplayer.android_nativeplayer.setup(android_nativeplayer.java:66)
at processing.core.PApplet.handleDraw(PApplet.java:1801)
at processing.opengl.PSurfaceGLES$RendererGLES.onDrawFrame(PSurfaceGLES.java:264)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1590)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1286)
FATAL EXCEPTION: main
Process: processing.test.android_nativeplayer, PID: 12773
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileDescriptor android.content.res.AssetFileDescriptor.getFileDescriptor()' on a null object reference
at processing.test.android_nativeplayer.android_nativeplayer$2.run(android_nativeplayer.java:110)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
OpenGL error 1285 at bot endDraw(): out of memory
I'll maybe try a post on the new forum, but there's so much ressource here, it felt more accurate to post here rather than create a new post which would point towards here...
Just to inform you, package on processing 3.3.7 is recognized as an error so I could not use the Keycode you sent me.
But based on your inputs, with research and experimentation, indicated are the following details. (Please correct me if I am wrong).
(1) I needed to use the System.exit(0); due to the reason that it is the only tested way I used to disconnect the target device with the app via bluetooth. When I don't use the indicated code, the app disconnects with the process but target device does not disconnect, creating an inefficiency in accessing app when placed on the background, which only happens when the back button is pressed.
(2) onBackPressed(); onHomePressed(); is not read in processing 3.3.7. I think that the reason to this is that, onBackPressed and onHomePressed runs in an activity and not in a fragment. And P3.3.7 executes commands in a fragment
(2) onStop(); onPause(); are affected by all buttons, that is why running System.exit(0); affected all buttons making all of the them disconnect application with the target device.
(3)onStop(); onPause(); when used in running System.exit(0); affects the app background button, giving it a minor inefficiency, wherein when the button is pressed if it is the only app on the background, there is a situation wherein you need to re-access the application twice.
(4) Based on my observation, pressing the backbutton destroys the app before it places it on the background, making the application disconnect without making the target device disconnect bluetooth connection. So due to this instead on focusing codes using onBackpress();, I used on onDestroy(); because it is not affect by the app backround button and homebutton. So applying system.exit(0); onDestroy, is just like executing the exit upon back button press.
So tested and finalized, due to the reason that the application has no more issues when pressing the 3 buttons, I used the indicated code below in exchange for the code that I used in this thread.
public void onDestroy(){ System.exit(0); }
These is a shared effort, so I will just indicate it as answered from akenaton's last response. Thank you.
@myrds===
that is not a 3XX problem; that is android. In order to be simple (& you can test each point):
When the user hits home button the activity goes in background without being killed except when the system decides it; if at this moment you are in an activity B, when the app resumes it restarts at the same activity. Think to a window or an app opened but not visible to the user, for a laptop. If for example you have a broadcast receiver or service registered it continues to run and you have probably (battery drain) to unregister it,in onPause() or (better) onStop() except in some cases (some service, an alarm with a pending intent: you app will do something each 25° day of the month at 12h: but the 24 other days it is sleeping).
When the user hits the back button that is not the case: if you are in an activity B, usually (see the last point) it kills it in the backStack and goes to activity A; all processes in B are stopped. It's like calling finish() on the activity B.
OnPause(), onStop() and so on are moments in the lifeCycle called one after the other; they are called in any case either when you hit the back button or the home one; that explains why overriding them affects the twos.
You can override back and/or home (of course you cannot "kill" them: the user is not your prisonner). Usually you do that to save some results or data or to open dialog window. Then using finish() in this case acts differently for the twos; it has not any effect with the Back one because this one calls finish() by itself (on the B Activity); with the Home one it kills all foregoing processes and on re-launch it restarts at the main activity.
Special case 1: you want to "disable" the back button; you are in C (from A to B) and you dont want to go to B nor A when back is pressed. In this case you have to destroy the whole backStack which is done adding "noHistory" to the Manifest.
Special case 2: you are in B and you want to preserve some results, as for example the list of all phones present with blue tooth activated, list you have got from the receiver; if back is pressed this list disappears (finish is called); in this case you can try to override onBackPressed with moveToTaskBack(true).
General cases for home && back: dont rely on them for your app especially the Home Button for security reasons:
Just an update guys for processing 3.3.7 android mode, please correct me if I am wrong, I think that the upgraded version of processing does not respond to codes using "public void onHomePressed()" and "public void onBackPressed()" syntax, that is why System.exit(0), did not activate using the codes for home and back. Though it works with "public void onPause()" and "public void onStop()". Am I not updated for the new syntax to run for processing 3.3.7 or it really does not really work at version 3.3.7. The app when installed, only runs on default Home, Back and Backround app buttons.
I just don't understand that if it worked with "onPause()" and "onStop()", why did it not work with "onBackPressed"?
I've just finished doing test doing "public void onPause, onStop, onResume and onStart" and also considered using "this.getActivity()" and System.exit(0);".
The result are the following:
(1) Based on the test, using "onPause" and "onStop" works. Also "System.exit(0);" should be used. It disconnects the bluetooth connection of both the application and the target device.
(2) It keeps the application in the background and reconnects bluetooth connection with target paired device when re-accessed.
But there is only one issue. When accessing app in the background, when displayed using the background applications button, the application does not respond on the first tap and displays or opens a different app. But reconnects on the second tap when app is re-accessed again.
No major issue though, but unable to access the application on the first tap is not a good quality. The issue only arises when the background application is pressed, but no issues with the home and back button.
I've been doing tests, and I thought of a solution. Indicated are the following observations.
(1)Pressing the "background apps button" and the "home button" places the application on the background without disconnecting the bluetooth connection with the target device.
(2)Pressing the "back button" places the application on the background disconnecting the bluetooth connection with the target device. A function placing the application onPause.
The problem occurs when the back button is pressed due to the reason that the app disconnects the bluetooth but the target device does not disconnect its connection unless the app completely closes, which only can be done manually when accessing the application on the "backround applications" and closing it there.
To efficiently reconnect the bluetooth connection of the app and the target device, the application should be completely closed, to also disconnect the bluetooth with the target device, but unfortunately, it is not possible. This makes "System.exit(0);" and "this.getActivity().finish();" not applicable. Also I tried removing the onBackpressed codes, and it works on (1) and (2) on default.
Is there a way to do the other way around since it works on (1) and (2) on default. That onBackpressed, we avoid the application from disconnecting bluetooth connection?
The truth is I already done everything I could, and I already want to give up. The only option that is left is how would I be able to work on the Bakpress button wothout disconnecting the bluetooth connection like the onPause.
@myrds===
i cannot seen any reason why back button could disable bluetooth "in the system" (and home button will not)
it s impossible to "close completely" (i.e "quit") with android; for that you have to uninstall the app. Only the system can destroy an app (for memory reasons or others)
put your complete code as it is now (and dont forget onPause, on stop() && on resume())
there is no way to change the back button to home button: it does its job: back in the stack.
@myrds===
without knowing how you have created your blueTooth conn. it's difficult to answer...Yet, supposing that you have a broadcastReceiver running (called eg myDiscoverer) you have to code something like that::
public void onPause(){
super.onPause();
if(myDiscoverer !=null){
getActivity().unregisterReceiver(myDiscoverer);
println("je désenregistre");
myDiscoverer=null;
}else{
println("désenregistré");
}
}
I tried the onPause(); it even affected the home button. So 2 problems, were gained, home button and onBackpressed.
@myrds===
ok, now i understand; in this case, yes, its easy, you have to disconnect bluetooth in the onPause() method.
Ok, thank you for answering the questions. This is how I installed the AM in Processing. I want to document it here and keep in mind these notes are from memory. Just to add, I run the emulator in Processing just now and it worked.
I have a Win 10 machine and P3.3.6 and AM4.0.1. I installed the Android SDK by installing Android Studio and selecting to install the Android SDK as well. I made a note of the sdk folder selected in the installation. Then I started Android Studio, I go to its SDK manager and I make sure I have Android API 26 (I didn't check this step, but I think I also have 21, 22 and 24). After they are installed, I closed AS. Then I ran Processing, I installed the AM as described above. After AM is installed, I switched from java to Android Mode in the PDE. The first time it tells me it cannot find the Android SDK and it gives me two options: Locate SDK Path Manually or Download SDK Automatically. I chose the first one and I provided the path of my SDK manually.
Then before I do anything else, I go to Android >> SDK updater and I make sure there are no updates pending.
Then in the processing IDE, I use the template I provide at the end of this post for testing. Then I go to Sketch>>Run in Emulator. As you described, an emulator window is launched where a Google animation is played for 15 seconds before the screen goes black. After about 2 minutes (ahhh slow laptop) I get the emulator showing me what it looks like a phone: Android Emulator - processing-phine:5566. My sketch is launched there. I click on the window and I register the ellipses.
As a side note, I cannot comment if downloading the Android SDK automatically works all the time. I tried this method long ago and it didn't work for me. I stick to this manner to install my Android SDK. From what I read, it seems that installing it this option, through the PDE, provides all the files you need to run AM in Processing. The reason I do it through Android Studio is because I am able to select and remove items in the SDK through their program. These options are simply not present in the SDK Updater in Processing.
Kf
//===========================================================================
// IMPORTS:
import android.app.Activity;
import android.content.Context;
import android.widget.FrameLayout;
//import android.app.Fragment;
import android.os.Environment;
import android.graphics.Color;
import android.widget.Toast;
import android.os.Looper;
import android.view.WindowManager;
import android.os.Bundle;
import android.view.ViewParent;
import android.view.ViewGroup;
import android.view.View;
import android.widget.RelativeLayout;
import android.view.LayoutInflater;
import android.R.string;
//===========================================================================
// FINAL FIELDS:
//===========================================================================
// GLOBAL VARIABLES:
Activity act;
Context mC;
//===========================================================================
// PROCESSING DEFAULT FUNCTIONS:
void setup(){
//size(400,600);
fullScreen();
orientation(PORTRAIT);
//orientation(LANDSCAPE;)
act = this.getActivity();
Looper.prepare();
textAlign(CENTER,CENTER);
rectMode(CENTER);
fill(255);
strokeWeight(2);
textSize(32);
}
void draw(){
//Erases everything in the sketch every two seconds approx.
if(frameCount%120==0)
background(0);
}
void keyReleased(){
}
void mouseReleased(){
fill(random(255));
ellipse(mouseX,mouseY,50,50);
}
//===========================================================================
// OTHER FUNCTIONS:
//===========================================================================
// ANDROID ACTIVITY LIFECYCLE'S FUNCTIONS:
// @@@@@@@@@@@@
@ Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// @@@@@@@@@@@@
@ Override
public void onStart() {
super.onStart();
}
// @@@@@@@@@@@@
@ Override
public void onResume() {
super.onResume();
act = this.getActivity();
mC= act.getApplicationContext();
}
// @@@@@@@@@@@@
@ Override
public void onPause() {
super.onPause();
}
// @@@@@@@@@@@@
@ Override
public void onStop() {
super.onStop();
}
// @@@@@@@@@@@@
@ Override
public void onDestroy() {
super.onDestroy();
}
Keywords: kf_keyword Android_SDK Android_SDK_Install Android_Emulator
I am not sure if this answers all your questions bc I am not sure what is the current status of your code. This next is tested. Notice some added imports and a single line change in setup, between other minor changes, like adding a button from Android widgets.
Kf
//REFERENCE: https:// forum.processing.org/two/discussion/26349/android-input-box#latest
//REFERENCE: https:// forum.processing.org/two/discussion/14206/on-screen-buttons-without-apwidgets
//REFERENCE:
//REFERENCE:
//REFERENCE:
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.*; //View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.LinearLayout;
import android.widget.EditText;
import android.widget.TextView;
import android.text.Editable;
import android.graphics.Color;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.View.OnKeyListener;
import android.view.View;
import android.view.KeyEvent;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Gravity;
import android.R;
import android.widget.Toast;
import android.os.Looper;
private static final int MY_BUTTON1 = 9000;
Activity act;
Context mC;
FrameLayout fl;
EditText edit;
Button iButton;
String txt;
int xbut, ybut, wbut = 110, hbut = 35;
boolean pressed;
void setup() {
fullScreen();
orientation(LANDSCAPE);
background(0, 0, 255);
xbut = width/10;
ybut = height/6;
inputButton(xbut, ybut, wbut, hbut);
Looper.prepare();
}
void draw() {
}
void showInputBox() {
background(0, 0, 255);
String txt = edit.getText().toString();
edit.getText().clear();
inputButton(xbut, ybut, wbut, hbut);
act.runOnUiThread(
new Runnable() {
public void run() {
edit.setVisibility(View.VISIBLE);
edit.requestFocus();
}
}
);
}
void hideInputBox() {
background(0, 0, 255);
inputButton(xbut, ybut, wbut, hbut);
String txt = edit.getText().toString();
text("Your input was: " + txt, width/3, height/12);
act.runOnUiThread(
new Runnable() {
public void run() {
edit.setVisibility(View.GONE);
}
}
);
}
void mousePressed() {
if (mouseX >= xbut && mouseX <= xbut + wbut && mouseY >= ybut && mouseY <= ybut + hbut) {
showInputBox();
}
}
void inputButton (int x, int y, float w, float h) {
textSize(20);
stroke(127);
rect(x, y, w, h);
color c2 = color(130, 0, 0);
color c1 = color(255, 85, 0);
for (int i = y; i <= y+h; i++) {
float inter = map(i, y, y+h, 0, 1);
color c = lerpColor(c1, c2, inter);
stroke(c);
line(x, i, x+w, i);
}
fill(255);
text("Input", x + 30, y + 25);
}
//===========================================================================
// ANDROID ACTIVITY LIFECYCLE'S FUNCTIONS:
// @@@@@@@@@@@@
@ Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// @@@@@@@@@@@@
@ Override
public void onStart() {
super.onStart();
act = this.getActivity();
mC= act.getApplicationContext();
act.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
iButton = new Button(act);
iButton.setText("InputButton");
iButton.setBackgroundColor(Color.GREEN);
iButton.setId(MY_BUTTON1);
OnClickListener oclMonBouton = new OnClickListener() {
public void onClick(View v) {
println("clicked");
pressed = true;
}
};
iButton.setOnClickListener(oclMonBouton);
edit = new EditText(mC);
edit.setLayoutParams (
new RelativeLayout.LayoutParams (
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT
)
);
edit.setHint("Write Here!");
edit.setTextColor(Color.rgb(0, 0, 0));
edit.setHintTextColor(Color.rgb(170, 170, 170));
edit.setBackgroundColor(Color.WHITE); // edit.getBackground().setAlpha(255);
edit.getLayoutParams().width=14*width/26;
edit.getLayoutParams().height=height/17;
edit.setX(width/3);
edit.setY(height/6);
edit.requestFocus();
edit.setInputType(android.text.InputType.TYPE_CLASS_TEXT);
edit.setOnKeyListener(
new View.OnKeyListener() {
@ Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode()== KeyEvent.KEYCODE_ENTER) {
InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
hideInputBox();
return true;
}
return false;
}
}
);
fl = (FrameLayout)act.findViewById(R.id.content);
FrameLayout.LayoutParams params1 = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
fl.addView(iButton, params1);
fl.addView(edit);
android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) getActivity().getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
// @@@@@@@@@@@@
@ Override
public void onResume() {
super.onResume();
act = this.getActivity();
mC= act.getApplicationContext();
act.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
// @@@@@@@@@@@@
@ Override
public void onPause() {
super.onPause();
}
// @@@@@@@@@@@@
@ Override
public void onStop() {
super.onStop();
}
// @@@@@@@@@@@@
@ Override
public void onDestroy() {
super.onDestroy();
}
@pigeon===
code snippet tested (with required permissions): it works; i have simplified your code (and suppressed some errors: your background cannot never be seen as green!!!!) but you can now easily get all infos about blueTooth devices: could be better to make an arrayList of all blueTooth objects and methods to get name, mac adress, rssi and so on...Think to unregister your receiver onPause (with cancelDiscovery()); see also that rssi can change, or new devices be discovered: your text in draw() can be difficult to read!
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Looper;
import android.app.Activity;
import android.app.Fragment;
import android.content.pm.PackageManager;
import android.os.Build;
int MyVersion = Build.VERSION.SDK_INT;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
Activity act;
Context mc;
String discoveredDeviceName;
String info = "";
short rssi;
boolean foundDevice=false; //When this is true, the screen turns green.
ArrayList<String> devicesDiscovered = new ArrayList<String>();
//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
BroadcastReceiver myDiscoverer;
void setup()
{
fullScreen();
orientation(LANDSCAPE);
textSize(28);
textAlign(CENTER, CENTER);
fill(225);
act = this.getActivity();
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
this.getActivity().startActivityForResult(requestBluetooth, 0);
}
bluetooth.startDiscovery();
myDiscoverer = new myOwnBroadcastReceiver();
/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */
if (bluetooth.isEnabled()) {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.getActivity().registerReceiver(myDiscoverer, filter);
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
}
};
void draw()
{
if(!foundDevice){
background(25, 25, 220);
}
if (bluetooth.isDiscovering()== false) {
bluetooth.startDiscovery();
}
if (foundDevice) {
background(0, 255, 0, 100);
fill(0);
//text("Found Device" +discoveredDeviceName+"\nRSSI: " + abs(rssi), width/2, (height/2+150));
if (devicesDiscovered.size() > 0) {
for (int i=0; i<devicesDiscovered.size(); i++) {
String myText = devicesDiscovered.get(i);
fill(0);
text(myText, width/2, height/2);
}
}
}
};
//@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { println(requestCode); if (requestCode==0) { if (resultCode == 1) { text("Bluetooth has been switched ON", 10, 10); } else { text("You need to turn Bluetooth ON !!!", 10, 10); } } }
/* Create a Broadcast Receiver that will later be used to receive the names of Bluetooth devices in range. / / This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
foundDevice=true;
println("Discovered: " );
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
devicesDiscovered.add(deviceName + "\n" + rssi);
println(devicesDiscovered);
} else {
println("no device");
}
} }
void onPause() { super.onPause(); if (myDiscoverer!=null) { bluetooth.cancelDiscovery();
println("je désenregistre");
} }
@ erwrow===
code snippet tested: it works (android 6.X) dont forget - 4 permissions (accessCoarseLocation, wifiState, wifiChange, netWorkstate) (i think now that you have not added these permissions, verify it!)
unregister your receiver onPause(), onStop(), on Destroy()
import java.util.List;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
Activity act;
Context context;
WifiManager wm;
List<ScanResult> results;
WifiInfo wifiInfo ;
boolean primeraVez = true, segundo = false;
List<ScanResult> result;
WifiManager wifiManager;
BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
IntentFilter IF = new IntentFilter(wifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
void setup()
{
fullScreen();
act = this.getActivity();
context = act.getApplicationContext();
wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
this.getActivity().registerReceiver(myDiscoverer, IF);
}
void draw()
{
textSize(height/18);
if (primeraVez)
{
primeraVez = false;
wifiManager.startScan();
}
if(segundo)
{
println(result);
segundo = false;
}
}
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
result = wifiManager.getScanResults();
if(result.size()>0){
//result = wifiManager.getScanResults();
segundo = true;
}
}
}
Thank you @kfrajer :) the screenshot you made mixes all the bug together into something... artsy ? ;)
I have one sort of depth buffer bug, ON SOME DEVICES, that clips together the 3 spheres I use
And then I have the other bug, triggers by onPause/onResume that "break" the colors (fill()) of the horizontal lines on the side of the globe AND the color of the blind that serves as the background of the "menu"
@PoYo===
try this=== BroadcastReceiver monRecepteur;
monRecepteur = new BroadcastReceiver() {
@ Override
public void onReceive(Context context, Intent intent) {
scanList = wifiManager.getScanResults();
for (ScanResult networkDevice : scanList) {
println(networkDevice.SSID);
updateItem(networkDevice.SSID, networkDevice.level);
}
bScanning = false;
wifiScanFinished();
getActivity().unregisterReceiver(monRecepteur);
monRecepteur = null;
}
};
getActivity().registerReceiver(monRecepteur, filter);
then unregister also in onPause() &&& onStop() &&& onDestroy() (adding a condtion: if(monRecepteur !=null){}
Thanks again @akenaton! It works now. A couple of things:
Here's my simple video player sketch, based on @akenaton 's excellent description. Thanks again!
(Can't get the forum's preprocessor not to convert "@Override" into an HTML ref to a forum user, so I changed it to "@ Override")(Thanks! @GoToLoop)
import android.media.MediaMetadataRetriever; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.app.Activity; import android.view.ViewGroup; import android.view.View; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.media.MediaMetadataRetriever; import android.media.MediaPlayer; import android.content.res.Resources; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.content.Context; AssetFileDescriptor afd; Context context; Activity act; SurfaceView mySurface; SurfaceHolder mSurfaceHolder; MediaMetadataRetriever metaRetriever; MediaPlayer mMediaPlayer; void setup() { size(400, 400, P2D); act = this.getActivity(); context = act.getApplicationContext(); Looper.prepare(); mMediaPlayer = new MediaPlayer(); try { afd = context.getAssets().openFd("Title.m4v"); MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever(); metaRetriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); String height = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); if (int(height) < 2) { throw new IOException(); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } mySurface = new SurfaceView(act); mSurfaceHolder = mySurface.getHolder(); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mSurfaceHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { mMediaPlayer.setDisplay(surfaceHolder); } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) { mMediaPlayer.setDisplay(surfaceHolder); } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { } } ); startVideo(); } void startVideo() { act.runOnUiThread(new Runnable() { public void run() { try { mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); mSurfaceHolder = mySurface.getHolder(); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mMediaPlayer.prepare(); // act.addContentView(mySurface, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); act.addContentView(mySurface, new ViewGroup.LayoutParams(400,400)); if (mMediaPlayer.isPlaying() == false) { mMediaPlayer.start(); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ); }; void draw() { } void onPause() { if (mMediaPlayer!=null) { mMediaPlayer.release(); mMediaPlayer = null; } super.onPause() ; } void onStop() { if (mMediaPlayer!=null) { mMediaPlayer.release(); mMediaPlayer = null; } super.onStop() ; } void onDestroy() { if (mMediaPlayer!=null) { mMediaPlayer.release(); mMediaPlayer = null; } super.onDestroy() ; } void onResume() { super.onResume() ; }
you can show video with android mediaplayer or android videoView (which is a kind of wrapper for mediaPlayer) following these steps (i choose mediaPlayer)::
imports:(some of them are useless)
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.app.Activity;
import android.view.ViewGroup;
import android.view.View;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
in setup():
Looper.prepare();
You find your video with fileDescriptor (like for the sound); your video is in your data folder; choose a standard format: mp4, 3Gp..., not mkv! - This is the first step and here you have to be sure that your video is found using MediaMetadataRetriever metaRetriever and getting height or width: if it returns 0 or -1, there is a problem!
you create a SurfaceView (mySurface) then you get the Holder from this surface; then you add callbacks to it (SurfaceCreated, surfaceChanged, surfaceDestroyed). In surfaceCreated you set your player.display to the surface: myPlayer.setDisplay(mySurface); the same for surfaceChanged (in case of config changes)
you create some method to add your video to surface view; it has to be a runnable (this.getactivity().runOnUiThread(new runnable)...In its run() you call another method which prepare the player in a standard way using the afd you have created at the beginning. At this moment your player is ok; you can add your surfaceview to the mainActivity; finally you start the player (if player().isPlaying == false){myPlayer.start();}
nothing to do in draw
in void onPause() or onDestroy() dont forget to release the player
try to do that and you can seee your video... tested with processing 3XXX and android mode 3; not tested with am 4 SONYXPERIA Z running kitKat nexus 7 TABLET running mmallow (6.0)
@coolphill===
you dont need ketai but:
your code cannot run for a lot of reasons:
first is that you dont get any context and so your sensor is null: you are in a fragment
second is that you never add a listener to your sensor manager: it cannot return any values
third is that you never clear your background in draw
here a snippet which will run (using your code and modifying it); in order to improve it you have to add onPause() && onResume() for registering and unregistering.
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
Context context;
SensorManager manager;
Sensor sensor;
float X1;
float Y1;
float Z1;
void setup() {
fullScreen();//better in settings()
context = getActivity().getApplicationContext();//get the context from the //main activity
manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
sensor = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
//verify wether the sensor is ok; if yes add a listener
if (sensor != null) {
manager.registerListener(listener, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
println("CAPTEUR", "ENREGISTREMENT DU CAPTEUR MAGNETIQUE");
} else {
println("SORRY!!!!-CE TELEPHONE N'A PAS DE CAPTEUR MAGNETIQUE");
}
};
//adding the listener (two methods are mandatory from the interface)
public SensorEventListener listener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event)
{
float[] val = event.values;
X1 = val[0];
Y1 = val[1];
Z1 = val[2];
}
};
void draw() {
background(255);//if you want to see your values
textSize(36);//phone res is probably too high for using default!
fill(255,0,0);
text(str(X1) + " " + str(Y1) + " " + str(Z1) , width/2, height/2);
}