update ui from another thread in android - java

i want to change UI in android.
my main class make a second class then second class call a method of main class.method in main class should update UI but program crash in runtime.
what should i do?
my main class :
public class FileObserverActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("new world");
MyFileObserver myFileObserver = new MyFileObserver("/sdcard/", this);
myFileObserver.startWatching();
}
String mySTR = "";
TextView tv ;
public void event(String absolutePath,String path,int event)
{
mySTR = absolutePath+path+"\t"+event;
tv.setText(mySTR); // program crash here!
}
}
and my second class :
public class MyFileObserver extends FileObserver
{
public String absolutePath;
FileObserverActivity fileobserveractivity;
public MyFileObserver(String path,FileObserverActivity foa)
{
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
fileobserveractivity = foa;
}
#Override
public void onEvent(int event, String path)
{
if (path == null)
{
return;
}
else if(event!=0)
{
fileobserveractivity.event(absolutePath, path, event);
}
else
{
return;
}
}
}

You can't call UI methods from threads other than the main thread. You should use Activity#runOnUiThread() method.
public class FileObserverActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("new world");
MyFileObserver myFileObserver = new MyFileObserver("/sdcard/", this);
myFileObserver.startWatching();
}
String mySTR = "";
TextView tv ;
public void event(String absolutePath,String path,int event)
{
runOnUiThread(action);
}
private Runnable action = new Runnable() {
#Override
public void run() {
mySTR = absolutePath+path+"\t"+event;
tv.setText(mySTR);
}
};
}
public class MyFileObserver extends FileObserver
{
public String absolutePath;
FileObserverActivity fileobserveractivity;
public MyFileObserver(String path,FileObserverActivity foa)
{
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
fileobserveractivity = foa;
}
#Override
public void onEvent(int event, String path)
{
if (path == null)
{
return;
}
else if(event!=0)
{
fileobserveractivity.event(absolutePath, path, event);
}
else
{
return;
}
}
}

Try as follows
public class FileObserverActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("new world");
MyFileObserver myFileObserver = new MyFileObserver("/sdcard/", this);
myFileObserver.startWatching();
registerReceiver(onBroadcast,new IntentFilter("abcd"));
}
String mySTR = "";
TextView tv ;
public void event(String absolutePath,String path,int event)
{
mySTR = absolutePath+path+"\t"+event;
tv.setText(mySTR); // program crash here!
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onBroadcast);
}
private final BroadcastReceiver onBroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context ctxt, Intent i) {
// do stuff to the UI
event(absolutePath, path, event);
}
};
}
public class MyFileObserver extends FileObserver
{
public String absolutePath;
FileObserverActivity fileobserveractivity;
public MyFileObserver(String path,FileObserverActivity foa)
{
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
fileobserveractivity = foa;
}
#Override
public void onEvent(int event, String path)
{
if (path == null)
{
return;
}
else if(event!=0)
{
context.sendBroadcast(new Intent("abcd"));
//fileobserveractivity.event(absolutePath, path, event);
}
else
{
return;
}
}
}

Related

How to fix ExoPlayer video Freeze 2.9.6

