Google Real-time Multiplayer on Android - android

I am having trouble with my app that uses Google's Real-time Multiplayer. When you launch the app, it just crashes. I added the crash log at the bottom...
I was able to find out that the problem was when I called mGoogleApiClient.connect();
Here is my code:
//(Your package here:)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.birdprograms.multiplayer.BaseGameUtils.src.main.java.com.google.example.games.basegameutils.BaseGameUtils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.GamesStatusCodes;
import com.google.android.gms.games.multiplayer.Invitation;
import com.google.android.gms.games.multiplayer.OnInvitationReceivedListener;
import com.google.android.gms.games.multiplayer.Participant;
import com.google.android.gms.games.multiplayer.realtime.RealTimeMessage;
import com.google.android.gms.games.multiplayer.realtime.RealTimeMessageReceivedListener;
import com.google.android.gms.games.multiplayer.realtime.Room;
import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
import com.google.android.gms.games.multiplayer.realtime.RoomStatusUpdateListener;
import com.google.android.gms.games.multiplayer.realtime.RoomUpdateListener;
import com.google.android.gms.plus.Plus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MyActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener, RealTimeMessageReceivedListener, RoomUpdateListener, RoomStatusUpdateListener, OnInvitationReceivedListener{
private static final int RC_SIGN_IN = 9001;
private GoogleApiClient mGoogleApiClient;
private boolean mResolvingConnectionFailure = false;
private boolean mSignInClicked = false;
private boolean mAutoStartSignInFlow = true;
String mRoomId = null;
ArrayList<Participant> mParrticipants = null;
String mMyId = null;
byte[] mMsgBuf = new byte[2];
private TextView textView;
private TextView myscoretxt;
private TextView urscoretxt;
final static int[] CLICKALBES = {
R.id.button,R.id.button2,R.id.button3
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.build();
for (int id : CLICKALBES){
findViewById(id).setOnClickListener(this);
}
}
private void startQuickGame(){
final int MIN_OPPONENTS = 1, MAX_OPPONENTS = 1;
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(MIN_OPPONENTS,
MAX_OPPONENTS,0);
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder(this);
rtmConfigBuilder.setMessageReceivedListener(this);
rtmConfigBuilder.setRoomStatusUpdateListener(this);
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
changedisplay(1);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
resetGameVars();
Games.RealTimeMultiplayer.create(mGoogleApiClient,rtmConfigBuilder.build());
}
#Override
public void onActivityResult(int requestCode, int responseCode,Intent intent){
super.onActivityResult(requestCode,responseCode,intent);
switch(requestCode){
case RC_SIGN_IN:
mSignInClicked = false;
mResolvingConnectionFailure = false;
if(responseCode == RESULT_OK){
mGoogleApiClient.connect();
} else {
BaseGameUtils.showActivityResultError(this, requestCode, requestCode, R.string.signin_other_error);
}
break;
};
super.onActivityResult(requestCode,responseCode,intent);
}
#Override
public void onStop(){
leaveRoom();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
changedisplay(0);
}
super.onStop();
}
#Override
public void onStart(){
changedisplay(0);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()){
} else {
mGoogleApiClient.connect();
}
super.onStart();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent e){
if (keyCode == KeyEvent.KEYCODE_BACK && findViewById(R.id.button).getVisibility() == View.VISIBLE){
leaveRoom();
return true;
}
return super.onKeyDown(keyCode, e);
}
void leaveRoom(){
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
resetGameVars();
if(mRoomId != null){
Games.RealTimeMultiplayer.leave(mGoogleApiClient, this, mRoomId);
mRoomId = null;
findViewById(R.id.button).setVisibility(View.VISIBLE);
changedisplay(0);
textView = (TextView)findViewById(R.id.textView3);
myscoretxt = (TextView)findViewById(R.id.textView);
urscoretxt = (TextView)findViewById(R.id.textView2);
}
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
mSignInClicked = true;
mGoogleApiClient.connect();
break;
case R.id.button2:
startQuickGame();
startGame(true);
break;
case R.id.button3:
scoreOnePoint();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mResolvingConnectionFailure){
return;
}
if (mSignInClicked || mAutoStartSignInFlow){
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = BaseGameUtils.resolveConnectionFailure(this,mGoogleApiClient,connectionResult,RC_SIGN_IN,getString(R.string.signin_other_error));
}
changedisplay(1);
}
void updateRoom(Room room){
if(room != null){
mParrticipants = room.getParticipants();
}
if (mParrticipants != null){
updatePeerScoresDisplay();
}
}
#Override
public void onConnectedToRoom(Room room) {
mRoomId = room.getRoomId();
mParrticipants = room.getParticipants();
mMyId = room.getParticipantId(Games.Players.getCurrentPlayerId(mGoogleApiClient));
}
#Override
public void onDisconnectedFromRoom(Room room) {
mRoomId = null;
showGameError();
}
void showGameError(){
BaseGameUtils.makeSimpleDialog(this,getString(R.string.game_problem));
changedisplay(0);
}
#Override
public void onJoinedRoom(int i, Room room) {
if(i != GamesStatusCodes.STATUS_OK){
showGameError();
return;
}
}
#Override
public void onRoomConnected(int i, Room room) {
if(i != GamesStatusCodes.STATUS_OK){
showGameError();
return;
}
updateRoom(room);
}
int mSecondsLeft = -1;
final static int GAME_DDURATION = 20;
int mScore = 0;
void resetGameVars(){
mSecondsLeft = GAME_DDURATION;
mScore = 0;
mParticipantScore.clear();
mFinishedParticipants.clear();
}
void startGame(boolean multiplayer){
updateScoreDisplay();
broadcastScore(false);
changedisplay(1);
final Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
if (mSecondsLeft <= 0)
return;
gameTick();
h.postDelayed(this, 1000);
}
}, 1000);
}
void gameTick(){
if(mSecondsLeft > 0)
--mSecondsLeft;
textView.setText("Time Left: "+mSecondsLeft+" seconds");
if (mSecondsLeft <= 0){
changedisplay(0);
broadcastScore(true);
}
}
void scoreOnePoint(){
if(mSecondsLeft <= 0)
return;
++mScore;
updateScoreDisplay();
updatePeerScoresDisplay();
broadcastScore(false);
}
Map<String, Integer> mParticipantScore = new HashMap<String, Integer>();
Set<String> mFinishedParticipants = new HashSet<String>();
#Override
public void onRealTimeMessageReceived(RealTimeMessage realTimeMessage) {
byte[] buf = realTimeMessage.getMessageData();
String sender = realTimeMessage.getSenderParticipantId();
if(buf[0] == 'F' || buf[0] == 'U'){
int existingScore = mParticipantScore.containsKey(sender) ?
mParticipantScore.get(sender) : 0;
int thisScore = (int) buf[1];
if(thisScore > existingScore){
mParticipantScore.put(sender, thisScore);
}
updatePeerScoresDisplay();
if((char) buf[0] == 'F'){
mFinishedParticipants.add(realTimeMessage.getSenderParticipantId());
}
}
}
void broadcastScore(boolean finalScore){
mMsgBuf[0] = (byte) (finalScore ? 'F' : 'U');
mMsgBuf[1] = (byte) mScore;
for(Participant p : mParrticipants){
if(p.getParticipantId().equals(mMyId))
continue;
if (p.getStatus() != Participant.STATUS_JOINED)
continue;
if (finalScore){
Games.RealTimeMultiplayer.sendReliableMessage(mGoogleApiClient, null, mMsgBuf, mRoomId, p.getParticipantId());
} else {
Games.RealTimeMultiplayer.sendUnreliableMessage(mGoogleApiClient, mMsgBuf, mRoomId, p.getParticipantId());
}
}
}
void updateScoreDisplay(){
myscoretxt.setText("Your Score: "+fomatScore(mScore));
}
String fomatScore(int i){
if(i<0)
i=0;
String s = String.valueOf(i);
return s.length() == 1 ? "00" + s : s.length() == 2 ? "0" + s : s;
}
void updatePeerScoresDisplay(){
if(mRoomId != null){
for (Participant p : mParrticipants){
String pid = p.getParticipantId();
if(pid.equals(mMyId))
continue;
if (p.getStatus() != Participant.STATUS_JOINED)
continue;
int score = mParticipantScore.containsKey(pid) ? mParticipantScore.get(pid) : 0;
urscoretxt.setText("Opponents Score: "+fomatScore(score));
}
}
}
void changedisplay(int i){
if(i == 0){
findViewById(R.id.button).setVisibility(View.VISIBLE);
findViewById(R.id.button2).setVisibility(View.VISIBLE);
findViewById(R.id.button3).setVisibility(View.GONE);
findViewById(R.id.textView).setVisibility(View.GONE);
findViewById(R.id.textView2).setVisibility(View.GONE);
findViewById(R.id.textView3).setVisibility(View.GONE);
}
else{
findViewById(R.id.button).setVisibility(View.GONE);
findViewById(R.id.button2).setVisibility(View.GONE);
findViewById(R.id.button3).setVisibility(View.VISIBLE);
findViewById(R.id.textView).setVisibility(View.VISIBLE);
findViewById(R.id.textView2).setVisibility(View.VISIBLE);
findViewById(R.id.textView3).setVisibility(View.VISIBLE);
}
}
}
I have removed several callbacks for readers sake that did not cause the problem for sure!
If you read the whole thing, then thank you for your patience. :)
Any help, or suggestions would be helpful. Thanks!
-Nathan
Edit
Here is the crash log:
04-22 09:28:00.320 19247-19247/com.birdprograms.multiplayerdemo E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.birdprograms.multiplayerdemo, PID: 19247
java.lang.IllegalStateException: A fatal developer error has occurred. Check the logs for further information.
at com.google.android.gms.internal.jl$h.b(Unknown Source)
at com.google.android.gms.internal.jl$h.g(Unknown Source)
at com.google.android.gms.internal.jl$b.hy(Unknown Source)
at com.google.android.gms.internal.jl$a.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5323)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)

