Libgdx - How to implement loading screen in Android Launcher using ads - java

So I've created a game using Libgdx and the load times were practically non-existent, recently I added a Facebook leaderboard using the GDXFacebook extension which added a small overhead when loading up the app as it will auto login when loading but nothing that really effected load times. Now using and implementation from Libgdx I have added ads through Google play services to the main page of the game but it has made it so the initial load times is now a good 5 seconds.
My question is is there away to add the loading image to the android launcher class while it is loading to the main screen?
Thanks in advance!
Here is my Android launcher class and main game class.
Android Launcher:
public class AndroidLauncher extends AndroidApplication implements IActivityRequestHandler {
private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/6300978111";
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
private AdView adView;
protected Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_ADS: {
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS: {
adView.setVisibility(View.GONE);
break;
}
}
}
};
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useCompass = false;
config.useAccelerometer = false;
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
load(config, layout);
// Hook it all up
setContentView(layout);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void load(AndroidApplicationConfiguration config, RelativeLayout layout){
// Create the libgdx View
View gameView = initializeForView(new Game(this), config);
String locationProvider = LocationManager.NETWORK_PROVIDER;
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Create and setup the AdMob view
adView = new AdView(this); // Put in your secret key here
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(AD_UNIT_ID);
/** if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}**/
//AdRequest adRequest = new AdRequest.Builder().setLocation(locationManager.getLastKnownLocation(locationProvider)).build();
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adView.setY(RelativeLayout.ALIGN_PARENT_BOTTOM - 80);
showAds(false);
layout.addView(adView, adParams);
}
#Override
public void onResume() {
super.onResume();
if (adView != null) adView.resume();
}
#Override
public void onPause() {
if (adView != null) adView.pause();
super.onPause();
}
#Override
public void onDestroy() {
if (adView != null) adView.destroy();
super.onDestroy();
}
#Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("AndroidLauncher Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
Game Class:
public class Game implements ApplicationListener{
private int m_ScreenWidth;
private int m_ScreenHeight;
private IActivityRequestHandler requestHandler;
private GameScreen m_GameScreen;
private MenuScreen m_Menu;
private HighScoreScreen m_HighScores;
private RankingsScreen m_RankingScreen;
private Input m_Input;
private Assets m_Assets;
private ShapeRenderer m_ShapeRenderer;
private SpriteBatch m_BatchRenderer;
private OrthographicCamera m_Camera;
private boolean m_Loaded;
public enum State {
READY, MENU, RUNNING, PAUSED, HIGHSCORE, RANKINGS
}
private State m_State;
public Game(IActivityRequestHandler handler){
requestHandler = handler;
}
#Override
public void create() {
m_ScreenWidth = 360;
m_ScreenHeight = 640;
m_Camera = new OrthographicCamera();
m_Camera.setToOrtho(false, 360, 640);
m_Camera.position.set(m_ScreenWidth / 2, m_ScreenHeight / 2, 0);
m_Camera.update();
m_ShapeRenderer = new ShapeRenderer();
m_BatchRenderer = new SpriteBatch();
m_BatchRenderer.setProjectionMatrix(m_Camera.combined);
m_ShapeRenderer.setProjectionMatrix(m_Camera.combined);
m_Loaded = false;
m_Assets = new Assets();
m_Assets.loadAssets();
while (!m_Loaded) {
if (m_Assets.getAssetManager().update()) {
m_Loaded = true;
}
}
m_GameScreen = new GameScreen(m_ScreenWidth, m_ScreenHeight, m_BatchRenderer, m_ShapeRenderer, m_Camera, this, m_Assets);
m_Menu = new MenuScreen(m_ScreenWidth, m_ScreenHeight, m_BatchRenderer, m_ShapeRenderer, m_Camera, this, m_Assets);
m_HighScores = new HighScoreScreen(m_ScreenWidth, m_ScreenHeight, m_BatchRenderer, m_ShapeRenderer, m_Camera, this, m_Assets);
m_RankingScreen = new RankingsScreen(m_ScreenWidth, m_ScreenHeight, m_BatchRenderer, m_ShapeRenderer, m_Camera, this, m_Assets);
m_Input = new Input(this, m_GameScreen, m_HighScores, m_Menu, m_RankingScreen);
Gdx.input.setInputProcessor(m_Input);
m_RankingScreen.autologin();
setState(State.MENU);
}
#Override
public void render() {
switch (m_State) {
case PAUSED:
m_GameScreen.renderBackground();
m_GameScreen.renderPaused();
break;
case HIGHSCORE:
m_GameScreen.renderBackground();
m_HighScores.render(Gdx.graphics.getDeltaTime());
break;
case MENU:
m_Menu.render(Gdx.graphics.getDeltaTime());
break;
case READY:
m_GameScreen.renderReady(Gdx.graphics.getDeltaTime());
break;
case RUNNING:
m_GameScreen.render(Gdx.graphics.getDeltaTime());
break;
case RANKINGS:
m_RankingScreen.render();
break;
}
}
#Override
public void dispose() {
m_RankingScreen.logout();
m_ShapeRenderer.dispose();
m_BatchRenderer.dispose();
m_Assets.dispose();
}
#Override
public void resize(int width, int height) {
}
public State getState() {
return m_State;
}
public void setState(State state) {
if(state == State.MENU) {
m_Menu.resetEnemies();
requestHandler.showAds(true);
}
else if(state == State.RANKINGS) {
m_RankingScreen.refresh();
requestHandler.showAds(false);
} else{
requestHandler.showAds(false);
}
m_State = state;
}
public void resetGame() {
m_GameScreen.reset();
m_State = State.READY;
}
public void closeGame() {
Gdx.app.exit();
}
#Override
public void pause() {
if (m_State == State.RUNNING)
setState(State.PAUSED);
}
#Override
public void resume() {
if (!m_Loaded) {
while (!m_Loaded) {
if (m_Assets.getAssetManager().update()) {
m_Loaded = true;
}
}
}
}

Related

Playing multiple clips the same time android studio - use threads?

Im creating an app in android studio where I want 10 clips to be played at the same time side by side. Im having some problems with some lags already at three clips and I wounder if Im better off using threads? In that case how?
Any hint would be very much apreciated
Here is my code so far. I know it is not very efficient and I am better off using an array of a player object for example but Im just testing so far:
public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {
private MediaPlayer mp1, mp2, mp3;
private TextureView tv1, tv2, tv3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = findViewById(R.id.textureView1);
tv2 = findViewById(R.id.textureView2);
tv3 = findViewById(R.id.textureView3);
tv1.setSurfaceTextureListener(this);
tv2.setSurfaceTextureListener(this);
tv3.setSurfaceTextureListener(this);
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
Surface surface = new Surface(surfaceTexture);
mp1 = MediaPlayer.create(this, R.raw.a7);
mp1.setSurface(surface);
// mp1.prepareAsync(); //
mp1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp1) {
mp1.start();
}
});
Surface surface2 = new Surface(surfaceTexture);
mp2 = MediaPlayer.create(this, R.raw.a9);
mp2.setSurface(surface2);
// mp1.prepareAsync(); //
mp2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp2) {
mp2.start();
}
});
Surface surface3 = new Surface(surfaceTexture);
mp3 = MediaPlayer.create(this, R.raw.a10);
mp3.setSurface(surface3);
// mp1.prepareAsync(); //
mp3.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp3) {
mp3.start();
}
});
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
#Override
protected void onPause() {
if (mp1 != null && mp1.isPlaying()) {
mp1.pause();
}
super.onPause();
}
#Override
protected void onResume() {
if (mp1 != null) {
mp1.start();
}
super.onResume();
}
#Override
protected void onDestroy() {
if (mp1 != null) {
mp1.stop();
mp1.release();
mp1 = null;
}
super.onDestroy();
}
}
You should play media in a different non-ui thread. like this:-
public class MediaService extends Service {
private MediaPlayer mp1, mp2, mp3;
private static final String ACTION_START = TAG + ".ACTION_START";
private IBinder mBinder = new MyBinder();
private MediaPlayer.OnPreparedListener mMediaPrepared = new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "MediaPlayer.onPrepared");
onCommandPlay(mp);
}
};
#Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "onBind");
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
m1 = MediaPlayer.create(this, R.raw.a1);
m2 = MediaPlayer.create(this, R.raw.a2);
m3 = MediaPlayer.create(this, R.raw.a9);
}
#Override
public void onDestroy() {
super.onDestroy();
if (m1 != null) m1 .release();
if (m2 != null) m2 .release();
if (m3 != null) m3 .release();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String action = intent.getAction();
Log.d(TAG, "onStartCommand: " + intent.getAction());
if (ACTION_START.equals(action)) {
onCommandStart();
return START_STICKY;
}
stopSelf();
return Service.START_STICKY_COMPATIBILITY;
}
/**
* Performs actions related to media player when Service onStartCommand method is called
*
*/
private void onCommandStart() {
// Create Notifications with remote views
mNotification = new NotificationCompat.Builder(this).setTicker("Media Service started...")
.setSmallIcon(R.mipmap.ic_launcher)
.setContent(collapsed)
.setAutoCancel(false)
.setOngoing(true)
.build();
startForeground(NOTIFICATION_ID, mNotification);
startPlaying();
}
private void onCommandPlay(MediaPlayer mp) {
try {
mp.start();
} catch (IllegalStateException e) {
Log.e(TAG, "onCommandPlay", e);
}
}
/**
* Start playing the provided media item
*
*/
private void startPlaying() {
mCurrent = item;
try {
mp1.reset();
mp1.setOnPreparedListener(mMediaPrepared);
mp2.reset();
mp2.setOnPreparedListener(mMediaPrepared);
mp3.reset();
mp3.setOnPreparedListener(mMediaPrepared);
AssetFileDescriptor afd1 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a9););
AssetFileDescriptor afd2 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a10););
AssetFileDescriptor afd3 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a8););
mp1.setDataSource(afd1 .getFileDescriptor(), afd1 .getStartOffset(), afd1.getLength());
mp2.setDataSource(afd2 .getFileDescriptor(), afd2 .getStartOffset(), afd2 .getLength());
mp3.setDataSource(afd3 .getFileDescriptor(), afd3 .getStartOffset(), afd3 .getLength());
mp1.prepareAsync();
mp2.prepareAsync();
mp3.prepareAsync();
} catch (IOException e) {
Log.e(TAG, "startPlaying", e);
}
}
public class MyBinder extends Binder {
public MediaService getService() {
return MediaService.this;
}
}
}
then start the service from Activity like this:
Intent intent = new Intent(context, MediaService.class);
intent.setAction(ACTION_START);
startServie(intent);
You should also handle different media playing use-cases. You can refer this link for more.

