Issuing Intent to call activity along with parameters - android

I'm trying to send parameters string through putExtra function to the activity from the service, I have this code for my Server.java:
package com.winacro.andRHOME;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Server extends Service{
IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public Server getServerInstance() {
return Server.this;
}
}
public void switchSpeaker(int hr, int min){
Toast.makeText(Server.this, hr +" , " +min, Toast.LENGTH_LONG).show();
String sendMessage = "1";
/* Intent myIntent = new Intent(Server.this, andRHOME.class);
myIntent.putExtra("sendMessage","1");
startActivity(myIntent);
PendingIntent pi = PendingIntent.getService(Server.this, 0, myIntent, 0);
AlarmManager almmgr = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar cldr = Calendar.getInstance();
int min1 = cldr.get(Calendar.MINUTE);
cldr.setTimeInMillis(System.currentTimeMillis());
cldr.add(Calendar.SECOND, 30);
almmgr.set(AlarmManager.RTC_WAKEUP, cldr.getTimeInMillis(), pi);*/
}
}
And This is the code for the Activity of whose sendMessage() method I want to access or pass in string variables too but My app is getting crashed, kindly help here!
package com.winacro.andRHOME;
import android.app.Activity;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
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 android.widget.ToggleButton;
/**
* This is the main Activity that displays the current chat session.
*/
public class andRHOME extends Activity {
// Debugging
private static final String TAG = "andRHOME";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
String inp;
// Layout Views
private TextView mTitle;
//private ListView mConversationView;
//private EditText mOutEditText;
//private Button mSendButton;
private ToggleButton TB1;
private ToggleButton TB2;
private ToggleButton TB3;
private ToggleButton TB4;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
public StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
public BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
Bundle bundle = getIntent().getExtras();
inp = bundle.getString("sendMessage");
sendMessage(inp);
}
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mChatService == null) setupChat();
}
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
//mConversationView = (ListView) findViewById(R.id.in);
// mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
//mOutEditText = (EditText) findViewById(R.id.edit_text_out);
// mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
//mSendButton = (Button) findViewById(R.id.button_send);
/*mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
//TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = "0";
sendMessage(message);
}
});*/
TB1 = (ToggleButton) findViewById(R.id.toggleButton1);
TB1.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB1.isChecked()){
String message = "1";
sendMessage(message);
} else if (!TB1.isChecked()){
String message = "6";
sendMessage(message);
}
}
});
TB2 = (ToggleButton) findViewById(R.id.ToggleButton01);
TB2.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB2.isChecked()){
String message = "0";
sendMessage(message);
} else if (!TB2.isChecked()){
String message = "5";
sendMessage(message);
}
}
});
TB3 = (ToggleButton) findViewById(R.id.ToggleButton02);
TB3.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB3.isChecked()){
String message = "2";
sendMessage(message);
} else if (!TB3.isChecked()){
String message = "7";
sendMessage(message);
}
}
});
TB4 = (ToggleButton) findViewById(R.id.ToggleButton03);
TB4.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB4.isChecked()){
String message = "3";
sendMessage(message);
} else if (!TB4.isChecked()){
String message = "8";
sendMessage(message);
}
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
//mOutEditText.setText(mOutStringBuffer);
}
}
// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.timer:
// Launch the DeviceListActivity to see devices and do scan
Intent myIntent = new Intent("com.winacro.andRHOME.Timer");
startActivity(myIntent);
return true;
/*case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;*/
}
return false;
}
}

Related

wifi p2p file transfer android connected device but not transfering