I use this code to play the full-screen video but I have a problem when it is video playing and moving from the main activity to the full-screen activity occurs freezing of the video for 2-3 seconds This problem occurs only with the releases after 2.8.3 only but with 2.8.0 works Video is smooth
code full: https://github.com/MATPOCKIH/ExoPlayerFullscreen
PlayerViewManager
public class PlayerViewManager {
private static final String TAG = "ExoPlayerViewManager";
public static final String EXTRA_VIDEO_URI = "video_uri";
private static Map<String, PlayerViewManager> instances = new HashMap<>();
private Uri videoUri;
public boolean isPlayerPlaying;
private boolean isMustPlaying;
private UniversalPlayerView universalPlayer;
public static PlayerViewManager getInstance(String videoUri) {
PlayerViewManager instance = instances.get(videoUri);
if (instance == null) {
instance = new PlayerViewManager(videoUri);
instances.put(videoUri, instance);
}
return instance;
}
private PlayerViewManager(String videoUri) {
this.videoUri = Uri.parse(videoUri);
}
public void preparePlayer(PlayerHolderView playerHolderView) {
if (playerHolderView == null) {
return;
}
if (universalPlayer == null) {
universalPlayer = createPlayer(playerHolderView.getContext());
isPlayerPlaying = true;
isMustPlaying = true;
}
universalPlayer.initialize(videoUri, playerHolderView);
}
public void releaseVideoPlayer() {
if (universalPlayer != null) {
universalPlayer.release();
}
universalPlayer = null;
}
public void goToBackground() {
if (universalPlayer != null /*&& !isMustPlaying*/) {
//isPlayerPlaying = player.getPlayWhenReady();
universalPlayer.pause();
}
}
public void goToForeground() {
if (universalPlayer != null && isMustPlaying) {
universalPlayer.play();
}
}
public void pausePlayer(){
if (universalPlayer != null) {
universalPlayer.pause();
isPlayerPlaying = false;
isMustPlaying = false;
}
}
public void playPlayer(){
if (universalPlayer != null) {
universalPlayer.play();
isPlayerPlaying = true;
isMustPlaying = true;
}
}
private UniversalPlayerView createPlayer(Context context){
if (videoUri.getScheme().startsWith("http")){
return new FaceterExoPlayerView(context);
}
return new FaceterExoPlayerView(context);
}
}
FaceterExoPlayerView
public class FaceterExoPlayerView extends UniversalPlayerView {
private Uri videoUri;
private DefaultDataSourceFactory dataSourceFactory;
private SimpleExoPlayer player;
private PlayerView exoPlayerView;
private Context context;
public FaceterExoPlayerView(Context context) {
this.context = context;
}
#Override
public void initialize(Uri videoUri, PlayerHolderView playerHolderView) {
if (playerHolderView == null || videoUri == null)
return;
exoPlayerView = playerHolderView.findViewById(R.id.exo_player);
if (player == null) {
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "faceter"));
MediaSource videoSource = buildMediaSource(videoUri, null);
player.prepare(videoSource);
}
player.clearVideoSurface();
player.setVideoTextureView((TextureView) exoPlayerView.getVideoSurfaceView());
exoPlayerView.setPlayer(player);
exoPlayerView.hideController();
setResizeModeFill(playerHolderView.isResizeModeFill());
}
#Override
public void play() {
player.setPlayWhenReady(true);
}
#Override
public void pause() {
player.setPlayWhenReady(false);
}
#SuppressWarnings("unchecked")
private MediaSource buildMediaSource(Uri uri, #Nullable String overrideExtension) {
int type = Util.inferContentType(uri, overrideExtension);
switch (type) {
/*case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new DashManifestParser(), (List<RepresentationKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new SsManifestParser(), (List<StreamKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);*/
case C.TYPE_HLS:
return new HlsMediaSource.Factory(dataSourceFactory)
/*.setPlaylistParser(
new FilteringManifestParser<>(
new HlsPlaylistParser(), (List<RenditionKey>) getOfflineStreamKeys(uri)))*/
.createMediaSource(uri);
case C.TYPE_OTHER:
return new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
#Override
public void release() {
if (player != null) {
player.release();
}
player = null;
}
#Override
public void setResizeModeFill(boolean isResizeModeFill) {
if (isResizeModeFill) {
exoPlayerView.setResizeMode(RESIZE_MODE_FILL);
} else {
exoPlayerView.setResizeMode(RESIZE_MODE_FIT);
}
}
}
PlayerHolderView.java
public class PlayerHolderView extends FrameLayout {
private String videoUrl;
private boolean isResizeModeFill = true;
private OnUserInteractionListener onUserInteractionListener;
public PlayerHolderView(#NonNull Context context) {
super(context);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.layout_player, this, true);
View controlView = this.findViewById(R.id.exo_controller);
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).pausePlayer();
}
});
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FullscreenVideoActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
getContext().startActivity(intent);
}
});
MainActivity
public class MainActivity extends AppCompatActivity {
private List<PlayerHolderView> playerHolders = new ArrayList<>();
private List<TextView> links = new ArrayList<>();
private List<String> mVideoUrls = new ArrayList<>(
Arrays.asList(
//"http://10.110.3.30/api/Playlists/6a3ecad7-e744-446f-9341-0e0ba834de63?from=2018-09-20&to=2018-09-21"
"https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/hls/TearsOfSteel.m3u8",
"http://redirector.c.youtube.com/videoplayback?id=604ed5ce52eda7ee&itag=22&source=youtube&sparams=ip,ipbits,expire,source,id&ip=0.0.0.0&ipbits=0&expire=19000000000&signature=513F28C7FDCBEC60A66C86C9A393556C99DC47FB.04C88036EEE12565A1ED864A875A58F15D8B5300&key=ik0",
"https://html5demos.com/assets/dizzy.mp4"
//"https://cdn.faceter.io/hls/ab196789-8876-4854-82f3-087e5682d013",
//"https://cdn.faceter.io/hls/65d1c673-6a63-44c8-836b-132449c9462a"
)
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playerHolders.add((PlayerHolderView) findViewById(R.id.holder1));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder2));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder3));
links.add((TextView) findViewById(R.id.title1));
links.add((TextView) findViewById(R.id.title2));
links.add((TextView) findViewById(R.id.title3));
}
#Override
public void onResume() {
super.onResume();
int i = 0;
for (final String videoUrl : mVideoUrls) {
playerHolders.get(i).setupPlayerView(videoUrl);
playerHolders.get(i).setOnUserInteractionListener(this);
links.get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVideoTitleClicked(videoUrl);
}
});
i++;
}
}
#Override
public void onPause() {
super.onPause();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).goToBackground();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).releaseVideoPlayer();
}
}
public void onVideoTitleClicked(String videoUrl) {
Intent intent = new Intent(getBaseContext(), DetailActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
startActivity(intent);
}
}
FullscreenVideoActivity
public class FullscreenVideoActivity extends AppCompatActivity {
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler();
private View mContentView;
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of
// API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
private String mVideoUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_video);
mContentView = findViewById(R.id.enclosing_layout);
PlayerHolderView playerHolderView = findViewById(R.id.player_holder);
playerHolderView.setResizeModeFill(false);
mVideoUri = getIntent().getStringExtra(PlayerViewManager.EXTRA_VIDEO_URI);
PlayerViewManager.getInstance(mVideoUri).preparePlayer(playerHolderView);
/*
// Set the fullscreen button to "close fullscreen" icon
View controlView = playerView.findViewById(R.id.exo_controller);
ImageView fullscreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon);
fullscreenIcon.setImageResource(R.drawable.exo_controls_fullscreen_exit);
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).pausePlayer();
}
});*/
}
#Override
public void onResume() {
super.onResume();
PlayerViewManager.getInstance(mVideoUri).goToForeground();
}
#Override
public void onPause() {
super.onPause();
PlayerViewManager.getInstance(mVideoUri).goToBackground();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide();
}
private void hide() {
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
/**
* Schedules a call to hide() in delay milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide() {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, 100);
}
}
Just try out this code for video freeze problem:
#Override
public void play() {
player.setPlayWhenReady(true);
player.getPlaybackState();
}
#Override
public void pause() {
player.setPlayWhenReady(false);
player.getPlaybackState();
}
Here player.getPlaybackState(); is help full to get it to back state.

How can disable hardware HomeKey and BackKey and Recent Butoom in Android Programitcaly

I'm setting a new app and want to disable hardware key like home,back and recent key in my app. I found some code in stackoverflow but none of them work.
Is it possible to disable hardware key?
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
}
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
}
}
do nothing in onBackPressed()
#Override
public void onBackPressed() {
}
add this in manifest
<uses-permission android:name="android.permission.REORDER_TASKS" />
and add this in onPause()
#Override
protected void onPause() {
super.onPause();
ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.moveTaskToFront(getTaskId(), 0);
}
In your MainActivity -
#Override
public void onBackPressed() {
// super.onBackPressed(); commented this line in order to disable back press
//Write your code here
Toast.makeText(getApplicationContext(), "Back press disabled!", Toast.LENGTH_SHORT).show();
}
You can not block Recent and Home but you can restart activity if user click on Home.
Here is example
HomeWatcher Class
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
final String SYSTEM_DIALOG_REASON_LONG_PRESS = "assist";
final String SYSTEM_DIALOG_REASON_VOICE_INTERACTION = "voiceinteraction";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_LONG_PRESS)) {
mListener.onHomeLongPressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_VOICE_INTERACTION)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
OnHomePressedListener interface
public interface OnHomePressedListener {
void onHomePressed();
void onHomeLongPressed();
}
In Your Main Activity
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
Log.d("Pressed", "Home Button Pressed");
}
#Override
public void onHomeLongPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Log.d("LongPressed", "Home Long Button Pressed");
}
});
mHomeWatcher.startWatch();

IOIOActivity and AppCompactActivity

I'm not experienced in Java development and migrating from Eclipse. I don't know how to use the nested classes in my case where I need to extend AppCompactActivity and IOIOActivity. Considering, I have another inner class Looper already extending another class. The code below isn't running what is inside Testing class. Can someone help me about how to execute my inner class, which is Testing class.
My code:
public class MainActivity extends AppCompatActivity {
private class Testing extends IOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
}
Thankss
I found my answer and I would like to share it with you all for the future. This is for starting a new IOIOActivity in Android Studio. IOIO developers haven't written the official IOIO code for AppCompactActivity yet. After couple of days trying, its finally tested and working with IOIO led.
Create a new Class file called AppCompactIOIOActivity (I just like that name) in your package. Note: all credits to Ytai. IOIO code from App507
public class AppCompactIOIOActivity extends AppCompatActivity implements IOIOLooperProvider {
private final IOIOAndroidApplicationHelper helper_ = new IOIOAndroidApplicationHelper(this, this);
public AppCompactIOIOActivity() {
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.helper_.create();
}
protected void onDestroy() {
this.helper_.destroy();
super.onDestroy();
}
protected void onStart() {
super.onStart();
this.helper_.start();
}
protected void onStop() {
this.helper_.stop();
super.onStop();
}
#SuppressLint("WrongConstant")
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if((intent.getFlags() & 268435456) != 0) {
this.helper_.restart();
}
}
protected IOIOLooper createIOIOLooper() {
throw new RuntimeException("Client must override one of the createIOIOLooper overloads!");
}
public IOIOLooper createIOIOLooper(String connectionType, Object extra) {
return this.createIOIOLooper();
}
}
Then in your MainActivity
public class MainActivity extends AppCompactIOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
Don't forget to add your resources and dependances from IOIO developers. Good luck!

Using constructor to call a handler to a activity from another class

I am trying to communicate with USB on android using input-output stream, using constructor if I use the handler individually it communicates without any problem, but if I use a common constructor it crashes the app saying null pointer exception hope I am doing some blunder mistake but don't know where I did that mistake
and the code as follows
public class BasicAccessoryDemo extends Activity implements View.OnClickListener {
Usb_Communciation usbCom = new Usb_Communciation(this, getIntent());
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mycontrol, close_command;
mycontrol = (Button) findViewById(R.id.send_command);
mycontrol.setOnClickListener(this);
close_command = (Button) findViewById(R.id.close_command);
close_command.setOnClickListener(this);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_command:
byte[] commandPacket = new byte[2];
commandPacket[0] =0x12;
commandPacket[1] =0x34;
usbCom.Send_message(commandPacket);
break;
case R.id.close_command:
byte[] commandPackets = new byte[2];
commandPackets[0] = 0;
commandPackets[1] = 0;
usbCom.Send_message(commandPackets);
break;
}
}
}
and communication class
public class Usb_Communciation {
public final static int USBAccessoryWhat = 0;
public int firmwareProtocol = 0;
public static USBAccessoryManager accessoryManager;
public static String TAG = "MICROCHIP";
public static final int APP_CONNECT = (int) 0xAE;
public boolean deviceAttached = false;
public Usb_Communciation(Context mContext, Intent intent) {
accessoryManager = new USBAccessoryManager(handler, USBAccessoryWhat);
accessoryManager.enable(mContext, intent);
}
public void Send_message(byte[] data) {
try {
accessoryManager.write(data);
} catch (Exception e) {
Log.d(TAG,
"USBAccessoryManager:write():IOException: arasu "
+ e.toString());
e.printStackTrace();
}
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
byte[] commandPacket = new byte[64];
byte[] WriteValue = new byte[2];
switch (msg.what) {
//Something inside
} //switch
} //handleMessage
}; //handler
public int getFirmwareProtocol(String version) {
String major = "0";
int positionOfDot;
positionOfDot = version.indexOf('.');
if (positionOfDot != -1) {
major = version.substring(0, positionOfDot);
}
return new Integer(major).intValue();
}
}
and the enable method on USB accessory manager class
public RETURN_CODES enable(Context context, Intent intent) {
//something inside
}
and the error shows on the part of the activity and the same constructor on the usb_Communcation class
Usb_Communciation usbCom = new Usb_Communciation(this, getIntent());
Try this:
Usb_Communciation usbCom;
#Override
public void onCreate(Bundle savedInstanceState) {
usbCom = new Usb_Communciation(this, getIntent());
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mycontrol, close_command;
mycontrol = (Button) findViewById(R.id.send_command);
mycontrol.setOnClickListener(this);
close_command = (Button) findViewById(R.id.close_command);
close_command.setOnClickListener(this);
}

Unable to display String from Intent

At the moment when running I get only one text displayed Wrong_answer.
public class AnswerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
TextView textViewDisplayResult = (TextView) findViewById(R.id.text_view_display_result);
textViewDisplayResult.setText(getIntent().getExtras().getString("KEY_ALL_CHECKED"));
textViewDisplayResult.setText(getIntent().getBooleanExtra("KEY_ANSWER", false)?R.string.Good_answer:R.string.Wrong_answer);
}
POST UPDATE
public class MainActivity extends AppCompatActivity {
private static int NUMBER_OF_QUESTIONS = 3;
static boolean[] answer = new boolean[NUMBER_OF_QUESTIONS];
static boolean[] checked = new boolean[NUMBER_OF_QUESTIONS];
static boolean[] isAnswered = new boolean[NUMBER_OF_QUESTIONS];
final Intent intent = new Intent(MainActivity.this, AnswerActivity.class);
buttonCheckAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!allAnswersChecked())
intent.putExtra("KEY_ALL_CHECKED", R.string.text_not_checked);
else if (checkAnswers())
intent.putExtra("KEY_ANSWER", R.string.Good_answer);
else
intent.putExtra("KEY_ANSWER", R.string.Wrong_answer);
startActivity(intent);
}
});
public static void checkSelected() {
for (boolean radioChecked : checked) {
if (radioChecked) {
buttonCheckAnswer.setVisibility(View.VISIBLE);
break;
}
}
}
private boolean checkAnswers() {
for (boolean radioAnswer : answer) {
if (!radioAnswer) {
return false;
}
}
return true;
}
private boolean allAnswersChecked() {
for (boolean radioAnswer : isAnswered) {
if (!radioAnswer) {
return false;
}
}
return true;
}
and AnswerActivity
public class AnswerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
TextView textViewDisplayResult = (TextView) findViewById(R.id.text_view_display_result);
textViewDisplayResult.setText(getIntent().getExtras().getString("KEY_ALL_CHECKED"));
textViewDisplayResult.setText(getIntent().getBooleanExtra("KEY_ANSWER", false)?getString(R.string.Good_answer):getString(R.string.Wrong_answer));
}
}
Second setText will overwrite your first setText value.
....
String x = getIntent().getExtras().getString("KEY_ALL_CHECKED");
textViewDisplayResult.setText(getIntent().getBooleanExtra("KEY_ANSWER", false) ? x +" "+ R.string.Good_answer: x +" "+ R.string.Wrong_answer);
textViewDisplayResult will always overwrite.
If you want both to display in same textView you just need to append the text like below:
textViewDisplayResult.setText(getIntent().getExtras().getString("KEY_ALL_CHECKED"));
textViewDisplayResult.append(getIntent().getBooleanExtra("KEY_ANSWER", false)?getString(R.string.Good_answer):getString(R.string.Wrong_answer));
This will display your both result in same textView.

Categories

Resources