Android: Bluetooth activity launch - android

I am building a piece of code that imitates an activity when the phone receives an active Bluetooth connection. This is to run as a service so it can be picked up on in the moment.
Here is the code I am working with. Right now its not launching the intent but its not failing either. How do I get this to run properly?
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class detectService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private BroadcastReceiver ConnectListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
{
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//Start Second Activity
Intent secondIntent = new Intent(detectService.this, otherClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(secondIntent);
}
}
};
}

You need to register the receiver you created using
registerReceiever(ConnectListener, intentFilter);
the intent filter in your case will be the bluetooth connnect filter, something like
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
For a more complete example look at this other post

Related

what will be the permission for calling broadcastReceiver on Runtime in Marshmallow

Basically i have created alarm app but the broadcastReceiver not getting called in the marshmallow i know about the runtime permission required in the marshmallow but i don't know what will be the permission for my problem for calling broadcastReceiver.
Can anybody please suggest me something please.
I simply solve this problem by creating a service by following this link
Link
Service Code Here...
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
/**
* Created by waqar on 1/05/2017.
*/
public class LocalService extends Service {
AlarmReceiver alarmReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarmReceiver = new AlarmReceiver();
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
this.registerReceiver(alarmReceiver, screenStateFilter);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(alarmReceiver);
}
}
And start this service from MainActivity in onCreate Method.
Intent intent = new Intent(getApplicationContext(), LocalService.class);
getApplicationContext().startService(intent);
And don't forget to register this service in the manifest.

Activity is never called

I am working on an android application where an action is triggered after specific interval of time again and again when there is an Intent.FLAG_ACTIVITY_NEW_TASK Broadcast message received.
I have the following code in UpdateService.java:
package com.missnoob.screentimeout;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class UpdateService extends Service {
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.v("ScreenTimeOut","Broadcast Received");
Toast.makeText(getApplicationContext(), "Broadcast Received", Toast.LENGTH_LONG).show();
//This part is not working
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//This part is not working
}
else
{
// YOUR CODE
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And the following code in Notification.java:
package com.missnoob.screentimeout;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.shadow.screentimeout.R;
public class Notification extends Activity {
/** Called when the activity is first created. */
Timer timer;
Toast toast;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = new Timer();
toast = Toast.makeText(getApplicationContext(), "15 seconds after",Toast.LENGTH_SHORT);
timer.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run() {
toast.show();
Log.v("ScreenTimeOut","Toast showed");
}
}, 0, 5000);
}
}
In UpdateService.java
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
never gets triggered.
You are missing startActivity(i)
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Also you cannot have
toast.show();
in timer as it runs on a different thread and you can update ui only on the ui thread.
Instead use a Handler. You can find an example #
Android Thread for a timer
You have not called startActivity(i).
See Start Another Activity (android developer website).
You are didn't call startActivity(i), thats why your activity is never caled, all you have to do is like this :
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

binding remote service from broadcastreceiver

I have a BroadcastReceiver named StartService which start when the phone boots which in turn starts a service but when I am going to the service from this BroadcastReceiver I get exception:
android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to bind to services
my code is below:
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
public class StartService extends BroadcastReceiver {
private RemoteServiceConnection conn = null;
private IMyRemoteService remoteService;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent startServiceIntent = new Intent(context, RemoteServiceClient.class);
context.startService(startServiceIntent);
conn = new RemoteServiceConnection();
Intent i = new Intent();
i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.RemoteService");
context.bindService(i, conn, Context.BIND_AUTO_CREATE);
}
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className,
IBinder boundService ) {
remoteService = IMyRemoteService.Stub.asInterface((IBinder)boundService);
Log.d( getClass().getSimpleName(), "onServiceConnected()" );
}
public void onServiceDisconnected(ComponentName className) {
remoteService = null;
Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
}
};
}
some of the step follow.
Step 1:
public class StartService extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, myServices.class);
context.startService(startServiceIntent);
}
}
Step 2:
// make all service related task
Step 3:
<service
android:name=".myServices"
android:enabled="true" />
<receiver android:name="com.yourpackage.StartService " >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
I am always used BroadcastReceiver and services this way.
May be helpful for you.If helpful then accept answer.

How to get Bluetooth Connecting status in android for API-level 7?

In my android project, my two devices are paired with each other. I want to send a file from one device to other device via Bluetooth and when this file is received either automatically or manually, my app on that device needs to read this file and do some action based on it.
I have created one service whose OnCreate method, I register one broadcast listener for CONNECTION_STATE_CHANGED. This service is started in OnCreate method of my main activity. So even if my app is not on front-end, this broadcast receiver would read the file and do the required action. First of all, is this the right way to do it? and if yes, please let me know how?
Following is my service file which registers a broadcast receiver. When I run this code and receive file, Broadcast Receiver's OnReceive is not being called.
package com.android;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class FileReceiver extends Service {
private static final String ACTION = "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
// private BroadcastReceiver BT_CONNECTION_BCAST_Receiver;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION);
Log.i("LocalService", "On created ");
// Registers the receiver so that your service will listen for broadcasts
this.registerReceiver(this.btReceiver_Receiver, theFilter);
}
private final BroadcastReceiver btReceiver_Receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Do whatever you need it to do when it receives the broadcast
// Example show a Toast message...
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("BT_Connection", "Inside Receiver");
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Log.i("BT_Connection", "Device Found");
}
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
{
Log.i("BT_Connection", "On BT Connection");
}
Log.i("LocalService", "On Broadcast Receiver");
showSuccessfulBroadcast();
}
};
#Override
public void onDestroy() {
super.onDestroy();
Log.i("LocalService", "On Being Destroyed!!");
// Do not forget to unregister the receiver!!!
this.unregisterReceiver(this.btReceiver_Receiver);
}
private void showSuccessfulBroadcast() {
Toast.makeText(this, "Broadcast Successful!!!", Toast.LENGTH_LONG).show();
}
}

Android - Bluetooth find device error

I'm new here so I apologize if I wrote something bad
I got some error in my code that should find some but device (in Eclipse it looks ok but it shows some Force Quit while I'm clicking button Find Device :(
Code
package com.moj.test;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Bluetooth extends Activity{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth);
Button bStart = (Button) findViewById(R.id.btbutton1);
Button bFind = (Button) findViewById(R.id.btbutton2);
bStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BluetoothStart();
}
});
bFind.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
mBluetoothAdapter.startDiscovery();
}
});
}
public void BluetoothStart() {
if (mBluetoothAdapter != null) {
if (!mBluetoothAdapter.isEnabled()) {
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BT);
}
}
}
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
EditText te = (EditText) findViewById(R.id.editText1);
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
te.setText(device.getName() + "\n" + device.getAddress());
}
}
};
}
You cant run this on Emulator because it doesn't have support for Bluetooth. You need to test it on a real device.
And don't forget to include Bluetooth permission in manifest.
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
...
</manifest>

Categories

Resources