Connect via Bluetooth - java

I have been working on a bluetooth app for android.I can select a Bt-device from vaible-device-list. How can i connect with the selected device? Could you please help me?
Thank you very much
Here is my code:
public class ScanActivity extends ListActivity {
private static final int REQUEST_BT_ENABLE = 0x1;
public static String EXTRA_DEVICE_ADDRESS = "device_address";
ListView listGeraete;
BluetoothAdapter bluetoothAdapter;
ArrayAdapter<String> arrayAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
// adapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// list of devices
ListView listGeraete = getListView();
arrayAdapter = new ArrayAdapter<String>(ScanActivity.this,android.R.layout.simple_list_item_1);
listGeraete.setAdapter(arrayAdapter);
// if bt disable, enabling
if (!bluetoothAdapter.isEnabled()) {
Intent enableBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBt, REQUEST_BT_ENABLE);
}
// start discovery
bluetoothAdapter.startDiscovery();
registerReceiver( ScanReceiver , new IntentFilter(
BluetoothDevice.ACTION_FOUND));
}
private final BroadcastReceiver ScanReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// find bt devices
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
arrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayAdapter.notifyDataSetChanged();
}
}
};
// select a device
public void onListItemClick(ListView l, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String devicesinfo = ((TextView) view).getText().toString();
String address = devicesinfo.substring(devicesinfo.length());
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
setResult(Activity.RESULT_OK, intent);
Toast.makeText(getApplicationContext(),"Connecting to " + devicesinfo +
address,
Toast.LENGTH_SHORT).show();
}
}

You can connect by using the following code (Assuming you are using RFComm to connect, otherwise change accordingly)
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
BluetoothSocket socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();

Related

Send bluetooth message via Android Studio