Data transfer between the Activities of Android

I have problem I create small application with first get sms code if length it is greater than six go to activity B. Activity B show scan QR Code. Scan QR Code use library google play services vision to scan QR Code. Get value with barcode and make mix with sms code if value is correct go to Activity C if not go to activity A. My question how get value sms code and barcode value and where make ctrytography.
this is class with get sms code
public class SmsCodeActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
}
public final static String EXTRA_MESSAGE = "smsCode";
private EditText smsCode;
private Button checkSmsCodeButton;
private TextView text_info;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_code);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_restart);
Typeface custom_fonts = Typeface.createFromAsset(getAssets(), "fonts/OpenSans-Light.ttf");
Typeface custom_fonts2 = Typeface.createFromAsset(getAssets(), "fonts/OpenSans-Regular.ttf");
TextView titleActivity = (TextView) findViewById(R.id.smsTitle);
titleActivity.setTypeface(custom_fonts2);
TextView subtitleApplication = (TextView) findViewById(R.id.stage1TextView);
subtitleApplication.setTypeface(custom_fonts2);
TextView subtitleText = (TextView) findViewById(R.id.subtitle_text);
subtitleText.setTypeface(custom_fonts);
text_info = (TextView) findViewById(text_Info);
text_info.setTypeface(custom_fonts2);
text_info.setVisibility(View.INVISIBLE);
smsCode = (EditText) findViewById(R.id.editTextSmsCode);
smsCode.setTypeface(custom_fonts);
checkSmsCodeButton = (Button) findViewById(R.id.buttonSmsCode);
checkSmsCodeButton.setTypeface(custom_fonts2);
checkSmsCodeButton.setOnClickListener(this);
setSupportActionBar(toolbar);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.buttonSmsCode) {
String smsText = smsCode.getText().toString();
if (smsText.isEmpty()) {
text_info.setVisibility(View.VISIBLE);
text_info.setText("Nie podałeś SMS Kodu");
} else if (smsText.length() < 6) {
text_info.setVisibility(View.VISIBLE);
text_info.setText("Podany SMS Kod jest za krótki");
} else if (smsText.length() == 6) {
Intent intent = new Intent(SmsCodeActivity.this, ScanQrCodeActivity.class);
intent.putExtra(EXTRA_MESSAGE, smsText);
startActivity(intent);
}
}
}
}
this is class with Scan OR Code
public class ScanQrCodeActivity extends AppCompatActivity {
SurfaceView cameraPreview;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qr_code);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_restart);
Typeface custom_fonts = Typeface.createFromAsset(getAssets(), "fonts/OpenSans-Regular.ttf");
TextView title_app = (TextView) findViewById(R.id.title_application_scan);
title_app.setTypeface(custom_fonts);
cameraPreview = (SurfaceView) findViewById(R.id.cameraPreview);
createCameraSource();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void createCameraSource() {
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build();
final CameraSource cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(1600, 1024)
.build();
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(ScanQrCodeActivity.this, Manifest.permission.CAMERA)) {
try {
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
} else {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() > 0) {
}
}
});
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("ScanQrCode Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
I think you need to get into Intents:
https://developer.android.com/guide/components/intents-filters.html
sending:
String text = "some text here";
Intent i = new Intent(this, ActivityB.class);
i.putExtra("interesting_text", text);
startActivity(i);
receiving:
Intent intent = getIntent();
String text = intent.getExtras().getString("interesting_text");

How to keep Flashlight ON while press on home button?

I am developing a very simple flashlight application, while I have successfully achieved what I was looking for, I would like to perform it that way I want it to. Currently my flashlight remains on while my activity is active, as soon as I hit the home button to minimize the activity flashlight turns off. I want the flashlight to stay on and turn off only when I click the turn off button in my activity.
public class FlashLightActivity extends Activity {
ImageButton btnSwitch;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
/*
* First check if device is supporting flashlight or not
*/
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(FlashLightActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
/*
* Switch button click event to toggle flash on/off
*/
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
/*
* Get the camera
*/
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Playing sound
* will play button toggle sound on flash on / off
* */
private void playSound(){
if(isFlashOn){
mp = MediaPlayer.create(FlashLightActivity.this, R.raw.light_switch_off);
}else{
mp = MediaPlayer.create(FlashLightActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.on);
}else{
btnSwitch.setImageResource(R.drawable.off);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}

Google Maps Fragment replacing current fragment

Background:
Create an app that will center on the user's location and allow for them to text their location to contacts. To do this, we need a simple credential check and server address to test on in the preferences.
Issue:
Whenever the user navigates from the original map fragment that shows their location with a marker, the proper map type (hybrid), etc. to another fragment and then wants to return to the map fragment, it defaults to LatLng 0,0 and a generic map (no indication of user location for example).
My initial thought was to try and save the state of the map fragment upon switching to another fragment and reload that when popping the other fragment from the stack. However I then thought it might be simpler to just replace the current fragment in the MainActivity whenever I need to switch. So on opening the app, MainActivity creates a new MapFragment then replaces it with a Preferences Fragment and when 'saving' creates a new MapFragment to replace the current fragment with. Thought this might fix my problem as on initial load the map functions like I want.
The code for MFragment that contains the Map Fragment:
public class MFragment extends Fragment implements android.location.LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private static GoogleMap map;
private static LocationClient lClient;
private final static String TAG = "MFragment";
private String provider;
private Location loc;
private LocationManager lManager;
private LatLng currentLatLng;
private final long MIN_TIME = 1000;
private final float MIN_DIST = 10;
private Update updateMarkers = new Update();
private View view;
private MapFragment mFrag;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mFrag = MapFragment.newInstance();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
//sets the layout for this fragment
view = inflater.inflate(R.layout.fragment_map, container, false);
//insert MapFragment into this Fragment
getActivity().getFragmentManager().beginTransaction()
.replace(R.id.mapview, mFrag)
.commit();
//get a handle on the map from the MapFragment
// map = mFrag.getMap();
//instantiates the location manager
lManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
//instantiate the location client
lClient = new LocationClient(getActivity(), this, this);
lClient.connect();
//run through initialization of all objects
setUpMapIfNeeded();
Log.d(TAG, "Successfully created MFragment");
return view;
}
/**
* instantiates map from the MapFragment if map is null.
*/
private void setUpMapIfNeeded() {
if (getActivity() != null && getActivity().getFragmentManager() != null &&
map == null) {
map = mFrag.getMap();
Log.d(TAG, "Map generated.");
setUpMap();
} else if (lClient.isConnected()) {
updateMap();
} else {
setUpMap();
}
}
/**
* sets up the location data for the map. conditional clause so that the GPS doesn't crash
* if the app can't get a location straight away.
*/
private void setUpMap() {
if (map != null) {
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Criteria crit = new Criteria();
provider = lManager.getBestProvider(crit, false);
if (lManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
loc = lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} else {
loc = lManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
lManager.requestLocationUpdates(provider, MIN_TIME, MIN_DIST, this);
}
}
protected void updateMap() {
if (servicesConnected()) {
map.clear();
currentLatLng = new LatLng(this.loc.getLatitude(), this.loc.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 14));
map.addMarker(new MarkerOptions()
.position(currentLatLng)
.title("You"));
map.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker m) {
SMSFragment sFrag = new SMSFragment();
sFrag.setMarker(m);
getActivity().getFragmentManager().beginTransaction()
.replace(android.R.id.content, sFrag)
.commit();
return false;
}
});
}
}
/**
* checks for connection to google play services
* #return
*/
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getActivity().getApplicationContext());
if (ConnectionResult.SUCCESS == resultCode) {
Log.d(TAG, getString(R.string.play_available));
return true;
} else {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil
.getErrorDialog(resultCode, getActivity(),
CONNECTION_FAILURE_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported");
}
return false;
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult
.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), R.string.connect_failed, Toast.LENGTH_SHORT).show();
}
}
/**
* Called after location client connects
*/
#Override
public void onConnected(Bundle arg0) {
updateMap();
}
/**
* simple display message after disconnecting.
*/
#Override
public void onDisconnected() {
Toast.makeText(getActivity(), R.string.disconnected, Toast.LENGTH_SHORT).show();
}
public void onStart() {
super.onStart();
lClient.connect();
setUpMapIfNeeded();
}
public void onResume() {
super.onResume();
lClient.connect();
setUpMapIfNeeded();
}
public void onPause() {
lClient.disconnect();
super.onPause();
}
public void onStop() {
lClient.disconnect();
super.onStop();
}
public void onDestroy() {
lClient.disconnect();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
this.loc = location;
updateMap();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void updateMarkers(List<Record> records){
//update map with markers corresponding to each latitude, longitude passed back from records
for (Record r : records){
map.addMarker( new MarkerOptions()
.position(new LatLng(r.getValueOfLatitude(), r.getValueOfLongitude())));
}
}
private class Update extends AsyncTask<Void, Void, Boolean> {
private List<Record> records;
protected Update() {
super();
records = new ArrayList<Record>();
}
#Override
protected Boolean doInBackground(Void... params) {
Connect conn = new Connect(getActivity());
try {
records = conn.getAll();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if (result) {
updateMarkers(records);
} else {
Toast.makeText(getActivity(), R.string.rec_fail, Toast.LENGTH_SHORT).show();
}
}
}
}
And an example of replacing the Fragment from another Fragment (From PrefsFragment to MFragment):
register = (Button) v.findViewById(R.id.register);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveToPreferences(v);
((MainActivity)getActivity()).replaceFragment();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getFragmentManager().beginTransaction()
.replace(android.R.id.content, new RegFragment())
.commit();
}
});
return v;
}
the save button calls a method in MainActivity to replace the current fragment with a MapFragment as an attempted work-around but doesn't function like I was hoping and using the similar method for the register button using FragmentManager doesn't fix the Map issue either.
Any help is appreciated.
Don't put a fragment inside another fragment unless you really need to. If you choose to do so, you may not use the FragmentManager of the Activity like you do. Instead you must use the child fragment manager of the container fragment to create the fragment transaction that will insert the child fragment by calling getChildFragmentManager().
This is supported since API level 17 (Android 4.2) or using the most recent Android Support Library. I suggest you to always use the support library by default.

