Android Check network status on every single activity (continuously) - java

Right now I can check network status on a single activity and its really working fine. But suppose I want to check the internet on every single activity. How to modify this code? I tried many ways but failed.
package com.example.wohhi.nointernetsnackbar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView status;
private static final String LOG_TAG = "CheckNetworkStatus";
private NetworkChangeReceiver receiver;
private boolean isConnected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView) findViewById(R.id.status);
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
}
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null) {
if (info.isConnectedOrConnecting()) {
if(!isConnected){
Log.v(LOG_TAG, "Now you are connected to Internet!");
String status = "Now you are connected to Internet!";
Snackbar.make(findViewById(R.id.activity_main), status, Snackbar.LENGTH_LONG).show();
isConnected = true;
//do your processing here ---
//if you need to post any data to the server or get status
//update from the server
}
return true;
}
}
}
Log.v(LOG_TAG, "You are not connected to Internet!");
String status = "You are not connected to Internet!";
Snackbar.make(findViewById(R.id.activity_main), status, Snackbar.LENGTH_LONG).show();
isConnected = false;
return false;
}
}
}

Instead of registering it in onCreate() Create a BroadcastReceiver class outside of activity and register it statically means in Manifest. But this will work for only API level 23 and below as it is given here.
Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

Related

How to navigate to specific activity/fragment after tapping on one signal push notification?