I'm trying to send a message via bluetooth in Android Studio. I've googled but I cannot find the answer. I want to send a message to a connected device.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ImageView bluetoothOnImageView;
private ImageView bluetoothOffImageView;
private TextView bluetoothOnOffTextView;
private BluetoothAdapter bluetoothAdapter;
private ListView listView;
private EditText messageEditText;
private ArrayList<String> deviceList = new ArrayList<String>();
private ArrayList<BluetoothDevice> deviceListBluetooth = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothOnImageView = findViewById(R.id.bluetoothOnImageView);
bluetoothOffImageView = findViewById(R.id.bluetoothOffImageView);
bluetoothOnOffTextView = findViewById(R.id.bluetoothOnOffTextView);
listView = findViewById(R.id.listView);
messageEditText = findViewById(R.id.messageEditText);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
checkBluetooth();
Toast.makeText(this, "Scanning devices...", Toast.LENGTH_SHORT).show();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
IntentFilter filterChange = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(receiverChange, filter);
listView.setOnItemClickListener(MainActivity.this);
}
private final BroadcastReceiver receiverChange = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 3 Cases
// 1: Bonded already
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.d("BroadcastReceiver", "BOND_BONDED");
Toast.makeText(MainActivity.this, "Already connected to this device.", Toast.LENGTH_SHORT).show();
}
// 2: Creating a bond
if (device.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d("BroadcastReceiver", "BOND_BONDING");
}
// 3: Breaking a bond
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d("BroadcastReceiver", "BOND_NONE");
Toast.makeText(MainActivity.this, "Broke connection to this device.", Toast.LENGTH_SHORT).show();
}
}
}
};
public void bluetoothSearchOnClick(View view) {
Toast.makeText(this, "Rescanning devices...", Toast.LENGTH_SHORT).show();
// Reset devices
deviceList.clear();
deviceListBluetooth.clear();
bluetoothAdapter.startDiscovery();
checkBluetooth();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
}
#Override
protected void onDestroy() {
unregisterReceiver(receiver);
unregisterReceiver(receiverChange);
super.onDestroy();
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String newDevice = device.getName() + "\n" + device.getAddress();
boolean duplicate = false;
// No duplicate devices
for (int i = 0; i < deviceList.size(); i++) {
if (newDevice.equals(deviceList.get(i))) {
duplicate = true;
}
}
if (!duplicate) {
deviceList.add(newDevice);
deviceListBluetooth.add(device);
}
Log.i("BT", device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, deviceList));
}
}
};
public void bluetoothOnOnClick(View view) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.disable();
// Wait x milliseconds
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
checkBluetooth();
}
}, 500);
}
public void bluetoothOffOnClick(View view) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.enable();
// Wait x milliseconds
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
checkBluetooth();
}
}, 500);
}
private void checkBluetooth() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(this, "This device does not support Bluetooth", Toast.LENGTH_SHORT).show();
} else if (!bluetoothAdapter.isEnabled()) {
// Bluetooth is not enabled :)
bluetoothOnImageView.setVisibility(View.GONE);
bluetoothOffImageView.setVisibility(View.VISIBLE);
bluetoothOnOffTextView.setText("OFF");
bluetoothOnOffTextView.setTextColor(Color.RED);
} else {
// Bluetooth is enabled
bluetoothOffImageView.setVisibility(View.GONE);
bluetoothOnImageView.setVisibility(View.VISIBLE);
bluetoothOnOffTextView.setText("ON");
bluetoothOnOffTextView.setTextColor(Color.GREEN);
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
checkBluetooth();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
Log.d("Bluetooth Adapter", "onItemClick: You Clicked on a device.");
String[] device = deviceList.get(position).split("\n");
String deviceName = device[0];
// Bond
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
Log.d("Bluetooth Adapter", "Trying to pair with " + deviceName);
deviceListBluetooth.get(position).createBond();
}
}
public void sendButtonOnClick(View view) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Send message
}
}
In the method sendButtonOnClick(View view) is where I want to send the message. You can find this method at the bottom of the code.
Can anyone help me?
this is not so simple as you think (packing up messaging feature into one method). you need to connect to BluetoothSocket obtained from BluetoothDevice using createRfcommSocketToServiceRecord and knowing "messaging" UUID (you can list them with getUuids() method). after proper socket connection you can obtain input and output streams (getInputStream and getOutputStream), from which you can read and write bytes converting to text if you want. found pretty good sample in HERE, which is using separated Threads for Bluetooth communication making whole feature async and not hanging main/UI thread

Pairing new device in Lock Task Mode (Android P/10)

I have an issue when I use the Lock Task Mode (Kiosk mode) on Android.
In "normal" mode, when I try to pair a device, a pop-up message appears :
"Are you sure you want to pair the Bluetooth Device?" Yes/No
But in Lock Task Mode, the message doesn't appear.
I added in my code to authorize notifications but pop-up are not displayed :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
int test = dmp.getLockTaskFeatures(adminComponentName);
dmp.setLockTaskFeatures(adminComponentName, DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO |
DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS |
DevicePolicyManager.LOCK_TASK_FEATURE_HOME);
}
Is there a way in Lock Task Mode to authorize such pop-ups?
Thanks
public class Bluetooth extends AppCompatActivity {
ArrayList<String> listItems=new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
BroadcastReceiver mReceiver;
DevicePolicyManager dpm;
ComponentName deviceAdmin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
dpm = (DevicePolicyManager) Bluetooth.this.getSystemService(Context.DEVICE_POLICY_SERVICE);
deviceAdmin = new ComponentName(Bluetooth.this, MyDeviceAdminReceiver.class);
dpm.setLockTaskPackages(deviceAdmin, new String[]{
Bluetooth.this.getPackageName()
"com.android.settings"
});
ListView lista=findViewById(R.id.devices);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
lista.setAdapter(adapter);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//setdevicevisible();
boolean hasBluetooth = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
if(!hasBluetooth) {
AlertDialog dialog = new AlertDialog.Builder(Bluetooth.this).create();
dialog.setTitle("Bluetooth nem elérhető");
dialog.setMessage("Bluetooth ki van kapcsolva!");
dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Closes the dialog and terminates the activity.
dialog.dismiss();
Bluetooth.this.finish();
}
});
dialog.setCancelable(false);
dialog.show();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
//device.setPairingConfirmation(true);
if (device.getName() != null) {
adapter.add(device.getName() + "\n" + device.getAddress());
device.createBond();
}
//adapter.add(device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
try{
unregisterReceiver(mReceiver);
dpm.setLockTaskPackages(deviceAdmin, new String[]{
Bluetooth.this.getPackageName()
});
}catch (Exception e){
// already unregistered
}
}
}

