[Q]Service Socket closed by Background Foreground Lifecycle - Java for Android App Development

I am writing an IRC Client, and so far as long as I dont send the app to the background and try to restore it it works fine. Tabs for multiple channels, the connected socket is in a bound service (started separately via INTENT and a startService call), etc and so on.
However, whenever I send the app to the background, then bring it back forward, the socket closes. I would have the same issue with screen rotation but I found the config setting that stops it from going through destroy/create on rotation. If I figure this out I may actually get rid of that since the issue will have been solved.
The other issue I seem to be having is that it takes a long time to re-bind to the service, and I have no idea why (the initial binding and startup is pretty quick, but re-binding to it seems to take forever, and when It does re-bind, the socket is closed).
Here are the code samples that I feel to be relevant, let me know if there's something more specific you want to see.
Code:
//This is the Service in question
public class ConnectionService extends Service{
private BlockingQueue<String> MessageQueue;
public final IBinder myBind = new ConnectionBinder();
public class ConnectionBinder extends Binder {
ConnectionService getService() {
return ConnectionService.this;
}
}
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private IRCServer server;
private WifiManager.WifiLock wLock;
private Thread readThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String line;
while ((line = reader.readLine( )) != null) {
//message parsing stuff
}
}
catch (Exception e) {}
}
});
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(MessageQueue == null)
MessageQueue = new LinkedBlockingQueue<String>();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return myBind;
}
@Override
public boolean stopService(Intent name) {
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.stopService(name);
}
@Override
public void onDestroy()
{//I put this here so I had a breakpoint in place to make sure this wasn't firing instead of stopService
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onDestroy();
}
public void SendMessage(String message)
{
try {
writer.write(message + "\r\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readLine()
{//this is called by the activity which consumes the service. Its just an accessor to MessageQueue
try {
if(!isConnected())
return null;
else
return MessageQueue.take();
} catch (InterruptedException e) {
return "";
}
}
public boolean ConnectToServer(IRCServer newServer)
{
try {
//create a new message queue (connecting to a new server)
MessageQueue = new LinkedBlockingQueue<String>();
//lock the wifi
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");
wLock.acquire();
server = newServer;
//connect to server
socket = new Socket();
socket.setKeepAlive(true);
socket.setSoTimeout(60000);
socket.connect(new InetSocketAddress(server.NAME, Integer.parseInt(server.PORT)), 10000);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//run basic login scripts.
String line;
while ((line = reader.readLine( )) != null) {
//server initialization stuff
}
//start the reader thread AFTER the primary login!!!
CheckStartReader();
if(server.START_CHANNEL == null || server.START_CHANNEL == "")
{
server.WriteCommand("/join " + server.START_CHANNEL);
}
//we're done here, go home everyone
} catch (NumberFormatException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
private void queueMessage(String line) {
try {
MessageQueue.put(line);
} catch (InterruptedException e) {
}
}
public boolean isConnected()
{
return socket.isConnected();
}
public void CheckStartReader()
{
if(this.isConnected() && !readThread.isAlive())
readThread.start();
}
}
Code:
//Here are the relevant portions of the hosting Activity that connects to the service
//NOTE: THE FOLLOWING CODE IS PART OF THE ACTIVITY, NOT THE SERVICE
private ConnectionService conn;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
conn = ((ConnectionService.ConnectionBinder)service).getService();
//debug toast
Toast.makeText(main_tab_page.this, "Connected", Toast.LENGTH_SHORT)
.show();
synchronized (_serviceConnWait) {
_serviceConnWait.notify();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
conn = null;//does this even run? Breakpoint here
}
};
@Override
protected void onSaveInstanceState(Bundle state){
super.onSaveInstanceState(state);
state.putParcelable("Server", server);
state.putString("Window", CurrentTabWindow.GetName());
//have to unbind, othewise we get that leaked service exception
unbindService(mConnection);
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(this.isFinishing())
stopService(new Intent(this, ConnectionService.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab_page);
localTabHost = (TabHost)findViewById(R.id.tabHostMain);
localTabHost.setup();
localTabHost.setOnTabChangedListener(new tabChange());
_serviceConnWait = new Object();
if(savedInstanceState == null)
{//initial startup, coming from Intent to start
//get server definition
server = (IRCServer)this.getIntent().getParcelableExtra(IRC_WINDOW);
server.addObserver(this);
AddTabView(server);
//this should only run the first time, all other calls to OnCreate should have something in SavedInstanceState
startService(new Intent(this, ConnectionService.class));
}
else
{
server = (IRCServer)savedInstanceState.getParcelable("Server");
String windowName = savedInstanceState.getString("Window");
//Add Needed Tabs
//Server
if(!(windowName.equals(server.GetName())))
AddTabView(server);
//channels
for(IRCChannel c : server.GetAllChannels())
if(!(windowName.equals(c.GetName())))
AddTabView(c);
//reset each view's text (handled by tabChange)
if(windowName.equals(server.GetName()))
SetCurrentTab(server.NAME);
else
SetCurrentTab(windowName);
ResetMainView(CurrentTabWindow.GetWindowTextSpan());
//Rebind to service
BindToService(new Intent(this, ConnectionService.class));
}
}
@Override
protected void onStart()
{
super.onStart();
final Intent ServiceIntent = new Intent(this, ConnectionService.class);
//check start connection service
final Thread serverConnect = new Thread(new Runnable() {
@Override
public void run() {
if(!BindToService(ServiceIntent))
return;
server.conn = conn;
conn.ConnectToServer(server);
server.StartReader();
if(server.START_CHANNEL != null && !server.START_CHANNEL.equals(""))
{
IRCChannel chan = server.FindChannel(server.START_CHANNEL);
if(chan != null)
{
AddTabView(chan);
}
else
{
server.JoinChannel(server.START_CHANNEL);
chan = server.FindChannel(server.START_CHANNEL);
AddTabView(chan);
}
}
}
});
serverConnect.start();
}
private boolean BindToService(Intent ServiceIntent)
{
int tryCount = 0;
bindService(ServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
while(conn == null && tryCount < 10)
{
tryCount++;
try {
synchronized (_serviceConnWait) {
_serviceConnWait.wait(1500);
}
}
catch (InterruptedException e) {
//do nothing
}
}
return conn != null;
}
Logcat...well...there isn't really any exception thrown, the code runs just fine...except that it closes the socket. I suppose that counts as an exception. Whenever I run the socket write command It throws a "Socket Closed" exception at me. No other crash involved.

Related

Why can't my GUI return back to recording mode despite having service?

Hi i'm new to android so that's why i come to find help... Hi an introduction to the app i'm doing here, i'm actually doing an car blackbox app..
I had my service run the video recording processes in the background so i should be able to leave the app for a while and come back to the Video recording GUI with the surfaceview but my application was force to close when i return to the app. So is the problem related to onResume() method or something else? If its yes what i should do in order to get my application GUI to return to the video recording surfaceview and still running the background recording using the service rather than giving me an error? Can someone help please...
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "Exception";
public static SurfaceView surfaceView;
public static SurfaceHolder surfaceHolder;
public static Camera camera;
public static boolean previewRunning;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.button4);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
Button btnStop = (Button) findViewById(R.id.button5);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
if (camera != null) {
Camera.Parameters params = camera.getParameters();
camera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (previewRunning) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(320, 240);
p.setPreviewFormat(PixelFormat.JPEG);
camera.setParameters(p);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e) {
Log.e(TAG,e.getMessage());
e.printStackTrace();
}
}
@Override
public void onResume(){
super.onResume();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder){
camera.stopPreview();
previewRunning = false;
camera.release();
}
}
My RecordingService.java Service file
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Camera camera;
private boolean recordingStatus;
private MediaRecorder mediaRecorder;
private final int maxDurationInMs = 20000;
private static final String TAG = "Exception";
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
camera = CameraTest.camera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
public boolean startRecording(){
try {
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
camera.unlock();
}
catch(Exception e){
camera.reconnect();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(maxDurationInMs);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File directory = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(directory.exists()))
directory.mkdir();
File FileSaved = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + ".3gp");
mediaRecorder.setOutputFile(FileSaved.getPath());
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
try {
camera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recordingStatus = false;
}
}
This is like the third time you've posted this. Convention dictates that you "bump" the existing thread rather than start a new one.
That said, I've considered replying each time, but I don't even know where to start. You seem to have a fundamental misunderstanding of OOP and java in general, and Android extensions specifically.
You can't use your CameraTest class the way you are in your service. You seem to be operating under the assumption that you can just declare some objects "static" (I'm assuming to get around compiler errors) and be able to access them as if they were some kind of global variables. You'll need to use bindings (AIDL) between your service and activity to properly synchronize calls between the two. This is a rather advanced topic and can't really be addressed in a reply.
Sorry i'm rather new to forums... By the way after your explanation i seems to get even more confused in a way, ya i'm rather confused/misunderstood OOP and java because i never really studied java before yet my lecturer still force me to do android for my project... Wow you're really good in spotting my problem.
Either way, i still don't seems to be able to return to my GUI recording preview homepage after i leaves the page, how should this problem be solve? Sorry if i'm rather slow/stupid to understand your "technical" descriptions...