can someone provide me the proper documentation or code to navigate to specific activity by tapping on one signal push notification, i want to open the specific fragment
here is my code where i extened application class and initialize one signal :
package com.example.nasapp;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.util.Log;
import com.example.nasapp.ui.home.HomeFragment;
import com.example.nasapp.ui.information.InformationFragment;
import com.onesignal.OSMutableNotification;
import com.onesignal.OSNotification;
import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenedResult;
import com.onesignal.OSNotificationReceivedEvent;
import com.onesignal.OneSignal;
import org.json.JSONException;
import org.json.JSONObject;
public class OneSignalApplication extends Application {
private static final String ONESIGNAL_APP_ID = "e855e254-9b4e-4e6f-a64a-e48db6f35d07";
#Override
public void onCreate() {
super.onCreate();
// Enable verbose OneSignal logging to debug issues if needed.
//OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
// promptForPushNotifications will show the native Android notification permission prompt.
// We recommend removing the following code and instead using an In-App Message to prompt for notification permission (See step 7)
OneSignal.promptForPushNotifications();
OneSignal.setNotificationOpenedHandler(new OneSignal.OSNotificationOpenedHandler() {
#Override
public void notificationOpened(OSNotificationOpenedResult result) {
JSONObject data = result.getNotification().getAdditionalData();
Log.i("OneSignalExample", "Notification Data: " + data);
String notification_topic;
if (data != null) {
try {
System.out.println(data.getString("job_id"));
} catch (JSONException e) {
e.printStackTrace();
}
notification_topic = data.optString("notification_topic", "hii");
if (notification_topic != null) {
OneSignal.addTrigger("level", notification_topic);
}
}
}
});
}
}
here is my NotificationServiceExtensionClass:
public class NotificationServiceExtension extends Service implements OneSignal.OSRemoteNotificationReceivedHandler {
#Override
public void remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent) {
OSNotification notification = notificationReceivedEvent.getNotification();
// Example of modifying the notification's accent color
OSMutableNotification mutableNotification = notification.mutableCopy();
mutableNotification.setExtender(builder -> {
//... do stuff
builder.setTimeoutAfter(30000);
Intent intent = new Intent();
JSONObject data = notification.getAdditionalData();
// check the data and create intent
intent = new Intent(context, InformationFragment.class);
// or any other depends on data value
intent.putExtra("data", (Parcelable) data);
PendingIntent pendIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder = builder.setContentIntent(pendIntent);
return builder;
});
JSONObject data = notification.getAdditionalData();
Log.i("OneSignalExample", "Received Notification Data: " + data);
// If complete isn't call within a time period of 25 seconds, OneSignal internal logic will show the original notification
// To omit displaying a notification, pass `null` to complete()
notificationReceivedEvent.complete(mutableNotification);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
In manifest i declare this service class:
<service
android:name=".service.NotificationServiceExtension"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false">
am i missing some code or what am i doing wrong in code ,can please someone help?

Wi-fi Scan Broadcast Receiver not Working

I am currently working on a simple Wi-fi scanner android application
with min API level 26 and target API level 28.
I want real time update in scan results so i have created a broadcast receiver but it is not working as intended.
Note: I have already tried
Wifi scan results broadcast receiver not working, Broadcast receiver with wifi scan not working
PLEASE NOTE THAT I WANT EXPLICIT BROADCAST RECEIVER NOT VIA MANIFEST FILE
I will be grateful to you.
Below is my java code:
package com.example.quickshare;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class ActivitySend extends AppCompatActivity {
WifiManager wifiManager;
ListView ScanList;
List<ScanResult> results;
ListAdapter listAdapter;
WifiReceiver wifiReceiver;
IntentFilter intentFilter;
TextView msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
CheckWifiStatus();
msg = findViewById(R.id.wifiStatus);
intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
intentFilter.addAction(WifiManager.EXTRA_RESULTS_UPDATED);
try {
getApplicationContext().registerReceiver(wifiReceiver, intentFilter);
}
catch(Exception e){
System.out.println(e);
}
boolean success = wifiManager.startScan();
if(success)
Toast.makeText(ActivitySend.this, "Scanning", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
CheckWifiStatus();
registerReceiver(wifiReceiver, intentFilter);
wifiManager.startScan();
results = wifiManager.getScanResults();
if (results.size() > 0)
Toast.makeText(ActivitySend.this, "Scan Successful", Toast.LENGTH_LONG).show();
else
Toast.makeText(ActivitySend.this, "No Device Available", Toast.LENGTH_LONG).show();
ScanList = findViewById(R.id.ScanList);
listAdapter = new ListAdapter(getApplicationContext(), results);
ScanList.setAdapter(listAdapter);
ScanList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ActivitySend.this, "Selected" + results.get(position).SSID, Toast.LENGTH_LONG).show();
//TODO: Establish Connection with selected SSID
}
});
}
class WifiReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(ActivitySend.this,"Available Device list changed",Toast.LENGTH_LONG).show();
//TODO: Append SSID of new Available APs in ListView and arrange a callback to onResume().
}
}
public void CheckWifiStatus(){
if (!wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
Toast.makeText(ActivitySend.this, "Wifi turned 'On' Successfully", Toast.LENGTH_SHORT).show();
msg.setText("Wifi Status : ON");
}
}
#Override
protected void onPause() {
unregisterReceiver(wifiReceiver);
super.onPause();
}
}
Using Above java code i can scan available APs if they are available before launching the activity.
After Launching this activity nothing changes in scan result and it keep showing previously fetched results even if i turn off that AP.
In order to detect your AP being disconnected, your intentFilter is lacking the ConnectivityManager.CONNECTIVITY_ACTION.
You can listen
to these action with the following line:
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Also, you need to add brackets to your else code blocks, i.e.
if {
// ...
} else {
Toast.makeText(ActivitySend.this, "No Device Available", Toast.LENGTH_LONG).show();
ScanList = findViewById(R.id.ScanList);
// ...
}

Samsung 10 plus won't allow wifi p2p discovery