How to send command linux from one device to another conneted via usb otg?

I made application which should send linux command to another device, when are together connected via ust otg.
How can i send my command to another device?
I made communication, and i can read for example model device, now i would like send command to see ip address connected device
Ok, sorry my fault
Here I is my MainActivity
private static final String TAG = "UsbEnumerator";
private TextView mStatusView, mResultView, showCommand;
private Button buttonRefresh, sendCommand;
private UsbManager usbManager;
private EditText writeCommand;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mStatusView = (TextView) findViewById(R.id.mStatusView);
mResultView = (TextView) findViewById(R.id.mResultView);
showCommand = (TextView) findViewById(R.id.showCommand);
buttonRefresh = (Button) findViewById(R.id.buttonRefresh);
sendCommand = (Button) findViewById(R.id.sendCommand);
writeCommand = (EditText) findViewById(R.id.writeCommand);
mResultView.setMovementMethod(new ScrollingMovementMethod());
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
finish();
overridePendingTransition(0,0);
startActivity(i);
overridePendingTransition(0,0);
}
});
sendCommand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View t) {
SendCommandExecutor exe = new SendCommandExecutor();
String command = writeCommand.getText().toString();
String outp = exe.Executer(command);
showCommand.setText(outp);
Log.d("Output", outp);
}
});
usbManager = getSystemService(UsbManager.class);
IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbReceiver, filter);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mUsbReceiver);
}
BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
printStatus("Delete");
printDeviceDescription(device);
}
}
}
};
private void handleIntent(Intent intent) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
printStatus("Adding");
printDeviceDetails(device);
} else {
printStatus("Remove");
printDeviceList();
}
}
I would like send linux command (for example check ip address) when i have connected device via ust otg. Should i execute command in here?
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
printStatus("Delete");
printDeviceDescription(device);
}
}
}
};

scaning bluetooth (java) on android studio