Playing videos using mediastore with custom player

Not that anyone will actually reply but I'm about to go insane to be honest, ALL i want to do is play a video from a list view using media store and a custom video player (Not stock player!) but so far all my attempts have failed.
So i need some professional help!
My MediaStore code:
Code:
public class VideoManager {
public VideoManager() {
}
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
public ArrayList<HashMap<String, String>> getPlayList(Context c) {
/*use content provider to get beginning of database query that queries for all audio by display name, path
and mimtype which i dont use but got it incase you want to scan for mp3 files only you can compare with RFC mimetype for mp3's
*/
final Cursor mCursor = c.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA}, null, null,
"UPPER(" + MediaStore.Video.Media.TITLE + ") ASC");
String videoTitle = "";
String videoPath = "";
/* run through all the columns we got back and save the data we need into the arraylist for our listview*/
if (mCursor.moveToFirst()) {
do {
videoTitle = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
videoPath = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
HashMap<String, String> video = new HashMap<String, String>();
video.put("videoTitle", videoTitle);
video.put("videoPath", videoPath);
videoList.add(video);
} while (mCursor.moveToNext());
}
mCursor.close(); //cursor has been consumed so close it
return videoList;
}
public ArrayList<HashMap<String, String>> getPlayList() {
// TODO Auto-generated method stub
return null;
}
}
The list code along with an OnItemClick method and Intent:
Code:
public class VideoActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
ListView videolist;
Cursor mCursor;
int videoTitle;
int count;
int videoPath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos);
ArrayList<HashMap<String, String>> videoListData = new ArrayList<HashMap<String, String>>();
VideoManager plm = new VideoManager();
// get all songs from sdcard
this.videoList = plm.getPlayList(this);
// looping through playlist
for (int i = 0; i < videoList.size(); i++) {
// creating new HashMap
HashMap<String, String> video = videoList.get(i);
// adding HashList to ArrayList
videoListData.add(video);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, videoListData,
R.layout.video_item, new String[] { "videoTitle" }, new int[] {
R.id.videoTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int videoIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
VideoPlayerActivity.class);
Log.d("TAG","onItemClick");
// Sending songIndex to PlayerActivity
in.putExtra("videoPath", videoIndex);
startActivity(in);
// Closing PlayListView
finish();
}
});
}
}
And lastly, the players code:
Code:
public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
private VideoManager videoManager;
private int currentvideoIndex = 0;
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList(this);
}
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 0){
currentvideoIndex = data.getExtras().getInt("videoPath");
// play selected song
playVideo(currentvideoIndex);
}
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
// Implement SurfaceHolder.Callback
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
player.prepareAsync();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
@Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
try {
player.prepare();
player.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return player.getCurrentPosition();
}
@Override
public int getDuration() {
return player.getDuration();
}
@Override
public boolean isPlaying() {
return player.isPlaying();
}
@Override
public void pause() {
player.pause();
}
@Override
public void seekTo(int i) {
player.seekTo(i);
}
@Override
public void start() {
player.start();
}
@Override
public boolean isFullScreen() {
return false;
}
@Override
public void toggleFullScreen() {
}
}
Right now PLEASE HELP ME!! :crying:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
EmptinessFiller said:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
Click to expand...
Click to collapse
Hi, thanks for the reply but unfortunately it didn't work.
I assume the code i entered is correct..
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
playVideo(getIntent().getExtras().getInt("videoPath"));
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList();
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Android getting SMS body from inbox