Your manifest is missing
<meta-data
android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
// this is required if your RequestedClients is using AppStateManager.SCOPE_APP_STATE
<meta-data
android:name="com.google.android.gms.games.appstate.APP_ID"
android:value="#string/app_id" />

Related

Google Achievements Unlock But Don't Save

I added achievements to my Google Play game following Google's tutorial. They unlock fine and if I display achievements in-game immediately they show up. If I quit the game and go to the Google Game's app they don't show up and they disappear from in-game also. Any ideas? I've tried multiple accounts. Thanks!
package com.b1stable.tth;
import java.io.File;
import java.io.FileFilter;
import java.util.Locale;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.FileSystems;
import java.util.Vector;
import android.os.Bundle;
import android.os.Build;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Vibrator;
import android.os.VibrationEffect;
import android.util.Log;
import android.view.Surface;
import android.view.Gravity;
import org.libsdl.app.SDLActivity;
import com.b1stable.tth.License_Viewer_Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.games.AchievementsClient;
import com.google.android.gms.games.AnnotatedData;
import com.google.android.gms.games.EventsClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.GamesClient;
import com.google.android.gms.games.LeaderboardsClient;
import com.google.android.gms.games.Player;
import com.google.android.gms.games.PlayersClient;
import com.google.android.gms.games.event.Event;
import com.google.android.gms.games.event.EventBuffer;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Task.*;
public class TTH_Activity extends SDLActivity
{
final static int LICENSE_REQUEST = 1;
native static void resume_after_showing_license();
native static void resume_after_showing_achievements();
native static void pause();
native static void resume();
// Client used to sign in with Google APIs
private GoogleSignInClient mGoogleSignInClient;
private AchievementsClient mAchievementsClient = null;
private boolean signin_failed = false;
// request codes we use when invoking an external activity
private static final int RC_UNUSED = 5001;
private static final int RC_SIGN_IN = 9001;
// This is so the screen is never cleared pure black, only shim::black (r:35, g:30, b:60)
static boolean paused = false;
private static final String TAG = "TTH";
#Override
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LICENSE_REQUEST) {
if (data != null) {
if (resultCode == RESULT_OK && data.getExtras().getString("MESSAGE").equals("OK")) {
show_license_result = 0;
}
else if (resultCode == RESULT_CANCELED && data.getExtras().getString("MESSAGE").equals("FAIL")) {
show_license_result = 1;
}
else {
show_license_result = 1;
}
}
else {
show_license_result = 1;
}
resume_after_showing_license();
}
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// The signed in account is stored in the result.
GoogleSignInAccount signedInAccount = result.getSignInAccount();
onConnected(signedInAccount);
}
else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = "An error occurred!";
}
new AlertDialog.Builder(this).setMessage(message).setNeutralButton(android.R.string.ok, null).show();
onDisconnected();
}
}
}
public void onStart() {
super.onStart();
}
#Override
public void onStop()
{
super.onStop();
pause();
}
#Override
public void onRestart()
{
super.onRestart();
resume();
}
#Override
public void onResume()
{
super.onResume();
signInSilently();
}
#Override
public void onPause()
{
super.onPause();
mAchievementsClient = null;
}
#Override
public void onPostResume()
{
super.onPostResume();
paused = true;
}
public void logString(String s)
{
Log.d("TTH", s);
}
public String getAppdataDir()
{
return getFilesDir().getAbsolutePath();
}
public String getSDCardDir()
{
File f = getExternalFilesDir(null);
if (f != null) {
return f.getAbsolutePath();
}
else {
return getFilesDir().getAbsolutePath();
}
}
static int show_license_result;
public void showLicense()
{
show_license_result = -1;
Intent intent = new Intent(this, License_Viewer_Activity.class);
startActivityForResult(intent, LICENSE_REQUEST);
}
public int getShowLicenseResult()
{
return show_license_result;
}
/*
public void openURL(String url)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
*/
public void rumble(int milliseconds)
{
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
if (v != null && v.hasVibrator()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(milliseconds, VibrationEffect.DEFAULT_AMPLITUDE));
}
else {
v.vibrate(milliseconds);
}
}
}
public boolean has_touchscreen()
{
return getPackageManager().hasSystemFeature("android.hardware.touchscreen");
}
public boolean has_vibrator()
{
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
return v.hasVibrator();
}
else {
return false;
}
}
public void start_draw()
{
if (paused) {
paused = false;
}
}
public String get_android_language()
{
return Locale.getDefault().getLanguage();
}
private static File[] list_dir_files = null;
public void list_dir_start(String path)
{
try {
int slash = path.lastIndexOf('/');
final String glob = path.substring(slash+1).replace("*", ".*"); // +1 works even if not found (-1+1 == 0)
String dir = path.substring(0, slash);
File f = new File(dir);
list_dir_files = f.listFiles(new FileFilter() {
public boolean accept(File f)
{
try {
if (f.getName().matches(glob)) {
return true;
}
else {
return false;
}
}
catch (Exception e) {
Log.d("TTH", "list_dir_start FileFilter throwing " + e.getMessage());
return false;
}
}
});
}
catch (Exception e) {
list_dir_files = null;
Log.d("TTH", "list_dir_start throwing " + e.getMessage());
}
}
public String list_dir_next()
{
if (list_dir_files == null) {
return "";
}
else if (list_dir_files.length == 0) {
list_dir_files = null;
return "";
}
else {
File f = list_dir_files[0];
String name = f.getName();
if (list_dir_files.length == 1) {
list_dir_files = null;
}
else {
File[] new_list = new File[list_dir_files.length-1];
for (int i = 1; i < list_dir_files.length; i++) {
new_list[i-1] = list_dir_files[i];
}
list_dir_files = new_list;
}
return name;
}
}
private static final String ARC_DEVICE_PATTERN = ".+_cheets|cheets_.+";
public boolean is_chromebook()
{
// Google uses this, so should work?
return Build.DEVICE != null && Build.DEVICE.matches(ARC_DEVICE_PATTERN);
}
private static final int RC_ACHIEVEMENT_UI = 9003;
public boolean show_achievements()
{
if (mAchievementsClient == null) {
return false;
}
mAchievementsClient.getAchievementsIntent().addOnSuccessListener(new OnSuccessListener<Intent>() {
#Override
public void onSuccess(Intent intent) {
startActivityForResult(intent, RC_ACHIEVEMENT_UI);
resume_after_showing_achievements();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
resume_after_showing_achievements();
}
}).addOnCompleteListener(new OnCompleteListener<Intent>() {
#Override
public void onComplete(Task<Intent> task) {
resume_after_showing_achievements();
}
});
return true;
}
public void achieve(String id)
{
if (mAchievementsClient != null) {
mAchievementsClient.unlock(id);
}
}
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
private void signInSilently() {
if (signin_failed == true || mAchievementsClient != null) {
return;
}
GoogleSignInOptions signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN;
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (GoogleSignIn.hasPermissions(account, signInOptions.getScopeArray())) {
// Already signed in.
// The signed in account is stored in the 'account' variable.
//GoogleSignInAccount signedInAccount = account;
onConnected(account);
}
else {
// Haven't been signed-in before. Try the silent sign-in first.
GoogleSignInClient signInClient = GoogleSignIn.getClient(this, signInOptions);
signInClient.silentSignIn().addOnCompleteListener(
this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
// The signed in account is stored in the task's result.
GoogleSignInAccount signedInAccount = task.getResult();
onConnected(signedInAccount);
}
else {
// Player will need to sign-in explicitly using via UI.
// See [sign-in best practices](http://developers.google.com/games/services/checklist) for guidance on how and when to implement Interactive Sign-in,
// and [Performing Interactive Sign-in](http://developers.google.com/games/services/android/signin#performing_interactive_sign-in) for details on how to implement
// Interactive Sign-in.
startSignInIntent();
}
}
}
);
}
}
public void start_google_play_games_services() {
/*
runOnUiThread(new Runnable() {
public void run() {
signInSilently();
}
});
*/
}
private void onConnected(GoogleSignInAccount googleSignInAccount) {
Log.d(TAG, "onConnected(): connected to Google APIs");
GamesClient gamesClient = Games.getGamesClient(this, googleSignInAccount);
gamesClient.setViewForPopups(findViewById(android.R.id.content));
gamesClient.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
mAchievementsClient = Games.getAchievementsClient(this, googleSignInAccount);
}
private void onDisconnected() {
Log.d(TAG, "onDisconnected()");
mAchievementsClient = null;
signin_failed = true;
}
}