I wrote an Android app to allow a device to discover nearby devices via Wi-Fi P2P discovery. I am following this doc.
The app works beautifully on my Samsung Tab E tablet -- I am able to scan and find other devices when the app is running on the tablet. But I am unable to even activate the peer discovery process when running the app on my Samsung Galaxy S10 Plus. My Samsung s10 Plus won't even appear on my tablet's list of available peers unless I manually go into my Galaxy S10 Plus's settings and enable Wi-Fi Discovery Mode. At that point, my Tab E tablet can "see" my Galaxy S10 Plus, but as soon as I exit the settings screen on the Galaxy s10 Plus, Wi-Fi discovery is turned back off and I am no longer able to see it as a potential p2p peer.
Is there a way to allow peer discovery on a Samsung s10 Plus? I am unable to test out my app without it and would rather not have to purchase another Tab E to test p2p connectivity.
Below is the code my app is running for reference:
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, connectionStatus;
EditText writeMsg;
//For programmatically turning wifi on and off:
WifiManager wifiManager;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter = new IntentFilter();
//For keeping track of available clients to connect to
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialWork();
//initializeButtonOnClickListeners();
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
btnDiscover = (Button)findViewById(R.id.discover);
connectionStatus = (TextView) findViewById(R.id.connectionStatus);
// btnSend = (Button)findViewById(R.id.sendButton);
listView = (ListView)findViewById(R.id.peerListView);
// read_msg_box = (TextView) findViewById(R.id.readMsg);
// writeMsg = (EditText)findViewById(R.id.writeMsg);
wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
initializeOnClickListeners();
}
private void initializeOnClickListeners() {
//Set up functionality for when the discover button is clicked.
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "looking for a new peer", Toast.LENGTH_SHORT).show();
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText("Discovery Started");
}
#Override
public void onFailure(int reason) {
connectionStatus.setText("Discovery Failed to start");
}
});
}
});
}
//Define the logic for when a new peer is discovered
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers)) {
//clear the peers
peers.clear();
//store device list
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()];
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()];
int index = 0;
for(WifiP2pDevice device : peerList.getDeviceList()) {
deviceNameArray[index] = device.deviceName;
deviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1,
deviceNameArray);
listView.setAdapter(adapter);
}
if(peers.size() == 0) {
Toast.makeText(getApplicationContext(), "No Devices Found :(", Toast.LENGTH_SHORT).show();
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pManager;
import android.widget.Toast;
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
WifiP2pManager.PeerListListener myPeerListListener;
public WiFiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity) {
this.mManager = mManager;
this.mChannel = mChannel;
this.mActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("The following action was received: " + action);
if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
//if wifi is enabled
if(state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Toast.makeText(context, "Wifi is ON", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Wifi is OFF", Toast.LENGTH_LONG).show();
}
} else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
Toast.makeText(context, "INSIDE THE P2P_PEERS_CHANGED_ACTION", Toast.LENGTH_LONG).show();
if(mManager != null) {
mManager.requestPeers(mChannel, mActivity.peerListListener);
Toast.makeText(context, "A new peer has been found!!!", Toast.LENGTH_LONG).show();
}
} else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
//do something
} else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
//do something
}
}
}
I don't code in Android for sometimes, but I think my experience might still valid, you can give it a try.
Correct me if I'm wrong, so, you have developed an app that allows your devices to discover and connect to each other, without the need to access to the phone's settings. For your S10, you have installed and opened the app, but you cannot discover it via your Tab, unless you manually switch it on in the settings?
First, ensure your app has all the required permission added and requested when using the app.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.nsdchat"
...
<uses-permission
android:required="true"
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:required="true"
android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission
android:required="true"
android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission
android:required="true"
android:name="android.permission.INTERNET"/>
Just to make sure your app has the permission, add the permission to the code below for the respective permission:
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CHANGE_WIFI_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
}
...
Second, look at the code library version. Since s10 + is fairly new, Android has actually enhanced the privacy and security starting from Android 8.0. The code you wrote might be outdated due to the library version, and some APIs might be deprecated.

App will not connect to Firebase Storage- Will not open, No errors