Hi,
I want to get body of SMS when I click on one. I have tried an approach simmilar to contact picker. Here is my code :
public class Decrypt extends Fragment {
Button loadButton;
EditText smsDisplay;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.decrypt, null);
// Button loadButton=(Button)v.findViewById(R.id.)
loadButton=(Button)v.findViewById(R.id.buttonLoad);
smsDisplay=(EditText)v.findViewById(R.id.editTextLoad);
loadButton.setOnClickListener(new OnClickListener() {
@override
public void onClick(View v) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
//sendIntent.setType(Sm)
//sendIntent.putExtra("sms_body","");
startActivityForResult(sendIntent,2);
}
});
return v;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
try{
// if (resultCode == Activity.RESULT_OK) {
Uri ur = data.getData();
Cursor c = getActivity().getContentResolver().query(ur, null, null, null, null);
if (c.moveToFirst()) {
String s = c.getString(c.getColumnIndex("body"));
System.out.println(s);
Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
smsDisplay.setText(s);
}
}catch(Exception e){
e.printStackTrace();
}
// }
}
}
It opens a Inbox like when I open original sms app in anroid, but when I click on one message it doesnt copy body of that sms in my edittext. Please couul you look at my code and find mistake?
Thanks a lot for your time

[Q] GP Services achievements unlock and leaderboards uploadnot working