Webrtc in Vuzix m300

I finished every configuration and tested on multiple Android devices, everything works fine, but when I test the streaming with the Vuzix M300, which is a smart glass run on Android 6, the streaming didn't happen and not even getting any error in Android Studio.Kindly help me out I am new in Vuzix m300.
Below is the java code:
package fr.pchab.androidrtc;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;
import org.json.JSONException;
import org.webrtc.MediaStream;
import org.webrtc.VideoRenderer;
import org.webrtc.VideoRendererGui;
import fr.pchab.webrtcclient.WebRtcClient;
import fr.pchab.webrtcclient.PeerConnectionParameters;
import java.util.List;
import static android.Manifest.permission.MODIFY_AUDIO_SETTINGS;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WAKE_LOCK;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.Manifest.permission.CAMERA;
public class RtcActivity extends Activity implements WebRtcClient.RtcListener {
private static final int PERMISSION_REQUEST_CODE = 0;
private final static int VIDEO_CALL_SENT = 666;
private static final String VIDEO_CODEC_VP9 = "VP9";
private static final String AUDIO_CODEC_OPUS = "opus";
// Local preview screen position before call is connected.
private static final int LOCAL_X_CONNECTING = 0;
private static final int LOCAL_Y_CONNECTING = 0;
private static final int LOCAL_WIDTH_CONNECTING = 100;
private static final int LOCAL_HEIGHT_CONNECTING = 100;
// Local preview screen position after call is connected.
private static final int LOCAL_X_CONNECTED = 72;
private static final int LOCAL_Y_CONNECTED = 72;
private static final int LOCAL_WIDTH_CONNECTED = 25;
private static final int LOCAL_HEIGHT_CONNECTED = 25;
// Remote video screen position
private static final int REMOTE_X = 0;
private static final int REMOTE_Y = 0;
private static final int REMOTE_WIDTH = 100;
private static final int REMOTE_HEIGHT = 100;
private VideoRendererGui.ScalingType scalingType = VideoRendererGui.ScalingType.SCALE_ASPECT_FILL;
private GLSurfaceView vsv;
private VideoRenderer.Callbacks localRender;
private VideoRenderer.Callbacks remoteRender;
private WebRtcClient client;
private String mSocketAddress;
private String callerId;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(
LayoutParams.FLAG_FULLSCREEN
| LayoutParams.FLAG_KEEP_SCREEN_ON
| LayoutParams.FLAG_DISMISS_KEYGUARD
| LayoutParams.FLAG_SHOW_WHEN_LOCKED
| LayoutParams.FLAG_TURN_SCREEN_ON);
setContentView(R.layout.main);
requestPermission();
mSocketAddress = "http://" + getResources().getString(R.string.host);
mSocketAddress += (":" + getResources().getString(R.string.port) + "/");
vsv = (GLSurfaceView) findViewById(R.id.glview_call);
vsv.setPreserveEGLContextOnPause(true);
vsv.setKeepScreenOn(true);
VideoRendererGui.setView(vsv, new Runnable() {
#Override
public void run() {
init();
}
});
// local and remote render
remoteRender = VideoRendererGui.create(
REMOTE_X, REMOTE_Y,
REMOTE_WIDTH, REMOTE_HEIGHT, scalingType, false);
localRender = VideoRendererGui.create(
LOCAL_X_CONNECTING, LOCAL_Y_CONNECTING,
LOCAL_WIDTH_CONNECTING, LOCAL_HEIGHT_CONNECTING, scalingType, true);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
final List<String> segments = intent.getData().getPathSegments();
callerId = segments.get(0);
}
}catch (Exception e){
System.out.print("error in opening activity"+e);
}
}
private void init() {
Point displaySize = new Point();
getWindowManager().getDefaultDisplay().getSize(displaySize);
PeerConnectionParameters params = new PeerConnectionParameters(
true, false, displaySize.x, displaySize.y, 30, 1, VIDEO_CODEC_VP9, true, 1, AUDIO_CODEC_OPUS, true);
client = new WebRtcClient(this, mSocketAddress, params, VideoRendererGui.getEGLContext());
}
#Override
public void onPause() {
super.onPause();
vsv.onPause();
if(client != null) {
client.onPause();
}
}
#Override
public void onResume() {
super.onResume();
vsv.onResume();
if(client != null) {
client.onResume();
}
}
#Override
public void onDestroy() {
if(client != null) {
client.onDestroy();
}
super.onDestroy();
}
#Override
public void onCallReady(String callId) {
if (callerId != null) {
try {
answer(callerId);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
//call(callId);
startCam();
}
}
public void answer(String callerId) throws JSONException {
client.sendMessage(callerId, "init", null);
startCam();
}
public void call(String callId) {
Intent msg = new Intent(Intent.ACTION_SEND);
msg.putExtra(Intent.EXTRA_TEXT, mSocketAddress + callId);
msg.setType("text/plain");
startActivityForResult(Intent.createChooser(msg, "Call someone :"), VIDEO_CALL_SENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VIDEO_CALL_SENT) {
startCam();
}
}
public void startCam() {
// Camera settings
client.start("android_test");
}
#Override
public void onStatusChanged(final String newStatus) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), newStatus, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onLocalStream(MediaStream localStream) {
localStream.videoTracks.get(0).addRenderer(new VideoRenderer(localRender));
VideoRendererGui.update(localRender,
LOCAL_X_CONNECTING, LOCAL_Y_CONNECTING,
LOCAL_WIDTH_CONNECTING, LOCAL_HEIGHT_CONNECTING,
scalingType);
}
#Override
public void onAddRemoteStream(MediaStream remoteStream, int endPoint) {
remoteStream.videoTracks.get(0).addRenderer(new VideoRenderer(remoteRender));
VideoRendererGui.update(remoteRender,
REMOTE_X, REMOTE_Y,
REMOTE_WIDTH, REMOTE_HEIGHT, scalingType);
VideoRendererGui.update(localRender,
LOCAL_X_CONNECTED, LOCAL_Y_CONNECTED,
LOCAL_WIDTH_CONNECTED, LOCAL_HEIGHT_CONNECTED,
scalingType);
}
#Override
public void onRemoveRemoteStream(int endPoint) {
VideoRendererGui.update(localRender,
LOCAL_X_CONNECTING, LOCAL_Y_CONNECTING,
LOCAL_WIDTH_CONNECTING, LOCAL_HEIGHT_CONNECTING,
scalingType);
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), MODIFY_AUDIO_SETTINGS);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
int result3 = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int result4 = ContextCompat.checkSelfPermission(getApplicationContext(), WAKE_LOCK);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{MODIFY_AUDIO_SETTINGS, CAMERA,RECORD_AUDIO,WRITE_EXTERNAL_STORAGE,WAKE_LOCK}, PERMISSION_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (locationAccepted && cameraAccepted) {
//Snackbar.make(view, "Permission Granted, Now you can access location data and camera.", Snackbar.LENGTH_LONG).show();
}
else {
//Snackbar.make(view, "Permission Denied, You cannot access location data and camera.", Snackbar.LENGTH_LONG).show();
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{ACCESS_FINE_LOCATION, CAMERA},
PERMISSION_REQUEST_CODE);
}
}
});
return;
}
}*/
}
}
break;
}
}
}
we have just fixed a similar problem.
you may try by adjusting the bolded number parameter a little bit lower.
PeerConnectionParameters params = new PeerConnectionParameters(
true, false, displaySize.x, displaySize.y, **30**, 1, VIDEO_CODEC_VP9, true, 1, AUDIO_CODEC_OPUS, true);
At least, this helps our case.. Hope work out for you too.