I was going through a tutorial to create a voice recorder which will then upload the recording to Firebase. I watched the tutorial many times and made sure the app is connected to Firebase; however, the app will not open right now most likely due to this issue. I'm pretty new to Java programming. Can someone please provide me with some guidance? Thank you
package bfb.ess.myapplicationbfb;
import android.app.ProgressDialog;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
public class speakp extends AppCompatActivity {
private Button mRecordBtn;
private TextView mRecordlabel;
private MediaRecorder mRecorder;
private String mFileName = null;
private static final String LOG_TAG = "Record_log";
private StorageReference mStorage;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordpage);
mStorage = FirebaseStorage.getInstance().getReference();
mRecordlabel = (TextView) findViewById(R.id.recordlabel);
mRecordBtn =(Button) findViewById(R.id.recordBtn);
mProgress = new ProgressDialog(this);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName +="/recorded_audio.3gp";
mRecordBtn.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
startRecording();
mRecordlabel.setText("Recording Started ...");
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
stopRecording();
mRecordlabel.setText("Recording Stopped ...");
}
return false;
}
});
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
uploadAudio();
}
private void uploadAudio() {
mProgress.setMessage("Uploading Audio ...");
mProgress.show();
StorageReference filepath = mStorage.child("Audio").child("new_audio.3gp");
Uri uri = Uri.fromFile(new File(mFileName));
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
mRecordlabel.setText("Uploading Finished");
}
});
}
}
Go to Firebase console and update read and write rules for storage
You can look into the Google Firebase Sample: Storage Sample
Please check the URI of audio file if its proper. Because I guess lastPathSegment of uri is getting faulty.
By Default:
service firebase.storage {
match /b/<name_of_app>/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Update it to:
service firebase.storage {
match /b/<name_of_app>/o {
match /{allPaths=**} {
allow read;
allow write;
}
}
}
NOTE:
This update will allow you to store the data even if you are not authorised.
It is only for development purpose because it can cause security issue of accessing the data without getting authorised.
So take care when uploading the app to play store, update this parameter and change according to your requirement.
You need to update the read and write rules for storage in your firebase console,
Go to Firebase console, select storage
Click on the Rules tab
By Default:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Change to:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
as Mohom.R said
NOTE: This update will allow you to store the data even if you are not authorised. It is only for development purpose because it can cause security issue of accessing the data without getting authorised. So take care when uploading the app to play store, update this parameter and change according to your requirement.

Bluetooth Sends Sensor Data Only once

So for my research, I have to send accelometer data to an arduino mega as a constant stream. I have the module connected to the arduino via serial. However, when I ran the code, it only runs once. I tried to place the Bluetooth connect part of the code inside my on accuracy change part of my code, but it keeps freezing the device. Here's my code:
package com.example.arduino_bluetooth2;
//=================================================================================================
//Imports
//=================================================================================================
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.TextView;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class MainActivity extends Activity implements SensorEventListener {
// Setup necessary sensor objects
private Sensor acc;
private SensorManager sm;
private TextView t1;
private double value;
// Bluetooth Object
private BluetoothAdapter bAdapter;
private BluetoothDevice device;
private BluetoothSocket mmServerSocket;
private OutputStream btoutput;
private static final UUID SPP_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final int DISCOVERY_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accelerometer_initialization();
bluetooth_initialization();
}
// Setsup the accelerometer object
private void accelerometer_initialization() {
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
acc = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, acc, SensorManager.SENSOR_DELAY_NORMAL);
}
// Setup bluetooth object
private void bluetooth_initialization() {
bAdapter = BluetoothAdapter.getDefaultAdapter();
startActivityForResult(new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),
DISCOVERY_REQUEST);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
bAdapter.startDiscovery();
}
#Override
public void onSensorChanged(SensorEvent event) {
value = event.values[0];
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (new String(device.getName()).equals("BT UART")) {
bAdapter.cancelDiscovery();
try {
BluetoothSocket test = null;
test = device
.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
mmServerSocket = test;
mmServerSocket.connect();
String message = Double.toString(value);
byte[] send = message.getBytes();
btoutput = mmServerSocket.getOutputStream();
btoutput.write(send);
btoutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
};
}
I am not sure you should creating and connecting the bluetooth socket in the broadcast receiver. I do the bluetooth connection management in the onResume() of the activity.
Also I use a thread to manage getting data from the serial data connection between the arduino and the device, it is spawned off and runs continuously in the background. There is a write method to send data out that i call from the activity
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
System.out.println("...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
System.out.println("...Error data send: " + e.getMessage() + "...");
}
}
then the run() method of the tread takes care of getting data back
See my answer in this thread for an example
Error with receiving xml strings via bluetooth in Android
Good luck!
Check out this page from arduino: http://arduino.cc/en/Reference/Loop
The problem is that it only goes once because it is not in a loop that continues forever until the device is shut off or told otherwise.

Categories

Resources