Hello iam stuck in problem since yesterday searched everything anywhere i create application which show device which arre connected to same router wifi , then iam able to connect both device using this exmple
https://developer.android.com/guide/topics/connectivity/wifip2p.html#creating-app
everything is okay both devices are connected but when transfer file serviceintent is not starting so thats why i cant transfer anything , there is not log error but happend nothing when i choose image to send
MainActivity Class
package com.b.wifip2p;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {
Button button;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
WifiP2pManager.Channel mChannel = null;
WifiP2pManager mManager;
private WifiP2pInfo info;
BroadCast broadCast;
private BroadcastReceiver receiver = null;
static List peers = new ArrayList();
ListView lv;
static Adapater myadapter;
ArrayList<DeviceInfo_Bean>list=new ArrayList<>();
private WifiP2pDevice device;
String hostaddd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=findViewById(R.id.lv);
myadapter=new Adapater(this,list);
button=findViewById(R.id.button);
lv.setAdapter(myadapter);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
connect();
}
});
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
System.out.println("---sucess discover");
}
#Override
public void onFailure(int reasonCode) {
System.out.println("---fail");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 007);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
System.out.println("---ip"+ipAddress);
}
});
}
#Override
public void onResume() {
super.onResume();
broadCast = new BroadCast(mManager, mChannel, MainActivity.this);
registerReceiver(broadCast, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadCast);
}
private static WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void
onPeersAvailable(WifiP2pDeviceList peerList) {
List<WifiP2pDevice> refreshedPeers = (List<WifiP2pDevice>) peerList.getDeviceList();
if (!refreshedPeers.equals(peers)) {
peers.clear();
peers.addAll(refreshedPeers);
System.out.println("---ref"+refreshedPeers);
}
if (peers.size() == 0) {
Log.d("-----deviceno", "No devices found");
return;
}
}
};
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
for (WifiP2pDevice device : peers.getDeviceList())
{
list.clear();
String address=device.deviceAddress;
String name=device.deviceName;
System.out.println("---name"+name+address);
list.add(new DeviceInfo_Bean(name,address));
}
myadapter.notifyDataSetChanged();
Log.i("----", "Found some peers!!! " + peers.getDeviceList());
}
public void connect() {
DeviceInfo_Bean device = list.get(0);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.address;
config.wps.setup = WpsInfo.PBC;
System.out.println("device in"+device.address);
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using
// FileTransferService.
Uri uri = data.getData();
// TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
// statusText.setText("Sending: " + uri);
// Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
Intent serviceIntent = new Intent(MainActivity.this, FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
startService(serviceIntent);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
//private TextView statusText;
/**
* #param context
*
*/
public FileServerAsyncTask(Context context) {
this.context = context;
//this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
System.out.println("---socket");
Socket client = serverSocket.accept();
///Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
//Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
OutputStream stream = client.getOutputStream();
String s="---mymsg";
stream.write(s.getBytes());
Log.e("hello","context value "+context);
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
// Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
// statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// statusText.setText("Opening a server socket");
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime=System.currentTimeMillis();
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime=System.currentTimeMillis()-startTime;
Log.v("","Time taken to transfer all bytes is : "+endTime);
} catch (IOException e) {
// Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
System.out.println("---info");
this.info=info;
// view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
InetAddress groupOwnerAddress = info.groupOwnerAddress;
System.out.println("--g"+groupOwnerAddress);
System.out.println("--info"+info.groupOwnerAddress.getHostAddress());
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getApplication())
.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the
// get file button.
}
// hide the connect button
// mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}
public void showDetails(WifiP2pDevice device) {
this.device = device;
// this.getView().setVisibility(View.VISIBLE);
// TextView view = (TextView) mContentView.findViewById(R.id.device_address);
// view.setText(device.deviceAddress);
//view = (TextView) mContentView.findViewById(R.id.device_info);
//view.setText(device.toString());
System.out.println("---device"+device.deviceAddress);
}
}'
Broadcast
package com.b.wifip2p;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import java.nio.channels.Channel;
/**
* Created by BHM on 3/3/2018.
*/
public class BroadCast extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity activity;
PeerListListener peerListListener=null;
public BroadCast(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.activity = (MainActivity) activity;
}
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("-----broadcast");
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// UI update to indicate wifi p2p status.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi Direct mode is enabled
// activity.setIsWifiP2pEnabled(true);
} else {
//activity.setIsWifiP2pEnabled(false);
// activity.resetData();
}
// Log.d(WiFiDirectActivity.TAG, "P2P state changed - " + state);
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (mManager != null) {
// mManager.requestPeers(mChannel, (PeerListListener) mChannel);
}
// Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
if (mManager == null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// we are connected with the other device, request connection
// info to find group owner IP
mManager.requestConnectionInfo(mChannel, activity);
} else {
// It's a disconnect
// activity.resetData();
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
// .findFragmentById(R.id.frag_list);
// fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
// WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
}
}
}
FileTransferService here intent is not coming
package com.b.wifip2p;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* Created by BHM on 3/4/2018.
*/
class FileTransferService extends IntentService {
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public FileTransferService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("--intent");
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
// Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
// Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
// Log.d(WiFiDirectActivity.TAG, e.toString());
}
MainActivity.copyFile(is, stream);
// Log.d(WiFiDirectActivity.TAG, "Client: Data written");
} catch (IOException e) {
// Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
}
I know this is a slightly old question by now, but for those looking for answers:
I would recommend checking that you have the intent filters properly in your AndroidManifest.xml file.
It should look something like:
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.ACTION_SEND_FILE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>