some mistakes on creating application

I'm learning how to create app with android studio,
this is my code source:
package com.example.droide;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class DroideSphereRuhlmannActivity extends Activity implements OnClickListener {
private TextView logview;
private Button connect, deconnect;
private ImageView forwardArrow, backArrow, rightArrow, leftArrow, stop, topleftArrow, toprightArrow, backleftArrow, backrightArrow;
private BluetoothAdapter mBluetoothAdapter = null;
private String[] logArray = null;
private BtInterface bt = null;
static final String TAG = "Droid";
static final int REQUEST_ENABLE_BT = 3;
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String data = msg.getData().getString("receivedData");
addToLog(data);
}
};
final Handler handlerStatus = new Handler() {
public void handleMessage(Message msg) {
int status = msg.arg1;
if(status == BtInterface.CONNECTED) {
addToLog("Connected");
} else if(status == BtInterface.DISCONNECTED) {
addToLog("Disconnected");
}
}
};
private void addToLog(String message){
for (int i = 1; i < logArray.length; i++){
logArray[i-1] = logArray[i];
}
logArray[logArray.length - 1] = message;
logview.setText("");
for (int i = 0; i < logArray.length; i++){
if (logArray[i] != null){
logview.append(logArray[i] + "\n");
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_remote);
logview = (TextView)findViewById(R.id.logview);
logArray = new String[3];
connect = (Button)findViewById(R.id.connect);
connect.setOnClickListener(this);
deconnect = (Button)findViewById(R.id.deconnect);
deconnect.setOnClickListener(this);
forwardArrow = (ImageView)findViewById(R.id.forward_arrow);
forwardArrow.setOnClickListener(this);
backArrow = (ImageView)findViewById(R.id.back_arrow);
backArrow.setOnClickListener(this);
rightArrow = (ImageView)findViewById(R.id.right_arrow);
rightArrow.setOnClickListener(this);
leftArrow = (ImageView)findViewById(R.id.left_arrow);
leftArrow.setOnClickListener(this);
stop = (ImageView)findViewById(R.id.stop);
stop.setOnClickListener(this);
topleftArrow = (ImageView)findViewById(R.id.topleft_arrow);
topleftArrow.setOnClickListener(this);
toprightArrow = (ImageView)findViewById(R.id.topright_arrow);
toprightArrow.setOnClickListener(this);
backrightArrow = (ImageView)findViewById(R.id.backright_arrow);
backrightArrow.setOnClickListener(this);
backleftArrow = (ImageView)findViewById(R.id.backleft_arrow);
backrightArrow.setOnClickListener(this);
}
#Override
public void onResume() {
super.onResume();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.v(TAG, "Device does not support Bluetooth");
}
else{
if (!mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else{
bt = new BtInterface(handlerStatus, handler);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent moreData){
if (requestCode == REQUEST_ENABLE_BT){
if (resultCode == Activity.RESULT_OK){
bt = new BtInterface(handlerStatus, handler);
}
else if (resultCode == Activity.RESULT_CANCELED)
Log.v(TAG, "BT pas active");
else
Log.v(TAG, "code n'est pas valide");
}
else{
Log.v(TAG, "code n'est pas reconnu");
}
}
#Override
public void onClick(View v) {
if(v == connect) {
addToLog("Appareillage en cours");
bt.connect();
}
else if(v == deconnect) {
addToLog("connexion en cours");
bt.close();
}
else if(v == forwardArrow) {
bt.sendData("F");
}
else if(v == backArrow) {
bt.sendData("B");
}
else if(v == rightArrow) {
bt.sendData("R");
}
else if(v == leftArrow) {
bt.sendData("L");
}
else if( v == topleftArrow){
bt.sendData("I");
}
else if(v == toprightArrow){``
bt.sendData("J");
}
else if(v == backleftArrow){
bt.sendData("G");
}
else if(v ==backrightArrow){
bt.sendData("H");
}
else if(v == stop) {
bt.sendData("S");
}
Error Log:
After that, I got some error like :
"Error:(156, 10) error: reached end of file while parsing"
or
"Error:Execution failed for task ':app:compileDebugJavaWithJavac'."
So now I don't now how to solve that.
If this is your full code then your onClick method has not ending curly bracket and also your main class is not ended with curly bracket.
so add two ending curly braces at end of your code

Google calendar API fragment

I've been trying to implement the google calendar on a fragment but unsuccessful.
This code provided by google works fine in one activity, but I'm using ViewPager with tabs.
When the button is press don't show data retrive from google calendar, the same code in activity (without inflate rootview) works fine..
package com.example.myapplication;
import android.Manifest;
import android.support.v4.app.Fragment;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import static android.app.Activity.RESULT_OK;
public class Tab1 extends Fragment implements EasyPermissions.PermissionCallbacks {
GoogleAccountCredential mCredential;
private TextView mOutputText;
private Button mCallApiButton;
ProgressDialog mProgress;
static final int REQUEST_ACCOUNT_PICKER = 1000;
static final int REQUEST_AUTHORIZATION = 1001;
static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003;
private static final String BUTTON_TEXT = "Atualizar Calendario";
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = { CalendarScopes.CALENDAR_READONLY };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout activityLayout = new LinearLayout(getActivity());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
activityLayout.setLayoutParams(lp);
activityLayout.setOrientation(LinearLayout.VERTICAL);
activityLayout.setPadding(16, 16, 16, 16);
ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mCallApiButton = new Button(getActivity());
mCallApiButton.setText(BUTTON_TEXT);
mCallApiButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallApiButton.setEnabled(false);
mOutputText.setText("");
getResultsFromApi();
mCallApiButton.setEnabled(true);
}
});
activityLayout.addView(mCallApiButton);
mOutputText = new TextView(getActivity());
mOutputText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
mOutputText.setLayoutParams(tlp);
mOutputText.setText("");
mOutputText.setPadding(16, 16, 16, 16);
mOutputText.setVerticalScrollBarEnabled(true);
mOutputText.setMovementMethod(new ScrollingMovementMethod());
activityLayout.addView(mOutputText);
mProgress = new ProgressDialog(getActivity());
mProgress.setMessage("A conferir Calendario Google");
mCredential = GoogleAccountCredential.usingOAuth2(getActivity().getApplicationContext(), Arrays.asList(SCOPES)).setBackOff(new ExponentialBackOff());
return (activityLayout);
}
private void getResultsFromApi() {
if (! isGooglePlayServicesAvailable()) {
acquireGooglePlayServices();
} else if (mCredential.getSelectedAccountName() == null) {
chooseAccount();
//VAI POR ESTE
} else if (! isDeviceOnline()) {
mOutputText.setText("No network connection available.");
} else {
new MakeRequestTask(mCredential).execute();
}
}
#AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
private void chooseAccount() {
if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.GET_ACCOUNTS)) {
String accountName = getActivity().getPreferences(Context.MODE_PRIVATE).getString(PREF_ACCOUNT_NAME, null);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
} else {
startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
} else {
EasyPermissions.requestPermissions(getActivity(), "This app needs to access your Google account (via Contacts).", REQUEST_PERMISSION_GET_ACCOUNTS, Manifest.permission.GET_ACCOUNTS);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode != RESULT_OK) {
mOutputText.setText("This app requires Google Play Services. Please install " + "Google Play Services on your device and relaunch this app.");
} else {
getResultsFromApi();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
SharedPreferences settings =
getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.apply();
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == RESULT_OK) {
getResultsFromApi();
}
break;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, getActivity());
}
#Override
public void onPermissionsGranted(int requestCode, List<String> list) {
// Do nothing.
}
#Override
public void onPermissionsDenied(int requestCode, List<String> list) {
// Do nothing.
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(getActivity());
return connectionStatusCode == ConnectionResult.SUCCESS;
}
private void acquireGooglePlayServices() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(getActivity());
if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
}
}
void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
Dialog dialog = apiAvailability.getErrorDialog(
getActivity(),
connectionStatusCode,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private com.google.api.services.calendar.Calendar mService = null;
private Exception mLastError = null;
MakeRequestTask(GoogleAccountCredential credential) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new com.google.api.services.calendar.Calendar.Builder(transport, jsonFactory, credential).setApplicationName("Google Calendar API Android Quickstart").build();
}
#Override
protected List<String> doInBackground(Void... params) {
try {
return getDataFromApi();
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
/**
* Fetch a list of the next 10 events from the primary calendar.
* #return List of Strings describing returned events.
* #throws IOException
*/
private List<String> getDataFromApi() throws IOException {
// List the next 10 events from the primary calendar.
DateTime now = new DateTime(System.currentTimeMillis());
List<String> eventStrings = new ArrayList<String>();
Events events = mService.events().list("primary").setMaxResults(10).setTimeMin(now).setOrderBy("startTime").setSingleEvents(true).execute();
List<Event> items = events.getItems();
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
eventStrings.add(
String.format("%s (%s)", event.getSummary(), start));
}
return eventStrings;
}
#Override
protected void onPreExecute() {
mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
mOutputText.setText("No results returned.");
} else {
output.add(0, "Data retrieved using the Google Calendar API:");
mOutputText.setText(TextUtils.join("\n", output));
}
}
#Override
protected void onCancelled() {
mProgress.hide();
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
showGooglePlayServicesAvailabilityErrorDialog(((GooglePlayServicesAvailabilityIOException) mLastError).getConnectionStatusCode());
} else if (mLastError instanceof UserRecoverableAuthIOException) {
//startActivityForResult(
// ((UserRecoverableAuthIOException) mLastError).getIntent(),
// MainActivity.REQUEST_AUTHORIZATION);
} else {
mOutputText.setText("The following error occurred:\n" + mLastError.getMessage());
}
} else {
mOutputText.setText("Request cancelled.");
}
}
}
}

