Using onCreate Bundle savedInstanceState with wallpaper service? (Watchface) - java

Im in need of some help.
Secondary Activity
package archtectsproductions.scriptpyandroidwearwatchface;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import static android.graphics.Color.BLUE;
import static android.graphics.Color.GREEN;
import static android.graphics.Color.RED;
public class WatchfaceConfigActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private int mTextColor = 0xffffffff;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watchface_config);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Wearable.API)
.build();
Button buttonOK = (Button)findViewById(R.id.buttonOK);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup radioTextColor =
(RadioGroup)findViewById(R.id.rGroup);
int selectedId = radioTextColor.getCheckedRadioButtonId();
switch (selectedId) {
default:
case R.id.rDarkpastel:
mTextColor = 0xffffffff;
break;
case R.id.Notepad:
mTextColor = GREEN;
break;
case R.id.rHarvenjark:
mTextColor = BLUE;
break;
case R.id.rVibrant:
mTextColor = RED;
break;
}
sendParamsAndFinish();
}
});
}
// sends data through Google API
private void sendParamsAndFinish() {
PutDataMapRequest putDataMapReq =
PutDataMapRequest.create("/watch_face_config_cliu");
putDataMapReq.getDataMap().putInt("text_color", mTextColor);
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
finish();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
MAIN
public class WatchFaceCLiuService extends
CanvasWatchFaceService {
private static final long UPDATE_INTERVAL =
TimeUnit.SECONDS.toMillis(1);
#Override
public Engine onCreateEngine() {
return new Engine();
}
private class Engine extends CanvasWatchFaceService.Engine implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
...
private GoogleApiClient mGoogleApiClient;
private int mTextColor = 0xffffffff;
private float offsetx = (float)(-50 + 100 * Math.random());
private float offsety = (float)(-50 + 100 * Math.random());
#Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
...
mGoogleApiClient = new GoogleApiClient.Builder(WatchFaceCLiuService.this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
...
#Override
public void onDraw(Canvas canvas, Rect bounds) {
...
canvas.drawText(ts1, tx1, ty1, mDigitalPaint);
...
}
private void releaseGoogleApiClient() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Wearable.DataApi.removeListener(mGoogleApiClient,
onDataChangedListener);
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
Wearable.DataApi.addListener(mGoogleApiClient,
onDataChangedListener);
Wearable.DataApi.getDataItems(mGoogleApiClient).
setResultCallback(onConnectedResultCallback);
}
private void updateParamsForDataItem(DataItem item) {
if ((item.getUri().getPath()).equals("/watch_face_config_cliu")) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
if (dataMap.containsKey("text_color")) {
int tc = dataMap.getInt("text_color");
mDigitalPaint.setColor(tc);
invalidate();
}
}
}
private final DataApi.DataListener onDataChangedListener =
new DataApi.DataListener() {
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
DataItem item = event.getDataItem();
updateParamsForDataItem(item);
}
}
dataEvents.release();
if (isVisible() && !isInAmbientMode()) {
invalidate();
}
}
};
private final ResultCallback<DataItemBuffer>
onConnectedResultCallback =
new ResultCallback<DataItemBuffer>() {
#Override
public void onResult(DataItemBuffer dataItems) {
for (DataItem item : dataItems) {
updateParamsForDataItem(item);
}
dataItems.release();
if (isVisible() && !isInAmbientMode()) {
invalidate();
}
}
};
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult
connectionResult) {
}
#Override
public void onDestroy() {
mUpdateTimeHandler.removeMessages(MESSAGE_ID_UPDATE_TIME);
releaseGoogleApiClient();
super.onDestroy();
}
}
}
I really need help, I'm bashing my head against a brick wall. this just doesn't work. it wont send int across at all. Ive followed a guide. Ive done my best it just wont send, does anyone know a better way? should I make a global? would that work better but I'm not sure how id do it as I seem limited on what code I can use in the canvas watchface service.
all I want Is to send an int from one activity to another. Using a watchface service not a companion. I want to learn. so if you do answer don't just paste the code straight out, unless its easier to just paste the code and I can follow it, and decipher it.
thank you for any help .
<-- old
While I understand how to make in java a simple app that saves the users selection of a radio button and then puts it over to a separate activity to, say, change the color of text, i have hit a point where im struggling to do so in android wear.
The reason being i cant Implement the following.
#overide
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Radiogroup = (RadioGroup)findViewById(R.id.myyrad);
Radiogroup.setOnCheckedChangedListener(new OnCheckedChangedListener()) { ....
the following cant be implemented on the wallpaper service?
is there any alternative? or do i have to go the extremely confusing googleapiclient route? any help would be greatly appreciated thank you.

This was solved. Nothing wrong with the tutorial or my code. Studio was looking for a different android play service. Changed it in the gradel

Related

Problem when transmitting camera from android to Wowza

I am trying to transmit the Android camera image via rtsp to Wowza, however without success. It does not return any error, but also in the local Wowza does not show any traffic. I have the local Wowza for testing in http://localhost:8088/
I am using the Libstreaming library to send the rtsp stream.
MainActivity.java
package com.security.testeslibstreaming;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.Window;
import android.view.WindowManager;
import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.rtsp.RtspClient;
public class MainActivity extends AppCompatActivity implements RtspClient.Callback, Session.Callback, SurfaceHolder.Callback {
// log tag
public final static String TAG = MainActivity.class.getSimpleName();
// surfaceview
private static SurfaceView mSurfaceView;
// Rtsp session
private Session mSession;
private static RtspClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mSurfaceView.getHolder().addCallback(this);
// Initialize RTSP client
initRtspClient();
}
#Override
protected void onResume() {
super.onResume();
toggleStreaming();
}
#Override
protected void onPause(){
super.onPause();
toggleStreaming();
}
private void initRtspClient() {
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_NONE)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView).setPreviewOrientation(0)
.setCallback(this).build();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
String ip, port, path;
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d+)/(.+)");
Matcher m = uri.matcher(AppConfig.STREAM_URL);
m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
mClient.setCredentials(AppConfig.PUBLISHER_USERNAME,
AppConfig.PUBLISHER_PASSWORD);
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/" + path);
}
private void toggleStreaming() {
if (!mClient.isStreaming()) {
// Start camera preview
mSession.startPreview();
// Start video stream
mClient.startStream();
} else {
// already streaming, stop streaming
// stop camera preview
mSession.stopPreview();
// stop streaming
mClient.stopStream();
}
}
#Override
public void onDestroy() {
super.onDestroy();
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
break;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
alertError(e.getMessage());
e.printStackTrace();
}
}
private void alertError(final String msg) {
final String error = (msg == null) ? "Unknown error: " : msg;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(error).setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onRtspUpdate(int message, Exception exception) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
alertError(exception.getMessage());
exception.printStackTrace();
break;
}
}
#Override
public void onPreviewStarted() {
}
#Override
public void onSessionConfigured() {
}
#Override
public void onSessionStarted() {
}
#Override
public void onSessionStopped() {
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onBitrateUpdate(long bitrate) {
}
}
AppConfig.java
package com.security.testeslibstreaming;
public class AppConfig {
public static final String STREAM_URL = "rtsp://192.XXX.XX.XX:1935/live/myStream";
public static final String PUBLISHER_USERNAME = "barrXXXXXXX";
public static final String PUBLISHER_PASSWORD = "XXXXXXXXXX";
}