Android Studio: Textview in Bluetooth Chat sample

I am using Bluetooth Chat sample to receive Sensor Data from my Arduino on my Android Device. I'm trying to display the incoming message to a TextView. Here's my code for the Bluetooth Chat Fragment class
package com.example.android.bluetoothchat;
import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
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 com.example.android.common.logger.Log;
/**
* This fragment controls Bluetooth to communicate with other devices.
*/
public class BluetoothChatFragment extends Fragment {
private static final String TAG = "BluetoothChatFragment";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private TextView display;
/**
* Name of the connected device
*/
private String mConnectedDeviceName = null;
/**
* Array adapter for the conversation thread
*/
private ArrayAdapter<String> mConversationArrayAdapter;
/**
* String buffer for outgoing messages
*/
private StringBuffer mOutStringBuffer;
/**
* Local Bluetooth adapter
*/
private BluetoothAdapter mBluetoothAdapter = null;
/**
* Member object for the chat services
*/
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (mChatService == null) {
setupChat();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null) {
mChatService.stop();
}
}
#Override
public void onResume() {
super.onResume();
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
mConversationView = (ListView) view.findViewById(R.id.in);
mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
mSendButton = (Button) view.findViewById(R.id.button_send);
display = (TextView) view.findViewById(R.id.kotak);
}
/**
* Set up the UI and background operations for chat.
*/
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
View view = getView();
if (null != view) {
TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
String message = textView.getText().toString();
sendMessage(message);
}
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(getActivity(), mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
/**
* Makes this device discoverable for 300 seconds (5 minutes).
*/
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
*
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
/**
* The action listener for the EditText widget, to listen for the return key
*/
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
return true;
}
};
/**
* Updates the status on the action bar.
*
* #param resId a string resource ID
*/
private void setStatus(int resId) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(resId);
}
/**
* Updates the status on the action bar.
*
* #param subTitle status
*/
private void setStatus(CharSequence subTitle) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(subTitle);
}
/**
* The Handler that gets information back from the BluetoothChatService
*/
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case Constants.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
display.setText(readMessage);
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
/**
* Establish connection with other device
*
* #param data An {#link Intent} with {#link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
* #param secure Socket Security type - Secure (true) , Insecure (false)
*/
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.bluetooth_chat, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}
case R.id.discoverable: {
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
}
return false;
}}
Problem is when I launched the application in my android, the app crashed after receiving bluetooth data. The report bug I get from the application is
java.lang.NullPointerException:
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at
com.example.android.bluetoothchat.BluetoothChatFragment$3.handleMessage(BluetoothChatFragment.java:315)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5442)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygotelnit$MethodAndArgsCaller.run(Zygotelnit.java:738)
at com.android.internal.os.Zygotelnit.main(Zygotelnit.java:628)
Can anybody help me for this problem? Thanks a lot
Remove this from your TextView textView = (TextView) view.findViewById(R.id.edit_text_out); from your mSendButton.setOnClickListener and intilize it it into your onViewCreated like below code
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
mConversationView = (ListView) view.findViewById(R.id.in);
mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
mSendButton = (Button) view.findViewById(R.id.button_send);
display = (TextView) view.findViewById(R.id.kotak);
TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
}

Location services across multiple activities