I am developing the attendance system using Bluetooth that allow the user to scan Bluetooth to get the Bluetooth address and compare it with registered Bluetooth address. The problem is, it only scan and display the registered list of student but not listing the available Bluetooth and also not compare with the register Bluetooth address.
here is the code for BluetoothScanActivity
public class BluetoothScanActivity extends AppCompatActivity {
public static final String TAG = BluetoothScanActivity.class.getSimpleName();
BluetoothAdapter mBluetoothAdapter;
IntentFilter filter;
BroadcastReceiver mReceiver;
String name[];
ArrayList<String> macID;
Bundle scan_data;
int countScans=0;
int numCountScans;
int value;
RippleBackground rippleBackground;
String classID;
boolean selectDateCheck = false;
Date selectedDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_scan);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(ContextCompat.getColor(getBaseContext(), R.color.main_blue));
}
classID = getIntent().getStringExtra("Class ID");
numCountScans = getIntent().getIntExtra("Number Scans",3);
value = getIntent().getIntExtra("Value",1);
selectDateCheck = getIntent().getBooleanExtra("Manual Date",false);
selectedDate = (Date)getIntent().getSerializableExtra("Selected Date");
Toast.makeText(this, numCountScans + " " + value, Toast.LENGTH_LONG).show();
rippleBackground = (RippleBackground)findViewById(R.id.content);
int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
init();
if(mBluetoothAdapter==null)
{
Toast.makeText(getApplicationContext(),"Your device doesn't support bluetooth!",Toast.LENGTH_SHORT).show();
finish();
}
else
{
if (!mBluetoothAdapter.isEnabled()) {
turnOnBT();
}
}
scan_data=new Bundle();
name=new String[100];
macID = new ArrayList<String>();
Log.d(TAG, "onCreate: ");
searchDevices();
}
private void turnOnBT() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
public void init()
{
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//Create a BroadCastReceiver for ACTION_FOUND
mReceiver=new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
//When discovery finds a device
if(BluetoothDevice.ACTION_FOUND.equals((action)))
{
//Get the BluetoothDevice object from the Intent
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//Add the name and address to an array adapter to show in a ListView
if(!macID.contains(device.getAddress().toUpperCase()))
macID.add(device.getAddress().toUpperCase());
Toast.makeText(context,device.getName(),Toast.LENGTH_SHORT).show();
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals((action)))
{
if(mBluetoothAdapter.getState()== BluetoothAdapter.STATE_OFF) {
turnOnBT();
}
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals((action)))
{
if(countScans == numCountScans-1)
{
rippleBackground.stopRippleAnimation();
Intent in = new Intent(BluetoothScanActivity.this, MarkStudentsActivity.class);
in.putExtra("Class ID", classID);
in.putExtra("Value",value);
in.putStringArrayListExtra("MAC ID's", macID);
intent.putExtra("Manual Date",selectDateCheck);
intent.putExtra("Selected Date",selectedDate);
startActivity(in);
finish();
}
else
{
countScans++;
Log.d("Mark","" + countScans);
mBluetoothAdapter.startDiscovery();
}
}
}
};
filter=new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
if(mBluetoothAdapter!=null)
mBluetoothAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}

How to refresh the static value when activity executed again

