Make Android app get bluetooth manufacturer data - java

I am working on an Android app android 10 and nordic nrf52840 which is advertising at channel 37,38,39 I want to get the manufacturer data from my nordic bluetooth device. Like the picture shown below. Now I can scan and find my device, but I don't know how to get manufacturer data.
package com.example.test373839;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.BatchingListUpdateCallback;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter=null;
private BluetoothManager mbluetoothManager=null;
private BroadcastReceiver mReceiver=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnScan=(Button)findViewById(R.id.button);
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
}
public void StartScan(View view) {
Log.d("Button","click");
checkBTPermission();
mBluetoothAdapter.startDiscovery();
IntentFilter dicoveryDeviceIntent=new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastreceiver,dicoveryDeviceIntent);
}
private void checkBTPermission(){
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
int pc=this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
pc+=this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if(pc!=0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1001);
}else {
Log.d("Bluetooth","checkBT permission");
}
}
}
final private BroadcastReceiver mBroadcastreceiver=new BroadcastReceiver() {
#Override
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
Log.d("Bluetooth",device.getAddress()+":"+device.getName());
}
}
};
}

Related

Android studio notification unable to display

package com.example.twapp.Observer;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.widget.Button;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.example.twapp.Notify;
import com.example.twapp.R;
import com.example.twapp.testReceiver;
public class ConcreteObserverA extends AppCompatActivity implements Observer {
NotificationManager notificationManager;
NotificationChannel channel;
Context context = this;
private String observerState;
private ConcreteSubject concreteSubject; // 持有指向 ConcreteSubject 物件的 reference
public ConcreteObserverA(ConcreteSubject concreteSubject) {
this.concreteSubject = concreteSubject;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void update() {
setContentView(R.layout.activity_notify);
notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
channel=new NotificationChannel("ID","com.example.twapp",NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
Intent intent = new Intent(context,testReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("訊息")
.setContentText("跌倒啦~")
.setChannelId("ID");
Notification notification=builder.build();
notificationManager.notify(1,notification);
}
}
I use the Observer pattern to implement notifications, but I have problems when my concreateObserver wants to print notifications.
When I delete this method. Simple print is feasible.Because I can't think of a way. So come to ask everyone android studio master.

How to show toast message using JobScheduler

I have been learning jobscheduler in andorid. I have trying to show a toast message in the onstartjob() after every 1minute. But its not showing up. Any help will be grateful.
jobschedul_service .class:
package com.prajwal.jobscheduler;
import android.app.Service;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class jobschedul_service extends JobService {
#Override
public boolean onStartJob(JobParameters jobParameters) {
Toast.makeText(getApplicationContext(), "After 15 minutes", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
return true;
}
}
MainActivity.class:
package com.prajwal.jobscheduler;
import androidx.appcompat.app.AppCompatActivity;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private static final int LOAD_ARTWORK_JOB_ID = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JobScheduler jobScheduler =
(JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(new JobInfo.Builder
(LOAD_ARTWORK_JOB_ID, new ComponentName(this, jobschedul_service.class))
.setPeriodic(900000)
.build());
}
}
Manifest.xml:
<service
android:name=".jobschedul_service"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"></service>
Got the answer!
The reason was the setperiodic(long interval).
As per the ss below:
This function was added in API 21 i.e Lolipop version. Whereas I was running the app on version > Lolipop.
Whereas this new function in the image below:
was added in API 24 i.e. Nougat
Hence, if you are targetting your app below Nougat i.e < Nougat but >= Lolipop then use setPeriodic(long interval) method whereas if u r targetting >= Nougat then use setPeriodic(long interval, long flexinterval).
Solution
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
{
builder.setPeriodic(900000,6000);
}
else
{
builder.setPeriodic(900000);
}

Multiple notifications with different data

I have an issue with my app that i cant solve. The app takes the input(reminder) from a user and then sets it as a notification. The user can create as many notifications as he/she likes. I want the user to click the notification and get taken to a new activity(Reminder), so he/she can see the reminder in a TextView. So i have an activity(SetReminder), which let the user put his data in a text editor.Then i save his data in a hashMap. The int is the id of user's string data. Then i have a class (AlarmReceiver) which extends BroacastReceiver and generates the notification.In this class i have an id for each notification,which matches the hashMap's int from the SetReminder activity. That way i was expecting that the user would see the data of each notification.But that's doesn't happen. I have multiple Notifications(i want that), but the user sees the data of the last notification, no matter which notifications selects. I am posting the code from the three activities.
Thanks in advance.
SetReminder.class
package demo.push_not_demo;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.widget.EditText;
import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment;
import java.util.HashMap;
public class SetReminder extends AppCompatActivity {
private SwitchDateTimeDialogFragment dateTimeFragment;
Button b1,b2,b3;
EditText editText;
public static int counter=0;
public static HashMap<Integer,String> hashMap;
private static final String TAG_DATETIME_FRAGMENT = "TAG_DATETIME_FRAGMENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_reminder);
hashMap= new HashMap<Integer, String>();
b1=(Button) findViewById(R.id.set_date_time);
b2=(Button) findViewById(R.id.cancel);
b3=(Button) findViewById(R.id.save);
b1.setOnTouchListener(touch);
b2.setOnTouchListener(touch);
b3.setOnTouchListener(touch);
editText=(EditText) findViewById(R.id.reminder_edit);
}
View.OnTouchListener touch= new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()){
case R.id.set_date_time:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
// Construct SwitchDateTimePicker
dateTimeFragment = (SwitchDateTimeDialogFragment) getSupportFragmentManager().findFragmentByTag(TAG_DATETIME_FRAGMENT);
if(dateTimeFragment == null) {
dateTimeFragment = SwitchDateTimeDialogFragment.newInstance(
getString(R.string.label_datetime_dialog),
getString(R.string.positive_button_datetime_picker),
getString(R.string.negative_button_datetime_picker)
);
}
dateTimeFragment.show(getSupportFragmentManager(), TAG_DATETIME_FRAGMENT);
}
break;
case R.id.cancel:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
cancelalarm();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
Intent intent = new Intent(SetReminder.this,HomeScreen.class);
startActivity(intent);
}
break;
case R.id.save:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
counter++;
hashMap.put(counter,editText.getText().toString());
alarmservice();
}
break;
}
return false;
}
};
public void alarmservice(){
Intent intent = new Intent(this,AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(alarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+ 5000,pendingIntent);
}
public void cancelalarm(){
Intent intent = new Intent(this,AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
AlertReceiver.class
package demo.push_not_demo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.EditText;
import java.util.HashMap;
import static android.support.v4.app.NotificationCompat.DEFAULT_SOUND;
import static android.support.v4.app.NotificationCompat.PRIORITY_HIGH;
import static android.support.v4.app.NotificationCompat.VISIBILITY_PUBLIC;
public class AlertReceiver extends BroadcastReceiver {
public static int id=0;
#Override
public void onReceive(Context context, Intent intent) {
id++;
createNotification(context);
}
private void createNotification(Context context) {
NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setSmallIcon(R.drawable.offer1)
.setContentTitle("Notification Title")
.setContentText("Tap to see your reminder")
.setPriority(PRIORITY_HIGH)
.setVibrate(new long[] { 50, 1000, 500, 1000, 1000 })
.setDefaults(DEFAULT_SOUND)
.setVisibility(VISIBILITY_PUBLIC);
Intent intent = new Intent(context,Reminder.class);
PendingIntent pendingintent = PendingIntent.getActivity(context,id,intent,PendingIntent.FLAG_ONE_SHOT);
notification.setContentIntent(pendingintent);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification ntfc = notification.build();
nm.notify(id,ntfc);
}
}
Reminder.class
package demo.push_not_demo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import static demo.push_not_demo.AlertReceiver.id;
import static demo.push_not_demo.SetReminder.hashMap;
public class Reminder extends AppCompatActivity{
TextView txtv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reminder);
txtv=(TextView) findViewById(R.id.reminder_textView);
txtv.setText(hashMap.get(id));
}
}
dont use static id,in your code id is always 0. you can check it using Log!
use another way for produce different ids.
when you add notification with same id, the new notification will replace with last notification. use random integer for id

How do I get the NMEA data from a serial GPS connected to my android device?

I am working on a project where I have to connect my android device to a GPS with usb. I can't figure out how I can get the data out of my GPS and I do not want to use the device it's internall GPS because I need to be pretty accurate. I have read the tutorial on the android website and I have tried to work with it but I still do not understand how I have to make connection to the GPS.
Here is my code.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.util.HashMap;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
UsbDevice device = deviceList.get("deviceName");
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){
if(device != null){
//roep hier de method aan om communicatie met he apparaat te maken
}
}
else{
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
}
}
You might want to give this a shot: http://code.google.com/p/usb-serial-for-android/. Captures all serial data, does not require rooting. You would need to use Service. Let us know if you need more help. I have done this before, not on Android though.

Trouble witn creating notification in status bar from service Android

I need to create Service in my application for showing notifications. I have the code for service:
package com.bba.droid;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class AlertsMonitorService extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int id) {
NotificationManager notifyMngr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification=new Notification(R.drawable.icon_back, "Downloading...", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, null, 0);
notification.setLatestEventInfo(this.getApplicationContext(), "YoutubeDownloader", "The video is downloading...", contentIntent);
notifyMngr.notify(0, notification);
}
}
And I have code for main Activity:
package com.bba.droid;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
public class DroidTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent service=new Intent();
service.setClass(this, AlertsMonitorService.class);
this.startService(service);
}
}
But service doesn't create a notification in status bar. Where have I made mistake?
I don't know if this is the only problem, but you are specifying null for the activity in your intent:
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, null, 0);
You want to specify an intent that will launch your activity:
Intent intent = new Intent(this, DroidTestActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent, 0);

Categories