UPDATE - edited code to display my broadcast idea. Using the method causes a !!! FAILED BINDER TRANSACTION !!! and no location data to be displayed by toast.
I was wondering if there was an elegant way to separate google fused location services away from activities. My warning class currently implements location services but I have another activity that takes photos. When a photo is taken I want to associate a location with the image. My current idea is to just use my broadcast receiver in my Bluetooth warning class to listen for a broadcast my camera will send and associate it then with a location. I'm not a fan of the idea because it doesn't separate functionality very well so was hoping for some suggestions or patterns. Code for classes below.
CAMERA CLASS
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraOperations extends AppCompatActivity {
public final static String ACTION_PICTURE_RECEIVED = "ACTION_PICTURE_RECEIVED";
public final static String TRANSFER_DATA = "bitmap";
ImageView mImageView;
String photoPath;
int REQUEST_IMAGE_CAPTURE = 1;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_view);
mImageView = (ImageView) findViewById(R.id.imageView);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(CameraOperations.this, "No Camera", Toast.LENGTH_SHORT).show();
} else {
dispatchTakePictureIntent();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
if(data == null){
Toast.makeText(this, "Data is null", Toast.LENGTH_SHORT);
Bitmap pictureMap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
mImageView.setImageBitmap(pictureMap);
broadcastUpdate(ACTION_PICTURE_RECEIVED, pictureMap);
}else {
Toast.makeText(this, "Error Occurred", Toast.LENGTH_SHORT).show();
}
}
}
private void broadcastUpdate(final String action, Bitmap picture) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
picture.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
Intent intent = new Intent(action);
intent.putExtra(TRANSFER_DATA, bytes);
sendBroadcast(intent);
intent = new Intent(CameraOperations.this, Warning.class);
startActivity(intent);
finish();
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
photoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try{
photoFile = createImageFile();
}catch(IOException e){
e.printStackTrace();
}
if(photoFile != null){
Uri photoUri = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
BLUETOOTH WARNING CLASS
import android.Manifest;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class Warning extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final static String TAG = Warning.class.getSimpleName();
private String mDeviceAddress;
private HandleConnectionService mBluetoothLeService;
private boolean quitService;
private final int PLAY_SERVICES_REQUEST_TIME = 1000;
private Location mLastLocation;
private GoogleApiClient mGoogleClient;
private boolean requestingLocationUpdates = false;
private LocationRequest locationRequest;
private int UPDATE_INTERVAL = 10000; // 10 seconds
private int FASTEST_INTERVAL = 5000; // 5 seconds
private int DISTANCEMOVED = 10; //In meters
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((HandleConnectionService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
mBluetoothLeService.connect(mDeviceAddress);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (HandleConnectionService.ACTION_GATT_DISCONNECTED.equals(action)) {
if (!quitService) {
mBluetoothLeService.connect(mDeviceAddress);
Log.w(TAG, "Attempting to reconnect");
}
Log.w(TAG, "Disconnected, activity closing");
} else if (HandleConnectionService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
getGattService(mBluetoothLeService.getSupportedGattService());
} else if (HandleConnectionService.ACTION_DATA_AVAILABLE.equals(action)) {
checkWarning(intent.getByteArrayExtra(HandleConnectionService.EXTRA_DATA));
}else if(CameraOperations.ACTION_PICTURE_RECEIVED.equals(action)){
byte[] bytes = intent.getByteArrayExtra("bitmap");
Bitmap picture = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
findLocation();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
if (checkGoogleServices()) {
buildGoogleApiClient();
}
quitService = false;
Intent intent = getIntent();
mDeviceAddress = intent.getStringExtra(Device.EXTRA_DEVICE_ADDRESS);
Intent gattServiceIntent = new Intent(this, HandleConnectionService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
MenuItem connect = menu.findItem(R.id.connect);
connect.setVisible(false);
MenuItem disconnect = menu.findItem(R.id.disconnect);
disconnect.setVisible(true);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.home:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Return Home")
.setMessage("Returning home will disconnect you, continue?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
quitService = true;
mBluetoothLeService.disconnect();
mBluetoothLeService.close();
Intent intent = new Intent(Warning.this, Main.class);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
return true;
case R.id.connect:
Toast.makeText(this, "Connect Pressed", Toast.LENGTH_SHORT).show();
return true;
case R.id.disconnect:
disconnectOperation();
intent = new Intent(Warning.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.profiles:
Toast.makeText(this, "Profiles Pressed", Toast.LENGTH_SHORT).show();
return true;
case R.id.camera:
Toast.makeText(this, "Camera Pressed", Toast.LENGTH_SHORT).show();
intent = new Intent(Warning.this, CameraOperations.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
quitService = true;
mBluetoothLeService.disconnect();
mBluetoothLeService.close();
Intent intent = new Intent(Warning.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onDestroy() {
super.onDestroy();
mBluetoothLeService.disconnect();
mBluetoothLeService.close();
System.exit(0);
}
public boolean disconnectOperation(){
this.quitService = true;
mBluetoothLeService.disconnect();
mBluetoothLeService.close();
return true;
}
private void checkWarning(byte[] byteArray) {
if (byteArray != null) {
for (int i = 0; i < byteArray.length; i++) {
if (byteArray[i] == 48) {
findLocation();
}
}
}
}
private void getGattService(BluetoothGattService gattService) {
if (gattService == null) {
return;
}
BluetoothGattCharacteristic characteristicRx = gattService.getCharacteristic(HandleConnectionService.UUID_BLE_SHIELD_RX);
mBluetoothLeService.setCharacteristicNotification(characteristicRx, true);
mBluetoothLeService.readCharacteristic(characteristicRx);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(HandleConnectionService.ACTION_GATT_CONNECTED);
intentFilter.addAction(HandleConnectionService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(HandleConnectionService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(HandleConnectionService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(CameraOperations.ACTION_PICTURE_RECEIVED);
return intentFilter;
}
private boolean checkGoogleServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int available = googleAPI.isGooglePlayServicesAvailable(this);
if (available != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(available)) {
googleAPI.getErrorDialog(this, available, PLAY_SERVICES_REQUEST_TIME).show();
}
return false;
}
return true;
}
public void findLocation() {
int REQUEST_CODE_ASK_PERMISSIONS = 123;
double latitude = 0.0;
double longitude = 0.0;
if(Build.VERSION.SDK_INT >= 23){
boolean fineLocationAccess = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean courseLocationAccess = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean accessGranted = fineLocationAccess && courseLocationAccess;
if (accessGranted) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
if(mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Toast.makeText(this, "latitude: " + latitude + " longitude: " + longitude, Toast.LENGTH_LONG).show();
}else{
Log.i("Warning", "Unable to get Location");
}
}else{
Log.i("Connection", "Request permission");
}
}else{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
if(mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Toast.makeText(this, "latitude: " + latitude + " longitude: " + longitude, Toast.LENGTH_LONG).show();
}else{
Log.i("Warning", "Unable to get Location");
}
}
}
public void buildGoogleApiClient() {
mGoogleClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
#Override
public void onConnected(Bundle bundle) {
Log.w("Connected", " : " + mGoogleClient.isConnected());
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this, "Location Services Stopped", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "Location Services Connection Fail", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleClient != null) {
mGoogleClient.connect();
}
}
}
I think your original idea is actually pretty sound as long as you construct it a certain way. The activity that is knowledgeable about the location information can update and store that location independent of any other activity. This would probably be ideal to have as a service actually that runs every x amount of time, or when the location changes.
Inside of that same class you can have a generic broadcast receiver that handles request for that location information. You can make this as generic as you want in terms of allowing other applications/activities you make also being to leverage it, as long as the location data is returned in a way that is usable to each requester.
From within your activity that takes photos (and eventually any activity you desire), when you take a photo, you can send a broadcast requesting that location information, with some default or null info if none is returned. One of the complexities is knowing how long to wait for this location info before completing. In this scenario the location activity is the 'generalized' one in that multiple activities can request location data if you construct it correctly.
Another potentially robust approach is to make the photo taking activity the generalized one. One way to do this is that when you take a photo, you can have your photo activity send broadcast to the location activity that contains the photos filepath/uri/identifying information, but you don't wait for a response. Instead, you make the location activity listen for this broadcast, and write to the photos meta data with the location using the provided identifying info to find said photo. In this way your photo taking app isn't stuck waiting for the location activity to finish (or event start if it ever does).
Good luck, sounds like a fun project.

Android connect to bluetooth device with click button on bluetooth device

I have device bluetooth with button, I want connect to this device after click button on this device, it's there any example to do this?
May this help you.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Set;
import java.util.UUID;
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.Toast;
public class MainActivity 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, mPrint;
static OutputStream outStream;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
static BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
setContentView(R.layout.activity_main);
mScan = (Button) findViewById(R.id.Scan);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(MainActivity.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(MainActivity.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
if (mBluetoothSocket != null) {
//code for send data on printer to print
sendDataToDevice("Hello");
}
// printer specific code you can comment ==== > End
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
/* mDisc = (Button) findViewById(R.id.dis); */
/*
* mDisc.setOnClickListener(new View.OnClickListener() { public void
* onClick(View mView) { if (mBluetoothAdapter != null)
* mBluetoothAdapter.disable(); } });
*/
}// onCreate
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();
// 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(MainActivity.this,
DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(MainActivity.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());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void sendDataToDevice(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg
+ ".\n\nTry Connecting the device one more time from the options menu.\n\n";
errorExit("Fatal Error", msg);
}
}
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(MainActivity.this, "DeviceConnected", 5000).show();
}
};
}
and DeviceListActivty.java is like this
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.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
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 = "None Paired";// 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();
}
};
}

android service to start activity not reacting like I think it should

I've been working on a program that listens for bluetooth messages to start various apps on my phone. Each of the following work correctly if the main layout is displayed but once one of the commands is called the other does not react properly. Here is the code for the two commands:
if (readMessage.equals("Button"))
{
Intent i = new Intent(Intent.ACTION_MAIN);
PackageManager manager = getPackageManager();
i = manager.getLaunchIntentForPackage("com.google.android.apps.maps");
Log.d("Main","i is: "+ i);
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
Log.d("Main","Map pushed");
}
if (readMessage.equals("Home"))
{
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
Log.d("Main","Home pushed");
}
So for example the message home is sent, the app will display the home screen. However if after the home screen is displayed and the message "Button" is sent nothing happens, but I know that the code is called from the Log.
Do I need to put my message handler into it's own service?
Here are the two java files:
Main:
package com.lorenjz.phoneremotefive;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.Set;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
public class MainRemote extends Activity {
private static TextView btstatus=null;
private Button closeButt;
private TextView ringtone=null;
private TextView checkbox2=null;
private Boolean serverState = false;
//declerations:
private BluetoothAdapter btAdapter;
public ArrayList myArray;
public ArrayList devArray;
private int myContext;
private BlueStuff mChatService = null;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_NAME = "device_name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_remote);
btstatus=(TextView)findViewById(R.id.btstatus);
closeButt=(Button)findViewById(R.id.close);
/**checkbox=(TextView)findViewById(R.id.checkbox);
checkbox2=(TextView)findViewById(R.id.checkbox2);**/
SharedPreferences prefs=PreferenceManager
.getDefaultSharedPreferences(this);
//checkbox.setText(new Boolean(prefs.getBoolean("checkbox", false))
// .toString());
Boolean servState = (new Boolean(prefs.getBoolean("serverstate", false)).booleanValue());
if (servState = true){
Log.d("Main","It thinks the server should be on");
//checkbox2.setText(new Boolean(prefs.getBoolean("checkbox2", false))
// .toString());
mChatService = new BlueStuff(getBaseContext(), mHandler);
int stateString = mChatService.getState();
Log.d("Main","chat service: " + stateString);
//+ mChatService.getState()
mChatService.start();
}
int stateString = mChatService.getState();
Log.d("Main","After stuff happens. chat service: " + stateString);
btstatus.setText("No Connection yet");
setupUI();
closeButt.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mChatService.stop();
}
});
}
#Override
public void onResume() {
super.onResume();
SharedPreferences prefs=PreferenceManager
.getDefaultSharedPreferences(this);
//checkbox.setText(new Boolean(prefs.getBoolean("checkbox", false))
// .toString());
String servState = (new Boolean(prefs.getBoolean("serverstate", false)).toString());
Log.d("Main","Server State: " +servState);
//checkbox2.setText(new Boolean(prefs.getBoolean("checkbox2", false))
// .toString());
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BlueStuff.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
startService(new Intent(this, BlueStuff.class));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_remote, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent(this, PreferencesB.class));
return true;
}
return(super.onOptionsItemSelected(item));
}
public void setupUI(){
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
//if(D) Log.i("Main", "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BlueStuff.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
//setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
//mConversationArrayAdapter.clear();
break;
case BlueStuff.STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
//setStatus(R.string.title_connecting);
break;
case BlueStuff.STATE_LISTEN:
Toast.makeText(getApplicationContext(), "Listening", Toast.LENGTH_SHORT).show();
break;
case BlueStuff.STATE_NONE:
//setStatus(R.string.title_not_connected);
break;
}
break;
/**case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;**/
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
//mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
//Toast.makeText(getApplicationContext(), "Message: " + readMessage, Toast.LENGTH_SHORT).show();
if (readMessage.equals("Button"))
{
/**Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);**/
Intent i = new Intent(Intent.ACTION_MAIN);
PackageManager manager = getPackageManager();
i = manager.getLaunchIntentForPackage("com.google.android.apps.maps");
Log.d("Main","i is: "+ i);
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
Log.d("Main","Map pushed");
/**Intent launch_intent = new Intent("android.intent.action.MAIN");
launch_intent.addCategory("android.intent.category.LAUNCHER");
launch_intent.setComponent(new ComponentName("com.google.android.maps", "map"));
launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launch_intent);**/
}
if (readMessage.equals("Home"))
{
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
Log.d("Main","Home pushed");
}
break;
/**case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;**/
}
}
};
final static void updateBTStatus(int mState){
Log.d("Main", "update called. mState is: " + mState);
btstatus.setText("prior to switch");
statusTry();
switch(mState){
case 1:
btstatus.setText("Listening for connection");
Log.d("Main","Status should be listening for connection");
case 2:
btstatus.setText("Connecting");
case 3:
btstatus.setText("Connected");
}
}
public static void statusTry(){
btstatus.setText("post switch try");
}
}
Blue Stuff:
package com.lorenjz.phoneremotefive;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class BlueStuff extends Service{
private static final String TAG = "Blue";
private static final boolean D = true;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final String NAME = "Zimmer";
//private BluetoothAdapter mBluetoothAdapter;
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private int mState;
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private AcceptThread mSecureAcceptThread;
private AcceptThread mInsecureAcceptThread;
/**
* Constructor. Prepares a new BluetoothChat session.
* #param context The UI Activity Context
* #param handler A Handler to send messages back to the UI Activity
*/
public BlueStuff(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
}
/**
* Return the current connection state. */
public synchronized int getState() {
return mState;
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
if (D) Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
setState(STATE_LISTEN);
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
public void stop(){
mConnectedThread.cancel();
}
/**
* Set the current state of the chat connection
* #param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(MainRemote.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
//tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
Log.d("Blue","Listen Failed tmp 1c: " + tmp);
mmServerSocket = tmp;
Log.d("Blue","mmServerSocket 1: " + mmServerSocket);
MainRemote.updateBTStatus(mState);
}
public void run() {
Log.d("Blue","Run Called");
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
Log.d("Blue","mmServerSocket 2: " + mmServerSocket);
socket = mmServerSocket.accept();
}
catch (IOException e) {
break;
}
// If a connection was accepted
/** if (socket != null) {
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(socket);
//mmServerSocket.close();
Log.d("Blue","Connection was accepted");
MainRemote.updateBTStatus(mState);
break;
}**/
if (socket != null) {
synchronized (BlueStuff.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
class ConnectThread extends Thread {
final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MainRemote.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
Log.d("Blue","message recieved!: " + bytes);
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* #param socket The BluetoothSocket on which the connection was made
* #param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
device) {
//if (D) Log.d(TAG, "connected, Socket Type:" + socketType);
// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Cancel the accept thread because we only want to connect to one device
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(MainRemote.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(MainRemote.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Its not that nothing is happening. Its that the Activity is not recreated. Try overriding onStart() I bet this is getting called instead.

Categories

Resources