Arduino ADK Mega is not connecting with any of my Android devices! OutputStream is null?

I have closely followed this tutorial: http://assets.en.oreilly.com/1/event/68/Building%20Android%20Accessories%20using%20the%20Open%20Accessory%20Development%20Kit%20and%20Arduino%20Presentation%201.pdf
However, I have made a few modifications so that I send ASCII values each time my text is updated. I still am unable to connect my Android devices (yes, I have multiple, from versions 2.2.3 to 2.2.7). I keep receiving the error in the onscreen Log that the Outputstreams are null. Any help would be greatly appreciated!
OpenAccessoryTest.java
package org.simonmonk.duinodroid;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;
public class OpenAccessoryTest extends Activity implements Runnable {
private EditText mByteField;
private EditText mResponseField;
private Button mSendButton;
private static final String ACTION_USB_PERMISSION = "com.google.android.DemoKit.action.USB_PERMISSION";
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
private boolean mPermissionRequestPending;
private UsbAccessory mAccessory;
private ParcelFileDescriptor mFileDescriptor;
private FileInputStream mInputStream;
private FileOutputStream mOutputStream;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mByteField = (EditText) findViewById(R.id.streamingTextView1);
mResponseField = (EditText) findViewById(R.id.arduinoresponse);
mSendButton = (Button) findViewById(R.id.sendButton);
// String valueStr = mByteField.getText().toString();
mSendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToArduino();
}
});
setupAccessory();
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
#Override
public void onResume() {
log("Resuming");
super.onResume();
if (mInputStream != null && mOutputStream != null) {
log("Resuming: streams were not null");
return;
}
log("Resuming: streams were null");
UsbAccessory[] accessories = mUsbManager.getAccessoryList();
UsbAccessory accessory = (accessories == null ? null : accessories[0]);
if (accessory != null) {
if (mUsbManager.hasPermission(accessory)) {
openAccessory(accessory);
} else {
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
mUsbManager.requestPermission(accessory,
mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {
log("onResume:mAccessory is null");
}
}
#Override
public void onPause() {
log("Pausing");
super.onPause();
}
#Override
public void onDestroy() {
log("Destroying");
unregisterReceiver(mUsbReceiver);
super.onDestroy();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
ValueMsg t = (ValueMsg) msg.obj;
log("Arduino sent: " + t.getFlag() + " " + t.getReading());
}
};
private void log(String string) {
String contents = mResponseField.getText().toString();
mResponseField.setText(contents + "\n" + string);
}
private void setupAccessory() {
log("In setupAccessory");
mUsbManager = UsbManager.getInstance(this);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
registerReceiver(mUsbReceiver, filter);
if (getLastNonConfigurationInstance() != null) {
mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
openAccessory(mAccessory);
}
}
private void openAccessory(UsbAccessory accessory) {
log("In openAccessory");
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Thread thread = new Thread(null, this, "OpenAccessoryTest");
thread.start();
alert("openAccessory: Accessory openned");
log("Attached");
} else {
log("openAccessory: accessory open failed");
}
}
private void closeAccessory() {
log("In closeAccessory");
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
private int composeInt(byte hi, byte lo) {
int val = hi & 0xff;
val *= 256;
val += lo & 0xff;
return val;
}
#Override
public void run() {
int ret = 0;
byte[] buffer = new byte[16384];
int i;
while (true) { // keep reading messages forever. There are prob lots of
// messages in the buffer, each 4 bytes
try {
ret = mInputStream.read(buffer);
} catch (IOException e) {
break;
}
i = 0;
while (i < ret) {
int len = ret - i;
if (len >= 2) {
Message m = Message.obtain(mHandler);
int value = composeInt(buffer[i], buffer[i + 1]);
m.obj = new ValueMsg('a', value);
mHandler.sendMessage(m);
}
i += 2;
}
}
}
public void sendMessageToArduino() {
String valueStr = mByteField.getText().toString();
try {
for (int x = 0; x < valueStr.length(); x++) {
sendCommand((byte) valueStr.charAt(x));
log("Sending to Arduino: " + (byte) valueStr.charAt(x));
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
alert("The Byte should be a number between 0 and 255");
}
}
public void sendCommand(byte value) {
log("Sent: " + value);
byte[] buffer = new byte[1];
buffer[0] = value;
if (mOutputStream != null) {
try {
mOutputStream.write(buffer);
} catch (IOException e) {
log("Send failed: " + e.getMessage());
}
} else {
log("Send failed: mOutStream was null");
}
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
openAccessory(accessory);
} else {
log("USB permission denied");
}
}
} else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (accessory != null && accessory.equals(mAccessory)) {
log("Detached");
closeAccessory();
}
}
}
};
public void alert(String message) {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage(message);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
}`
StreamingTextView.java
package org.simonmonk.duinodroid;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;
public class StreamingTextView extends EditText {
public StreamingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public StreamingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public StreamingTextView(Context context) {
super(context);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
((OpenAccessoryTest) super.getContext()).sendCommand(toAscii(event));
return super.onKeyDown(keyCode, event);
}
private byte toAscii(KeyEvent event) {
byte ch = (byte) event.getUnicodeChar();
if (ch == 0) {
switch(event.getKeyCode()){
case KeyEvent.KEYCODE_DEL:
ch = 8;
break;
case KeyEvent.KEYCODE_ENTER:
ch = 10;
break;
}
}
return ch;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Byte 0 (decimal)" />
<org.simonmonk.duinodroid.StreamingTextView
android:id="#+id/streamingTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="StreamingTextView" >
<requestFocus />
</org.simonmonk.duinodroid.StreamingTextView>
<Button
android:id="#+id/sendButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send to Arduino" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Log" />
<EditText
android:id="#+id/arduinoresponse"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false"
android:lines="10" />
</LinearLayout>
android version must be > to 2.2 . That start working with Google api version 2.3.4 I think

Categories

Resources