Im Sorry, Please Help. I have MainActivity and 2 IntentService. I want to change my MainActivity Variables (kabupaten and provinsi) from variables that get from FetchAddressIntentService. Then, i want to give that variables (kabupaten and provinsi) to another intent (ParseXmlCuaca).. The problem is kabupaten and provinsi variables is null, although FetchAddressIntentService has already run. How to solve this problem? Sorry For my bad english.. And Thanks For help....
Main Activity Code
package com.example.gawaipintarcuaca;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private TextView lokasi;
private TextView waktu;
private FusedLocationProviderClient fusedLocationProviderClient;
protected Location lastLocation;
private AddressResultReceiver resultReceiver;
private LocationCallback locationCallback;
private TextView suhu;
public static String kabupaten;
public static String provinsi;
private String kodeCuaca;
private Date date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultReceiver = new AddressResultReceiver(new Handler());
lokasi = findViewById(R.id.kota);
date = Calendar.getInstance().getTime();
waktu = findViewById(R.id.waktu);
waktu.setText(date.toString());
//Ambil Lokasi
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION}, 2);
}
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
lastLocation = location;
startIntentService();
}
}
});
startIntentService1();
suhu = findViewById(R.id.suhu);
}
protected void startIntentService(){
Intent intent = new Intent (this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, resultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, lastLocation);
startService(intent);
}
private void startIntentService1() {
Intent intent = new Intent(this, ParseXmlCuaca.class);
Bundle bundle = new Bundle();
bundle.putString("kabupaten", kabupaten);
bundle.putString("provinsi", provinsi);
intent.putExtra("Bundle", bundle);
startService(intent);
}
private class AddressResultReceiver extends ResultReceiver{
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultData == null){
return;
}
String addressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
kabupaten = resultData.getString("kabupaten");
String[] kab = kabupaten.split(" ");
MainActivity.kabupaten = "";
int kabLength = kab.length;
for (int i = 1; i < kabLength; i++ ){
if (i == kabLength - 1){
MainActivity.kabupaten += kab[i];
}
else{
MainActivity.kabupaten += kab[i] + " ";
}
}
MainActivity.provinsi = resultData.getString("provinsi");
showResult(addressOutput);
}
private void showResult(String addressOutput) {
lokasi.setText(addressOutput);
}
}
}
FetcAddressIntentService
package com.example.gawaipintarcuaca;
import android.app.IntentService;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FetchAddressIntentService extends IntentService {
public static final String TAG = "Service Lokasi";
protected ResultReceiver receiver;
public String provinsi;
public String kabupaten;
public FetchAddressIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
if (intent == null) {
return;
}
String errorMessage = " ";
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
receiver = intent.getParcelableExtra(Constants.RECEIVER);
List <Address> addresses = null;
try{
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
1);
}
catch (IOException ioException){
errorMessage = getString(R.string.service_not_available);
Log.e(TAG, errorMessage, ioException);
}
catch (IllegalArgumentException illegalArgumentException){
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e(TAG, errorMessage + ". " + "Latitude = "
+ location.getLatitude() + ", Longitude = " +
location.getLongitude(), illegalArgumentException);
}
if (addresses == null || addresses.size() == 0){
if (errorMessage.isEmpty()){
errorMessage = getString(R.string.no_address_found);
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
}
else{
Address address = addresses.get(0);
ArrayList <String> addressFragments = new ArrayList<String>();
for (int i = 0 ; i <= address.getMaxAddressLineIndex(); i++){
addressFragments.add(address.getAddressLine(i));
}
Log.i(TAG, getString(R.string.address_found));
kabupaten = address.getSubAdminArea();
provinsi = address.getAdminArea();
deliverResultToReceiver(Constants.SUCCESS_RESULT, TextUtils.join(System.getProperty("line.seperator"),addressFragments));
}
}
private void deliverResultToReceiver(int resultCode, String message) {
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, message);
bundle.putString("kabupaten", kabupaten);
bundle.putString("provinsi", provinsi);
receiver.send(resultCode, bundle);
}
}
move startIntentService1(); from the end of onCreate to end of onReceiveResult in AddressResultReceiver, after you receive and store these two needed variables
currently you are starting ParseXmlCuaca Service at very beginning of Activity lifecycle, before your Activity gets location and fetch data in AddressResultReceiver. thats why both values are null, they aren't initiated (yet)
Related
I've been working on this for the past few days and have tried different codes, but none of them have worked so far. I'm trying to make an activity that takes the user's current location and displays nearby hospitals to them.
Here's the code I'm using (it's the 1 I found online that doesn't crash android studio):
activity_hospitals.java (The draw() function is where I place markers):
package com.example.mobileproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.CancellationTokenSource;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.maps.model.PlacesSearchResult;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class activity_hospitals extends FragmentActivity implements OnMapReadyCallback {
Toolbar mytoolbar;
GoogleMap Gmap;
FusedLocationProviderClient flsc;
public LatLng here;
public double longo, lato;
Button Test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospitals);
Test=findViewById(R.id.btnGet);
Test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if (here == null)
Toast.makeText(activity_hospitals.this, "Success!", Toast.LENGTH_SHORT).show();
else{
Toast.makeText(activity_hospitals.this, "Error", Toast.LENGTH_SHORT).show();
draw();
}
}
catch(Exception e){
}
}
});
mytoolbar = (Toolbar) findViewById(R.id.hospitalToolbar);
mytoolbar.setTitle("Hospitals Near You");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
flsc = LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Gmap = googleMap;
}
public void draw(){
here = new LatLng(33.71456158807447, 35.48425016137045);
Gmap.addMarker(new MarkerOptions().position(here).title("Your Location").snippet("Your last recorded location"));
float zoomLevel = 11.0f; //This goes up to 21
Gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(here, zoomLevel));
double lat = here.latitude;
double lng = here.longitude;
StringBuilder sb = new StringBuilder("http://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+ 33.71456158807447 + "," + 35.48425016137045);
sb.append("&radius=1000");
sb.append("&types=hospital|health");
sb.append("&sensor=true");
sb.append("&key=" +getResources().getString(R.string.map_key));
String url=sb.toString();
Object dataFetch[] = new Object[2];
dataFetch[0] = Gmap;
dataFetch[1] = url;
FetchData fetchData = new FetchData();
fetchData.execute(dataFetch);
}
public void getLastLocation(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
flsc.getLastLocation().addOnSuccessListener(this, location -> {
if (location != null) {
longo = location.getLatitude();
lato = location.getLongitude();
here = new LatLng(lato, longo);
}
});
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 100){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
getLastLocation();
}
else{
Toast.makeText(this, "Required Permission", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
DownloadURL.java:
package com.example.mobileproject;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadURL {
public String retrieveUrl(String url) throws IOException {
String urlData="";
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
URL getUrl = new URL(url);
httpURLConnection = (HttpURLConnection) getUrl.openConnection();
httpURLConnection.connect();
inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer sb = new StringBuffer();
String line ="";
while((line = bufferedReader.readLine())!=null){
sb.append(line);
}
urlData = sb.toString();
bufferedReader.close();//////
}catch(Exception e){
Log.d("Exception", e.toString());
}finally{
inputStream.close();
httpURLConnection.disconnect();
}
return urlData;
}
}
FetchData.java:
package com.example.mobileproject;
import android.os.AsyncTask;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
public class FetchData extends AsyncTask<Object, String, String> {
String googleNearByPlacesData;
GoogleMap googleMap;
String url;
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsOnObject = jsonArray.getJSONObject(i);
JSONObject getLocation=jsOnObject.getJSONObject("geometry").getJSONObject("location");
String lat = getLocation.getString("lat");
String lng = getLocation.getString("lng");
JSONObject getName = jsonArray.getJSONObject(i);
String name = getName.getString("name");
LatLng latlng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.title(name);
markerOptions.position(latlng);
googleMap.addMarker(markerOptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Object... objects) {
try{
googleMap = (GoogleMap) objects[0];
url = (String) objects[1];
DownloadURL downloadURL = new DownloadURL();
googleNearByPlacesData = downloadURL.retrieveUrl(url);
} catch (IOException e) {
e.printStackTrace();
}
return googleNearByPlacesData;
}
}
I've also tried a different way using PlacesSearchResponse request = new PlacesSearchResponse(); that I found in a stackoverflow post. It also didn't crash the application, but it didn't work.
I have the following code that runs in a service where it captures screenshots from Android. What technology could I use to send a remote command to this service to execute the task? I don't want it to run from a MainActivity button. Firebase cloud messaging ? Websocket ?
ScreenCaptureService.java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.Display;
import android.view.OrientationEventListener;
import android.view.WindowManager;
import androidx.annotation.RequiresApi;
import androidx.core.util.Pair;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Objects;
public class ScreenCaptureService extends Service {
private static final String TAG = "ScreenCaptureService";
private static final String RESULT_CODE = "RESULT_CODE";
private static final String DATA = "DATA";
private static final String ACTION = "ACTION";
private static final String START = "START";
private static final String STOP = "STOP";
private static final String SCREENCAP_NAME = "screencap";
private static int IMAGES_PRODUCED;
private MediaProjection mMediaProjection;
private String mStoreDir;
private ImageReader mImageReader;
private Handler mHandler;
private Display mDisplay;
private VirtualDisplay mVirtualDisplay;
private int mDensity;
private int mWidth;
private int mHeight;
private int mRotation;
private OrientationChangeCallback mOrientationChangeCallback;
public static Intent getStartIntent(Context context, int resultCode, Intent data) {
Intent intent = new Intent(context, ScreenCaptureService.class);
intent.putExtra(ACTION, START);
intent.putExtra(RESULT_CODE, resultCode);
intent.putExtra(DATA, data);
return intent;
}
public static Intent getStopIntent(Context context) {
Intent intent = new Intent(context, ScreenCaptureService.class);
intent.putExtra(ACTION, STOP);
return intent;
}
private static boolean isStartCommand(Intent intent) {
return intent.hasExtra(RESULT_CODE) && intent.hasExtra(DATA)
&& intent.hasExtra(ACTION) && Objects.equals(intent.getStringExtra(ACTION), START);
}
private static boolean isStopCommand(Intent intent) {
return intent.hasExtra(ACTION) && Objects.equals(intent.getStringExtra(ACTION), STOP);
}
private static int getVirtualDisplayFlags() {
return DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY | DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC;
}
private class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
#Override
public void onImageAvailable(ImageReader reader) {
FileOutputStream fos = null;
Bitmap bitmap = null;
try (Image image = mImageReader.acquireLatestImage()) {
if (image != null) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * mWidth;
// create bitmap
bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
// write bitmap to a file
fos = new FileOutputStream(mStoreDir + "/myscreen_" + IMAGES_PRODUCED + ".png");
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
IMAGES_PRODUCED++;
Log.e(TAG, "captured image: " + IMAGES_PRODUCED);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
}
private class OrientationChangeCallback extends OrientationEventListener {
OrientationChangeCallback(Context context) {
super(context);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onOrientationChanged(int orientation) {
final int rotation = mDisplay.getRotation();
if (rotation != mRotation) {
mRotation = rotation;
try {
// clean up
if (mVirtualDisplay != null) mVirtualDisplay.release();
if (mImageReader != null) mImageReader.setOnImageAvailableListener(null, null);
// re-create virtual display depending on device width / height
createVirtualDisplay();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private class MediaProjectionStopCallback extends MediaProjection.Callback {
#Override
public void onStop() {
Log.e(TAG, "stopping projection.");
mHandler.post(new Runnable() {
#Override
public void run() {
if (mVirtualDisplay != null) mVirtualDisplay.release();
if (mImageReader != null) mImageReader.setOnImageAvailableListener(null, null);
if (mOrientationChangeCallback != null) mOrientationChangeCallback.disable();
mMediaProjection.unregisterCallback(MediaProjectionStopCallback.this);
}
});
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
// create store dir
File externalFilesDir = getExternalFilesDir(null);
if (externalFilesDir != null) {
mStoreDir = externalFilesDir.getAbsolutePath() + "/screenshots/";
File storeDirectory = new File(mStoreDir);
if (!storeDirectory.exists()) {
boolean success = storeDirectory.mkdirs();
if (!success) {
Log.e(TAG, "failed to create file storage directory.");
stopSelf();
}
}
} else {
Log.e(TAG, "failed to create file storage directory, getExternalFilesDir is null.");
stopSelf();
}
// start capture handling thread
new Thread() {
#Override
public void run() {
Looper.prepare();
mHandler = new Handler();
Looper.loop();
}
}.start();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isStartCommand(intent)) {
// create notification
Pair<Integer, Notification> notification = NotificationUtils.getNotification(this);
startForeground(notification.first, notification.second);
// start projection
int resultCode = intent.getIntExtra(RESULT_CODE, Activity.RESULT_CANCELED);
Intent data = intent.getParcelableExtra(DATA);
startProjection(resultCode, data);
} else if (isStopCommand(intent)) {
stopProjection();
stopSelf();
} else {
stopSelf();
}
return START_NOT_STICKY;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startProjection(int resultCode, Intent data) {
MediaProjectionManager mpManager =
(MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (mMediaProjection == null) {
mMediaProjection = mpManager.getMediaProjection(resultCode, data);
if (mMediaProjection != null) {
// display metrics
mDensity = Resources.getSystem().getDisplayMetrics().densityDpi;
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mDisplay = windowManager.getDefaultDisplay();
// create virtual display depending on device width / height
createVirtualDisplay();
// register orientation change callback
mOrientationChangeCallback = new OrientationChangeCallback(this);
if (mOrientationChangeCallback.canDetectOrientation()) {
mOrientationChangeCallback.enable();
}
// register media projection stop callback
mMediaProjection.registerCallback(new MediaProjectionStopCallback(), mHandler);
}
}
}
private void stopProjection() {
if (mHandler != null) {
mHandler.post(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void run() {
if (mMediaProjection != null) {
mMediaProjection.stop();
}
}
});
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#SuppressLint("WrongConstant")
private void createVirtualDisplay() {
// get width and height
mWidth = Resources.getSystem().getDisplayMetrics().widthPixels;
mHeight = Resources.getSystem().getDisplayMetrics().heightPixels;
// start capture reader
mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 2);
mVirtualDisplay = mMediaProjection.createVirtualDisplay(SCREENCAP_NAME, mWidth, mHeight,
mDensity, getVirtualDisplayFlags(), mImageReader.getSurface(), null, mHandler);
mImageReader.setOnImageAvailableListener(new ImageAvailableListener(), mHandler);
}
}
MainActivity.java
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;
import app.mobile.secure.appservice.api.AppUtil;
import app.mobile.secure.appservice.configuracao.Permissao;
import app.mobile.secure.appservice.service.MonitorService;
public class MainActivity extends AppCompatActivity {
private MediaProjectionManager projectionManager;
private static final int REQUEST_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
projectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
startActivityForResult(projectionManager.createScreenCaptureIntent(), REQUEST_CODE);
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
startService(app.mobile.secure.appservice.service.ScreenCaptureService.getStartIntent(this, resultCode, data));
startProjection();
}
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startProjection() {
MediaProjectionManager mProjectionManager =
(MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
}
}
Try using firebase Messaging in conjunction with your backend.
You can read about it here:
https://firebase.google.com/docs/cloud-messaging/?authuser=0#implementation_paths
https://firebase.google.com/docs/cloud-messaging/js/client?authuser=0
I just got the permissions handled through the library Let, but I still can't get a longitude and latitude in my android app. I'm using a service called GPS_Service.java. Also I'm not 100% sure my permissions aren't the issue. The call to the google API in GPS_Service still is underlined with the warning that it requires permissions which might be rejected. Is that supposed to go away even with third party libraries? Would this still be an issue because on my device the app has location permissions enabled?
here is my main activity:
package com.example.paxie.stormy.ui;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.canelmas.let.AskPermission;
import com.canelmas.let.DeniedPermission;
import com.canelmas.let.Let;
import com.canelmas.let.RuntimePermissionListener;
import com.canelmas.let.RuntimePermissionRequest;
import com.example.paxie.stormy.GPS_Service;
import com.example.paxie.stormy.R;
import com.example.paxie.stormy.weather.Current;
import com.example.paxie.stormy.weather.Day;
import com.example.paxie.stormy.weather.Forecast;
import com.example.paxie.stormy.weather.Hour;
import com.google.android.gms.maps.model.LatLng;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements RuntimePermissionListener {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
private Forecast mForecast;
private double mLatitude;
private double mLongitude;
private BroadcastReceiver broadcastReceiver;
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private Context mContext;
#BindView(R.id.timeLabel)
TextView mTimeLabel;
#BindView(R.id.temperatureLabel)
TextView mTemperatureLabel;
#BindView(R.id.humidityValue)
TextView mHumidityValue;
#BindView(R.id.precipValue)
TextView mPrecipValue;
#BindView(R.id.summaryLabel)
TextView mSummaryLabel;
#BindView(R.id.iconImageView)
ImageView mIconImageView;
#BindView(R.id.refreshImageView)
ImageView mRefreshImageView;
#BindView(R.id.progressBar)
ProgressBar mProgressBar;
#BindView(R.id.locationLabel)
TextView mLocationlabel;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Let.handle(this, requestCode, permissions, grantResults);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast();
}
});
getForecast();
Log.d(TAG, "Main UI code is running!");
}
private void getForecast() {
checkGPS();
String apiKey = "1621390f8c36997cb1904914b726df52";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + mLatitude + "," + mLongitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e)
{
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
Toast.makeText(this, "Network is currently unavailable!", Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mLocationlabel.setText(mLatitude + " " + mLongitude);
Current current = mForecast.getCurrent();
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("At " + current.getFormattedTime() + " it will be:");
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
Drawable drawable = ContextCompat.getDrawable(this, current.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrent(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonDay = data.getJSONObject(i);
Day day = new Day();
day.setSummary(jsonDay.getString("summary"));
day.setIcon(jsonDay.getString("icon"));
day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
day.setTime(jsonDay.getLong("time"));
day.setTimeZone(timezone);
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getDouble("temperature"));
hour.setIcon(jsonHour.getString("icon"));
hour.setTime(jsonHour.getLong("time"));
hour.setTimeZone(timezone);
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current();
current.setHumidity(currently.getDouble("humidity"));
current.setTime(currently.getLong("time"));
current.setIcon(currently.getString("icon"));
current.setPrecipChance(currently.getDouble("precipProbability"));
current.setSummary(currently.getString("summary"));
current.setTemperature(currently.getDouble("temperature"));
current.setTimeZone(timezone);
Log.d(TAG, current.getFormattedTime());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
startActivity(intent);
}
#OnClick(R.id.hourlyButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
startActivity(intent);
}
#AskPermission({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
private void checkGPS() {
GPS_Service gps_service = new GPS_Service(this);
gps_service.getLocation();
mLatitude = gps_service.getLatitude();
mLongitude = gps_service.getLongitude();
}
#Override
public void onShowPermissionRationale(List<String> permissionList, RuntimePermissionRequest permissionRequest) {
}
#Override
public void onPermissionDenied(List<DeniedPermission> deniedPermissionList) {
}
}
And here is my GPS_Service.java:
package com.example.paxie.stormy;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.canelmas.let.AskPermission;
import com.canelmas.let.DeniedPermission;
import com.canelmas.let.Let;
import com.canelmas.let.RuntimePermissionListener;
import com.canelmas.let.RuntimePermissionRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import java.util.ArrayList;
import java.util.List;
/**
* Created by paxie on 10/27/16.
*/
public class GPS_Service extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
private static final int RC_GPS_PERMS = 124;
public String[] perm = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
public GPS_Service(Context c) {
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
} catch (Exception e) {
Log.d(TAG, e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void getLocation() {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
In that case enable your GPS and go to google maps and hit the location button, wait until google maps locate u and then go back and test in ur app. This should work because if u are using the first time ur phone without never been conected to GPS it gives u that problem
It is looking for specifically "LastKnownLocation", I had this issue as well. Move about 3 meters and try again. If there is no 'last known location' then it sends a null value.
What I did was set a few if statements for my application. If the GPS Provider was spitting out null values, then use the Network Provider location coordinates, and if that was spitting out null values then I just displayed a message saying "To Wait" or "Try again later". Eventually your GPS Provider will pick up location values after it has been activated for a while.
newLoc = _locationManager.GetLastKnownLocation(_locationProvider);
if (newLoc != null)
{
_latitudeUser = newLoc.Latitude;
_longitudeUser = newLoc.Longitude;
_locationText.Text = string.Format("{0:f6},{1:f6}", newLoc.Latitude, newLoc.Longitude);
}
else
{
_locationProvider = LocationManager.NetworkProvider;
newLoc = _locationManager.GetLastKnownLocation(_locationProvider);
if (newLoc != null)
{
_latitudeUser = newLoc.Latitude;
_longitudeUser = newLoc.Longitude;
_locationText.Text = string.Format("{0:f6},{1:f6}", newLoc.Latitude, newLoc.Longitude);
}
else
{
_locationText.Text = string.Format("We currently cannot determine your location, please try again later.");
}
I am doing a customisation app where the user is buying personalised products. I am trying to do the basket page but it just isn't working. I have an error in the Bundle BuyIntent = mservice.getBuyIntent(3, getPackageName(), sku,"Purchase text item","bGoa+V7g/yqD"); and also in the skuDetails= mservice.getSkuDetails(3, getPackageName(),"Purchase text item", querySku);. It is saying cannot resolve method. Please can someone help, thank you.
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Button;
import android.content.ServiceConnection;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.ResponseCache;
import java.util.ArrayList;
import android.support.v4.os.IResultReceiver.Stub;
import android.support.v7.app.ActionBarActivity;
public class Basket extends AppCompatActivity {
Basket mservice;
ServiceConnection connection;
String purchase = "android.test.purchased";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basket);
connection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mservice = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Stub.asInterface(service);
}};
bindService(new Intent(
"com.example.emily.activity.414timber"),
connection, Context.BIND_AUTO_CREATE);
Button purchaseBtn = (Button) findViewById(R.id.purchase);
purchaseBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
ArrayList skuList = new ArrayList();
skuList.add(purchase);
Bundle querySku = new Bundle();
querySku.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails;
try {
skuDetails= mservice.getSkuDetails(3, getPackageName(),
"Purchase text item", querySku);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0){
ArrayList <String> responseList = skuDetails
.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList){
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
if (sku.equals(purchase)){
System.out.println("price " + price);
Bundle BuyIntent = mservice.getBuyIntent(3, getPackageName(), sku,
"Purchase text item",
"bGoa+V7g/yqD");
PendingIntent pendingIntent= BuyIntent
.getParcelable("BUY_INTENT");
startIntentSenderForResult(
pendingIntent.getIntentSender(),1001,
new Intent(),Integer.valueOf(0),
Integer.valueOf(0), Integer.valueOf(0));
}
}
}
} catch (RemoteException e){
e.printStackTrace();
}catch (JSONException e){
e.printStackTrace();
}catch (IntentSender.SendIntentException e){
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == 1001 ){
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
if (resultCode == RESULT_OK){
try {
JSONObject jo = new JSONObject(purchaseData);
String sku = jo.getString(purchase);
Toast.makeText(
Basket.this,
"You have bought the" + sku
+ "Excellent choice, adventurer!",
Toast.LENGTH_LONG).show();
}catch (JSONException e) {
System.out.println("Failed to parse purchase data.");
e.printStackTrace();
}
}
}
}
#Override
public void onDestroy(){
super.onDestroy();
if (connection != null){
unbindService(connection);
}
}
}
Can you add the declaration for getSkuDetails()? From you error message it sounds like you may be expecting either a different number of arguments or different data types.
Hello I am new to Android. I want to communicate android with pc to send a text file.
I am trying to communicate using following code.
I am using bluetooth dongle to pc.
When i run application it get crashed without any error. Please help me in communication.
enter code here
package com.exam.bluetooth2;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity implements Runnable
{
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_list_item);
mScan = (Button) findViewById(R.id.button1);
mScan.setOnClickListener(new View.OnClickListener()
{
public void onClick(View mView)
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
Toast.makeText(Main.this, "Message1", 2000).show();
}
else
{
if (!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else
{
ListPairedDevices();
Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
}
}
}
});
}
public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent)
{
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode)
{
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK)
{
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
Toast.makeText(getBaseContext(), mBluetoothDevice.getAddress(), 10000).show();
//pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK)
{
ListPairedDevices();
Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
}
else
{
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices()
{
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
for (BluetoothDevice mDevice : mPairedDevices)
{
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
}
}
// Object device = null;
// String dv = device.toString();
// if(dv.contains("00:1B:EE:82:31:1E"))
// {
// mBluetoothDevice = (BluetoothDevice) device;
// }
}
public void run()
{
try
{
mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
String messsage = "Welcome to SmarTec";
byte[] tosend=messsage.getBytes();
OutputStream out=mBluetoothSocket.getOutputStream();
out.write(tosend);
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket)
{
try
{
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
}
catch (IOException ex)
{
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "Device Connected", 5000).show();
// Intent in = new Intent(getBaseContext(), Option.class);
// startActivity(in);
}
};
/* public void sendtext(View v) {//button click
Set<BluetoothDevice> bd = mBluetoothAdapter.getBondedDevices();
sendDataToPairedDevice("message1");
}
private void sendDataToPairedDevice(String message ){
byte[] toSend = message.getBytes();
try {
UUID applicationUUID = UUID.fromString("8ce255c0-200a-11e0-ac64- 0800200c9a66");
BluetoothSocket socket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmOutStream = socket.getOutputStream();
mmOutStream.write(toSend);
} catch (IOException e) {
Log.e( "Exception during write", e.toString());
}
}
*/
}
enter code here
package com.exam.bluetooth2;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
Vijay,
You need to check few thinks below:
Add bluetooth permission in manifest file.
If device is not supporting bluetooth, then you get bluetooth adapter value null. So need to check that also.
Also its better to create broadcast receiver with bluetooth actions.