Using Background Music while playing game on Android app game

I am a newbie in Android Developer
I am building a game app on Android Studio. But, I have had a problem about Background music while playing game. I have used Bound Service to handle through the class: MusicService extends Service implements MediaPlayer.OnErrorListener. But, my App was stopped when I run.
I have tried to fixed and explored solutions, but, I can't run app...
This is source code:
MusicService.java
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class MusicService extends Service implements MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MediaPlayer Player;
public MusicService() {
}
public class ServiceBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
Player = MediaPlayer.create(this, R.raw.one);
mPlayer.setOnErrorListener(this);
if (mPlayer != null) {
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int
extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return START_STICKY;
}
public void pauseMusic() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
length = mPlayer.getCurrentPosition();
}
}
public void resumeMusic() {
if (mPlayer.isPlaying() == false) {
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic() {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
return false;
}
}
and, MainActivity.java
public class MainActivity extends AppCompatActivity {
private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon =new ServiceConnection(){
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.ServiceBinder binder = (MusicService.ServiceBinder)service;
mServ =binder.getService();
}
public void onServiceDisconnected(ComponentName name) {
mServ = null;
}
};
// Activity create UI its
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Activity start.
#Override
protected void onStart() {
super.onStart();
// create Intent for MusicService.
Intent intent = new Intent(MainActivity.this,MusicService.class);
// call method bindService(..) to bind activity
this.bindService(intent, Scon, Context.BIND_AUTO_CREATE);
}
//Activity stop
#Override
protected void onStop() {
super.onStop();
if (mIsBound) {
this.unbindService(Scon);
mIsBound = false;
}
}
Then, I didn't also forget add the code following in AndroidManifest
<service
android:name=".MusicService"
android:enabled="true"
android:exported="true"></service>
That's all problems mine. This makes me so confuse
Help you, please
Thank you very much
Can you add more log debug in logcat? Not sure but I guess problem is you call:
mPlayer.start();
in onStartComand(). Your service should implement MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,MediaPlayer.OnCompletionListener and above function should be call in
void onPrepared(MediaPlayer mp)

Java/Android override methods

I am practicing Android for internship and I have been able to write a class that handles the geolocation for me trying to find the best location and I keep updating things whenever onLocationChanged is called.
Now I need to use my location to put Markers on a GoogleMaps I could obviously change the onLocationChanged method from my class handling geolocation but I would love to extract the action I need to do outside of the class because in the future I might need my current location to perform a lot of different things.
package com.example.soueuls.swipe;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class GeoLocation {
private final Context context;
private final LocationManager locationManager;
private Location currentLocation;
private int updateLimit = 0;
private long timeLimit = 0;
public GeoLocation(Context context) {
this.context = context;
this.locationManager = (LocationManager)this.context.getSystemService(Context.LOCATION_SERVICE);
this.currentLocation = this.locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (this.currentLocation == null) {
this.currentLocation = this.locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location newLocation) {
if (isBetterLocation(GeoLocation.this.currentLocation, newLocation)) {
GeoLocation.this.currentLocation = newLocation;
}
if (--GeoLocation.this.updateLimit == 0) {
GeoLocation.this.stopLocationUpdate();
} else if (System.currentTimeMillis() / 1000 > GeoLocation.this.timeLimit) {
GeoLocation.this.stopLocationUpdate();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
private boolean isBetterLocation(Location currentLocation, Location newLocation) {
if (currentLocation == null) {
return true;
}
int twoMinutes = 1000 * 60 * 2;
long timeDelta = newLocation.getTime() - currentLocation.getTime();
int accuracyDelta = (int) (newLocation.getAccuracy() - currentLocation.getAccuracy());
boolean isSignificantlyNewer = timeDelta > twoMinutes;
boolean isSignificantlyOlder = timeDelta < -twoMinutes;
boolean isNewer = timeDelta > 0;
if (isSignificantlyNewer) {
return true;
} else if (isSignificantlyOlder) {
return false;
}
boolean isMoreAccurate = accuracyDelta < 0;
boolean isLessAccurate = accuracyDelta > 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
boolean isFromSameProvider = isSameProvider(currentLocation.getProvider(), newLocation.getProvider());
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
} else {
return false;
}
}
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
public void setUpdateLimit(int limit) {
this.updateLimit = limit;
}
public void setTimeLimit(long limit) {
this.timeLimit = System.currentTimeMillis() / 1000 + limit;
}
public void setLocationUpdate(String provider, int minTimeInterval, int minDistance) {
this.locationManager.requestLocationUpdates(provider, minTimeInterval, minDistance, this.locationListener);
}
public void stopLocationUpdate() {
this.locationManager.removeUpdates(this.locationListener);
}
public Location getCurrentLocation() {
return this.currentLocation;
}
}
Here is GeoLocation class I would still need to update this.currentLocation each time onLocationChanged is called.
But I would like to be able to detect whenever onLocationChanged iscalled to perform update inside my activity which is outside this class.
How could I do it ?
EDIT :
Inside the onResume method of the activity I am trying to listen I do
GeolocationListener locationListener = new GeolocationAdapter() {
#Override
public void onLocationChanged(Location newLocation) {
System.out.println("OHOHOH");
displayWeatherInformation(weatherCache, geoLocation.getCurrentLocation());
}
};
use listeners
you add the interface to your Geolocation class
public class GeoLocation {
add your listeners
// listeners
private List<LocationListener> listeners = new ArrayList<LocationListener>();
public void addListener(LocationListener l){
listeners.add(l);
}
public void removeListener(LocationListener l){
listeners.remove(l);
}
then inside your private LocationListener locationListener = new LocationListener() you put
#Override
public void onLocationChanged(Location newLocation) {
if (isBetterLocation(GeoLocation.this.currentLocation, newLocation)) {
GeoLocation.this.currentLocation = newLocation;
for(LocationListener l:listeners){
l.onLocationChanged(newLocation);
}
}
... the rest of the code
then any class can register to receive updates on your Geolocation class
edit:
declare your activity like this:
public class MyActivity extends Activity implements LocationListener{
#Override
public void onResume(){
geoLocation.addListener(this);
}
#Override
public void onPause(){
geoLocation.removeListener(this);
}
#Override
public void onLocationChanged(Location newLocation) {
}
}
You can use observer pattern-the activity registers itself in onResume() with the GeoLocation class to receive updates and in onPause() unregisters itself.
There are lot of material on net to learn observer pattern-http://en.wikipedia.org/wiki/Observer_pattern

Why the function getLastKnownLocation return Null on Android SDK?

I use android sdk on eclipse and i want to get location from device so i wrote an program in other class(diffrent from main) and i call mContext function inside this class from main class:
package com.example.deomanapp;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.example.deomanapp.MainActivity.PlaceholderFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class Mhelper {
public void mContext(Context context)
{
LocationManager lm;
lm = (LocationManager)context.getSystemService(context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String slongitude = String.valueOf((long) longitude);
String slatitude = String.valueOf((long) latitude);
Toast.makeText(context, slongitude, Toast.LENGTH_SHORT).show();
}
}
The problem is getLongitude or getLatitude return null,so the program crash on this line with this log:
04-20 04:30:30.410: E/AndroidRuntime(5151): java.lang.NullPointerException
04-20 04:30:30.410: E/AndroidRuntime(5151): at com.example.deomanapp.Mhelper.mContext(Mhelper.java:29)
What is wrong with this code ?
PS: I read other question with the same title and non of theme help (non of them have actual answer) because:
1-I test this program on the real device(not emulator) with GPS ON and working , but this program can't able to get location although the Device get its location before and it must show LastKnownLocation.
2-I gave the program ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permission.
3-I even use an function to see if the GPS is on, when i turn it off program alert me.
It was silly question to ask ,It was null because it was NULL,i understand it by comments on main question, my solution was to download android api image in sdk manager,run Google map once and send GPS location to it by DDMS and then run the program.
I have tried to modify some of my code, hopefully it works for your needs.
You will find the implementation of my LocationsCoreModule code in the bottom of the answer:
LocationsCoreModule locationService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationRequest mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(5000);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(1000);
locationService = new LocationsCoreModule(this, mLocationRequest);
locationService.setLocationsListener(new LocationsCoreModuleCallback() {
#Override
public void locationClientConnected() {
Location location = locationService.getLastLocation();
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String slongitude = String.valueOf((long) longitude);
String slatitude = String.valueOf((long) latitude);
Toast.makeText(getApplicationContext(), slongitude, Toast.LENGTH_SHORT).show();
}
});
}
If you want the application to start listening for new GPS locations right away:
#Override
protected void onStart() {
super.onStart();
locationService.start(new LocationListener() {
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
}, new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onStop() {
super.onStop();
locationService.stop();
}
And finally, the LocationsCoreModule:
public class LocationsCoreModule implements
GooglePlayServicesClient.ConnectionCallbacks {
private static final String TAG = "LocationsCoreModule";
public interface LocationsCoreModuleCallback {
public void locationClientConnected();
}
private LocationsCoreModuleCallback locationsCoreModuleCallback;
private com.google.android.gms.location.LocationListener locationListener;
private Location lastLocation;
private LocationClient mLocationClient;
private final LocationRequest mLocationRequest;
private final Context context;
#Inject
public LocationsCoreModule(Context context, LocationRequest locationRequest) {
this.context = context;
this.mLocationRequest = locationRequest;
}
public void setLastLocation(Location lastLocation) {
this.lastLocation = lastLocation;
}
public void setLocationsListener(
LocationsCoreModuleCallback locationsCoreModuleCallback) {
this.locationsCoreModuleCallback = locationsCoreModuleCallback;
}
public void start(
com.google.android.gms.location.LocationListener locationListener,
GooglePlayServicesClient.OnConnectionFailedListener connectionFailedListener) {
this.locationListener = locationListener;
mLocationClient = new LocationClient(context, this,
connectionFailedListener);
mLocationClient.connect();
}
public void stop() {
if (mLocationClient != null) {
// If the client is connected
if (mLocationClient.isConnected() && locationListener != null) {
/*
* Remove location updates for a listener. The current Activity
* is the listener, so the argument is "this".
*/
mLocationClient.removeLocationUpdates(locationListener);
}
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
}
}
public boolean isConnected() {
if (mLocationClient == null) return false;
return mLocationClient.isConnected();
}
public Location getLastLocation() {
if (lastLocation != null) {
return lastLocation;
}
if (mLocationClient != null) {
if (mLocationClient.isConnected()) {
return lastLocation = mLocationClient.getLastLocation();
}
if (!mLocationClient.isConnecting())
mLocationClient.connect();
}
return null;
}
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "GooglePlayServices connected!");
Location lastLocation = mLocationClient.getLastLocation();
if (lastLocation == null)
Log.e(TAG, "Lastlocation is null even after connected!!!!");
if (locationsCoreModuleCallback != null) {
locationsCoreModuleCallback.locationClientConnected();
locationsCoreModuleCallback = null; // single shot
}
}
public void requestLocationUpdates() {
if (mLocationClient != null && mLocationClient.isConnected()) {
Log.d(TAG, "Requesting location updates");
mLocationClient.requestLocationUpdates(mLocationRequest,
locationListener);
}
}
public void stopLoactionUpdates() {
if (mLocationClient != null && mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(locationListener);
}
}
#Override
public void onDisconnected() {
Log.d(TAG, "GooglePlayServices disconnected!");
}
}

Facebook Feed Dialog with game images and description below

I want to achieve Facebook Integration in my app. At this point of time, I have the login and post to wall functionality, but the wall post I have is only like the simple wall post.
I want to achieve this. Just like in every game, they have this kind of facebook feed..
This is the current code I have..
package com.example.facebooktrial;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
#SuppressWarnings("deprecation")
public class AndroidFacebookConnectActivity extends Activity {
Button btnFbLogin;
Button btnPostToWall;
// Your Facebook APP ID
private static String APP_ID = "593769430655402"; // Replace your App ID here
// Instance of Facebook Class
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFbLogin = (Button) findViewById(R.id.btnFbLogin);
btnPostToWall = (Button) findViewById(R.id.btnFbPost);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
}
I found the solution. Just make use of a Bundle where you'll store all the necessary information like the picture, name, link and so on.. After that, include that bundle in the Facebook dialog as an argument..
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
Bundle params = new Bundle();
params.putString("name", "Check it out, I am playing FLIP game!");
params.putString("caption", "Come on FLIP with me");
params.putString("description", "FLIP!");
params.putString("picture", "http://www.rawk.com/media/images/uploaded/products/2099/flip-hkd-black-complete-skateboard.3043.full.jpg");
facebook.dialog(this, "feed",params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}

Categories

Resources