Running Bluetooth as background service not working properly

*I am new in android any help please help me and thanks in advance.
I want that bluetooth is always connected in app while switching from one activity to another. so I am making background service . There are two classes first class shows the list of paired device and second class is used to run the bluetooth as background service . There is no error Everything is fine but when I switch the activity Bluetooth is disconnected and also it didn't show the status changed. Ask me If you need any additional information *
This is my first class Homescreen class
public class Homescreen extends Activity {
public static Homescreen home;
private Button mBtnSearch;
private Button mBtnConnect;
private ListView mLstDevices;
private BluetoothAdapter mBTAdapter;
private static final int BT_ENABLE_REQUEST = 10; // This is the code we use for BT Enable
private static final int SETTINGS = 20;
private UUID mDeviceUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID
// (http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord%28java.util.UUID%29)
private int mBufferSize = 50000; //Default
public static final String DEVICE_EXTRA = "com.blueserial.SOCKET";
public static final String DEVICE_UUID = "com.blueserial.uuid";
private static final String DEVICE_LIST = "com.blueserial.devicelist";
private static final String DEVICE_LIST_SELECTED = "com.blueserial.devicelistselected";
public static final String BUFFER_SIZE = "com.blueserial.buffersize";
private static final String TAG = "BlueTest5-Homescreen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
home=this;
ActivityHelper.initialize(this); //This is to ensure that the rotation persists across activities and not just this one
Log.d(TAG, "Created");
mBtnSearch = (Button) findViewById(R.id.btnSearch);
mBtnConnect = (Button) findViewById(R.id.btnConnect);
mLstDevices = (ListView) findViewById(R.id.lstDevices);
/*
*Check if there is a savedInstanceState. If yes, that means the onCreate was probably triggered by a configuration change
*like screen rotate etc. If that's the case then populate all the views that are necessary here
*/
if (savedInstanceState != null) {
ArrayList<BluetoothDevice> list = savedInstanceState.getParcelableArrayList(DEVICE_LIST);
if(list!=null){
initList(list);
MyAdapter adapter = (MyAdapter)mLstDevices.getAdapter();
int selectedIndex = savedInstanceState.getInt(DEVICE_LIST_SELECTED);
if(selectedIndex != -1){
adapter.setSelectedIndex(selectedIndex);
mBtnConnect.setEnabled(true);
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
mBtnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBTAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth not found", Toast.LENGTH_SHORT).show();
} else if (!mBTAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, BT_ENABLE_REQUEST);
} else {
new SearchDevices().execute();
}
}
});
mBtnConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intt=new Intent(Homescreen.this,BluetoothService.class);
//bindService( intt, null, Context.BIND_AUTO_CREATE);
BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
intt.putExtra(DEVICE_EXTRA, device);
intt.putExtra(DEVICE_UUID, mDeviceUUID.toString());
intt.putExtra(BUFFER_SIZE, mBufferSize);
startService(intt);
// Toast.makeText(Homescreen.this, "Device Connected", Toast.LENGTH_LONG).show();
// BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
// Intent intent = new Intent(getApplicationContext(), MainBluetooth.class);
// intent.putExtra(DEVICE_EXTRA, device);
// intent.putExtra(DEVICE_UUID, mDeviceUUID.toString());
// intent.putExtra(BUFFER_SIZE, mBufferSize);
// startActivity(intent);
}
});
}
/**
* Called when the screen rotates. If this isn't handled, data already generated is no longer available
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
MyAdapter adapter = (MyAdapter) (mLstDevices.getAdapter());
ArrayList<BluetoothDevice> list = (ArrayList<BluetoothDevice>) adapter.getEntireList();
if (list != null) {
outState.putParcelableArrayList(DEVICE_LIST, list);
int selectedIndex = adapter.selectedIndex;
outState.putInt(DEVICE_LIST_SELECTED, selectedIndex);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case BT_ENABLE_REQUEST:
if (resultCode == RESULT_OK) {
msg("Bluetooth Enabled successfully");
new SearchDevices().execute();
} else {
msg("Bluetooth couldn't be enabled");
}
break;
case SETTINGS: //If the settings have been updated
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String uuid = prefs.getString("prefUuid", "Null");
mDeviceUUID = UUID.fromString(uuid);
Log.d(TAG, "UUID: " + uuid);
String bufSize = prefs.getString("prefTextBuffer", "Null");
mBufferSize = Integer.parseInt(bufSize);
String orientation = prefs.getString("prefOrientation", "Null");
Log.d(TAG, "Orientation: " + orientation);
if (orientation.equals("Landscape")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if (orientation.equals("Portrait")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (orientation.equals("Auto")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Quick way to call the Toast
* #param str
*/
private void msg(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
/**
* Initialize the List adapter
* #param objects
*/
private void initList(List<BluetoothDevice> objects) {
final MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, R.id.lstContent, objects);
mLstDevices.setAdapter(adapter);
mLstDevices.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setSelectedIndex(position);
mBtnConnect.setEnabled(true);
}
});
}
/**
* Searches for paired devices. Doesn't do a scan! Only devices which are paired through Settings->Bluetooth
* will show up with this. I didn't see any need to re-build the wheel over here
* #author ryder
*
*/
private class SearchDevices extends AsyncTask<Void, Void, List<BluetoothDevice>> {
#Override
protected List<BluetoothDevice> doInBackground(Void... params) {
Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device : pairedDevices) {
listDevices.add(device);
}
return listDevices;
}
#Override
protected void onPostExecute(List<BluetoothDevice> listDevices) {
super.onPostExecute(listDevices);
if (listDevices.size() > 0) {
MyAdapter adapter = (MyAdapter) mLstDevices.getAdapter();
adapter.replaceItems(listDevices);
} else {
msg("No paired devices found, please pair your serial BT device and try again");
}
}
}
/**
* Custom adapter to show the current devices in the list. This is a bit of an overkill for this
* project, but I figured it would be good learning
* Most of the code is lifted from somewhere but I can't find the link anymore
* #author ryder
*
*/
private class MyAdapter extends ArrayAdapter<BluetoothDevice> {
private int selectedIndex;
private Context context;
private int selectedColor = Color.parseColor("#abcdef");
private List<BluetoothDevice> myList;
public MyAdapter(Context ctx, int resource, int textViewResourceId, List<BluetoothDevice> objects) {
super(ctx, resource, textViewResourceId, objects);
context = ctx;
myList = objects;
selectedIndex = -1;
}
public void setSelectedIndex(int position) {
selectedIndex = position;
notifyDataSetChanged();
}
public BluetoothDevice getSelectedItem() {
return myList.get(selectedIndex);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public BluetoothDevice getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView tv;
}
public void replaceItems(List<BluetoothDevice> list) {
myList = list;
notifyDataSetChanged();
}
public List<BluetoothDevice> getEntireList() {
return myList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.tv = (TextView) vi.findViewById(R.id.lstContent);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (selectedIndex != -1 && position == selectedIndex) {
holder.tv.setBackgroundColor(selectedColor);
} else {
holder.tv.setBackgroundColor(Color.WHITE);
}
BluetoothDevice device = myList.get(position);
holder.tv.setText(device.getName() + "\n " + device.getAddress());
return vi;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homescreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(Homescreen.this, PreferencesActivity.class);
startActivityForResult(intent, SETTINGS);
break;
}
return super.onOptionsItemSelected(item);
}
}
This is my second class BluetoothService Class
public class BluetoothService extends Service {
public static BluetoothService service;
private boolean mConnectSuccessful = true;
private static boolean isRunning = false;
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
//private UUID mDeviceUUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private boolean mIsBluetoothConnected = false;
//private BluetoothDevice mDevice=Homescreen.home.device;
private BluetoothDevice mDevice;
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
// Intent intt = getIntent();
// Bundle b = intt.getExtras();
// mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
// mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
// mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
// super.onStart(intent, startId);
}
#Override
public void onCreate() {
service=this;
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
// TODO Auto-generated method stub
// Intent intent = getIntent();
// Bundle b = intent.getExtras();
// mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
// mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
// mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
super.onCreate();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Bundle b = intent.getExtras();
mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
Log.i("mDeviceUUID", ""+mDeviceUUID);
Log.d("mDevice",""+mDevice );
new ConnectBT().execute();
return START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
public boolean isRunning() {
return isRunning;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
super.onDestroy();
}
class ConnectBT extends AsyncTask<Void, Void, Void> {
//ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// http://stackoverflow.com/a/11130220/1287554
// progressDialog = ProgressDialog.show(BluetoothService.this, "Hold on", "Connecting");
Log.d("check check check", "check1");
}
#Override
protected Void doInBackground(Void... devices) {
Log.d("check check check", "check2");
try {
Log.e("check check check", "check3");
if (mBTSocket == null || !mIsBluetoothConnected) {
Log.e("UUID", ""+mDeviceUUID);
Log.e("mDevice", ""+mDevice);
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
Log.d("check check check", "check4");
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
Log.d("check check check", "check5");
// Toast.makeText(BluetoothService.this, "background service start", Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(BluetoothService.this, "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
Log.e("Device Status in service", "Disconnected");
} else {
Toast.makeText(BluetoothService.this, "Connected to device", Toast.LENGTH_SHORT).show();
Log.e("Device Status in service", "Device Connected");
mIsBluetoothConnected = true;
// Kick off input reader
}
//progressDialog.dismiss();
}
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
Log.e("Bluetooth device connected","BT Connected");
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Do something if disconnected
Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
Log.e("Bluetooth device disconnected","BT Disconnected");
}
//else if...
}
};
}
Android's AsyncTask class will help you. Do the bluetooth discovery task in the doInBackground() method of AsyncTask.You can Toast a message a after the task in the onPostExecute() method. Here is sample code snippet to demonstrate the use of AsyncTask

Categories

Resources