Here there is an activity called groupchat. Here I am having the static object activeEventMO.
In this groupchat activity the chatting function is going on. If user1 send a message to user2 that message received by gcmIntent class. in this gcmIntent class I have added the code for notification. Here if user1 send a message for a particular event notification received for user2. If user2 clicks that notification it will take to the user to that chat window that means groupchat activity.
for that in gcmIntent class I used parcelable to send the eventMO to groupchat activity. if user1 send a message to user2 for event2 user2 receives a notification. if user2 clciks the notification it show the chatwindow of event1. because when first time I send the eventid1 by sing eventMO. So it holds the eventid1 forever. it cannot refreshed.
This is my groupchat activity code
public class GroupChatActivity extends Activity {
private static ListView listViewMessages;
private static List<ChatMO> listChatMessageObjectses = new ArrayList<ChatMO>();
private static MessagesListAdapter adapter;
private static Handler UIHandler;
private static int RESULT_LOAD_IMAGE = 1;
private EditText inputMsg;
private String formatDate;
private Context context;
private String dateResult;
private static EventMO activeEventMO = null;
private UserDelegate userDelegate = new UserDelegate();
private MediaDelegates mediaDelegates = new MediaDelegates();
private MessageDelegates messageDelegates = new MessageDelegates();
private SharedPreferences sharedpreferences;
private List<UserMO> eventUserMOs = new ArrayList<>();
private Gson gson = new Gson();
private UserMO userMO = new UserMO();
private MessageMO messageMO = new MessageMO();
private File imgFile;
private MediaMO mediaMO = new MediaMO();
// this method is for store the current event id to eventMO coz eventMO globally declared as static
public void getevent()
{
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
}
public static void messageHandler(final MessageMO messageMo) {
UIHandler = new Handler(Looper.getMainLooper());
UIHandler.post(new Runnable() {
public void run() {
Log.e("messageHandler", messageMo.getEventTitle());
ChatMO chatMO = new ChatMO();
chatMO.setMessage(messageMo.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMo.getfromUserName());
chatMO.setDate(messageMo.getDate());
Log.e("handler", "eventMO" + activeEventMO);
Log.e("handler", "messageMO" + messageMo);
if (activeEventMO.getEventId() == messageMo.getEventId()) {
listChatMessageObjectses.add(chatMO);
listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 1);
editor.putLong("eventId", activeEventMO.getEventId());
editor.commit();
Log.i("App", "start");
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
Log.i("App", "stop");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 2);
editor.commit();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.image_upload, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ChatMO chatMO = new ChatMO();
chatMO.setMessage_type(Constants.IS_TYPE_CHAT_IMAGE);
chatMO.setMessage(picturePath);
chatMO.setSelf(1);
chatMO.setIs_delete(0);
chatMO.setFromName("");
chatMO.setEvent_id(activeEventMO.getEventId());
messageMO.setMessage("");
messageMO.setRingeeUserId(userMO.getRingeeUserId());
// messageMO.setDate(messageMO.getDate());
messageMO.setMobileNumber(userMO.getMobileNumber());
messageMO.setEventId(activeEventMO.getEventId());
messageMO.setEventTitle(activeEventMO.getText());
Log.e("sendbutton", "eventtitle" + messageMO.getEventTitle());
messageMO.setfromUserName(userMO.getUserName());
messageMO.setMessageType(Constants.MESSAGE_TYPE_MSG);
mediaMO.setRingeeUserId(userMO.getRingeeUserId());
mediaMO.setIsType(Constants.IS_TYPE_CHAT_IMAGE);
imgFile = new File(picturePath);
listChatMessageObjectses.add(chatMO);
listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return mediaDelegates.insertChatFile(context, imgFile, messageMO, eventUserMOs, mediaMO);
}
#Override
protected void onPostExecute(String mediaBo) {
Toast.makeText(getApplicationContext(), "uploaded Status" + mediaBo, Toast.LENGTH_LONG).show();
if (!mediaBo.equals("null")) {
MediaMO mediaMO1 = gson.fromJson(mediaBo, new TypeToken<MediaMO>() {
}.getType());
}
}
}.execute(null, null, null);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.ic_menu_gallery) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final List<ChatMO> chatMOs1 = new ArrayList<>();
activeEventMO = new EventMO();
setContentView(R.layout.chat_main);
context = getApplicationContext();
String message = "";
DatabaseHelper dbHelper = new DatabaseHelper(context);
listChatMessageObjectses = chatMOs1;
inputMsg = (EditText) findViewById(R.id.inputMsg);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
Log.e("oncreate", "eventMO" +activeEventMO);
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(activeEventMO.getEventId());
Log.e("oncreate", "chatMOs" + chatMOs);
for (ChatMO chatMO1 : chatMOs) {
message = chatMO1.getMessage();
chatMO1.getEvent_id();
chatMO1.getFromName();
int messageType = chatMO1.getMessage_type();
chatMO1.getDate();
chatMO1.isSelf();
if (messageType == 0) {
chatMOs1.add(chatMO1);
}
}
adapter = new MessagesListAdapter(context, chatMOs1);
//adapter functionality added for show the previous chat list of event/invite
listViewMessages.setAdapter(adapter);
sharedpreferences = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, context.MODE_PRIVATE);
// by default first primary user is current user in sql lite
// user table
userMO = dbHelper.getUserData(1);
here i am passing the eventMO in gcmIntent
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
EventMO eventMO = new EventMO();
eventMO.setEventId(messageMO.getEventId());
Log.e("gcm","evetid"+eventMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("MessageMO", gson.toJson(messageMO));
editor.commit();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_dialog_info).setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName())).setContentText(messageMO.getMessage()).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
Log.e("gcm","eventid"+messageMO.getEventId());
mNotificationManager.notify((int) (long) eventMO.getEventId(), mBuilder.build());
}
can you please tell me how to fix this issue thanks in advance
To refresh a variable after you activity or fragment has been destroyed you need to store in the saved bundled provided you in the method
public void onSavedInstanceState(final Bundle bundle)
And reset values with the bundle provided in the method
public void onCreate(final Bundle savedInstance)
Here is some good documentation
enter code here[Recreating an Activity - Android][1]

Categories