Hello, I have my new game which will be released at the end of february. But now, I have just the signed version installed on phone and the app is not published yet. And hen I try to submit my score to leaderboard, it simply won't and I don't know why. I am using the instance on GoogleApiClient because I need to unlock Achievements in several different Activities. So, here is my code:
Code:
public class GameOverActivity extends GoogleBaseGameActivity {
int coins2;
int score;
int coins;
String type;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_over_layout);
SharedPreferences shop = getSharedPreferences("Shop", Context.MODE_PRIVATE);
coins2 = shop.getInt("money", 0);
score = getIntent().getExtras().getInt("score");
coins = getIntent().getExtras().getInt("coins");
type = getIntent().getExtras().getString("GameType");
TextView money = (TextView) findViewById(R.id.coins);
money.setText("Coins:" + String.valueOf(coins2) + "+" + String.valueOf(coins));
SharedPreferences.Editor editor = shop.edit();
editor.putInt("money", coins + coins2);
editor.commit();
GoogleApiClient mGoogleApiClient = getApiClient();
mGoogleApiClient.connect();
TextView score1 = (TextView) findViewById(R.id.score);
score1.setText("Score:" + String.valueOf(score));
Button mainMenu = (Button) findViewById(R.id.MainMenu);
if (mGoogleApiClient.isConnected()) {
Games.Achievements.unlockImmediate(mGoogleApiClient, getString(R.string.achievement_newbie_player));
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_casual_player), 1);
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_addicted_player), 1);
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_mrms_addicted), 1);
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_mrms_maniac), 1);
switch (type) {
case "normal":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_normal_mode),
score);
case "hard":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_hard_mode),
score);
case "reversed":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_reversed_mode),
score);
if(score==69){
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_reversed_reversed));
}
case "revHard":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_reversed_hard_mode),
score);
}
}
mainMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GameOverActivity.this, MainMenuActivity.class);
startActivity(intent);
}
});
Button replay = (Button) findViewById(R.id.replay);
replay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (type.equals("normal")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTap.class);
startActivity(intent);
} else if (type.equals("hard")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTapHardMode.class);
startActivity(intent);
} else if (type.equals("reversed")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTapReversedMode.class);
startActivity(intent);
} else if (type.equals("revHard")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTapReversedHardMode.class);
startActivity(intent);
} else {
Intent intent = new Intent(GameOverActivity.this, MainMenuActivity.class);
startActivity(intent);
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK)
return false;
return false;
}
@Override
public void onSignInFailed() {
}
@Override
public void onSignInSucceeded() {
}
}
How to make it working ?
The problem is that I can open up the screen with the achievements/leaderboards but can't update them.

BLE Application (Display data from characteristic in a textView)

I used the BluetoothLeGatt example code to write an app that automatically connects to a bonded BLE peripheral upon launching the app. Now i am trying to display the data from one of the peripheral's characteristic in a textView. The BluetoothLeGatt example code only demonstrates this using ExpandableListView.OnChildClickListener, my app should require no user input and simply get he data from the characteristic. This is what i have so far:
Code:
private TextView mConnectionState;
private TextView mDataField;
private String mDeviceName;
private String mDeviceAddress;
private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
private boolean mConnected = false;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
mConnectionState.setTextColor(Color.parseColor("#FF17AA00"));
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
*edit*
UUID chara = UUID.fromString("c97433f0-be8f-4dc8-b6f0-5343e6100eb4");
List<BluetoothGattService> servs = mBluetoothLeService.getSupportedGattServices();
for (int i = 0; servs.size() > i; i++) {
List<BluetoothGattCharacteristic> charac = servs.get(i).getCharacteristics();
for (int j = 0; charac.size() > i; i++) {
BluetoothGattCharacteristic ch = charac.get(i);
if (ch.getUuid() == chara) {
mBluetoothLeService.readCharacteristic(ch);
mBluetoothLeService.setCharacteristicNotification(ch, true);
}
}
}
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_control);
final Intent intent = getIntent();
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mDataField = (TextView) findViewById(R.id.data);
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mConnectionState.setText(resourceId);
}
});
}
private void displayData(String data) {
if (data != null) {
mDataField.setText(data);
}
}
private void clearUI() {
mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
mDataField.setText(R.string.no_data);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentFilter;
}
I've successfully connected to an already bonded device, but now im trying to get the data from a characteristic using its uuid and display it in a textView. The BluetoothLeGatt example shows how a characteristic is selected by a user using an expandable list view onclick listener displaying the supported characteristics. I want to bypass all that and just get the data from the characteristic with the known uuid.
-EDIT-
figured it out

Categories

Resources