Discovering Bluetooth Devices: ListView will not get updated - android

I am trying to discover Bluetooth Devices.
When I'm debugging my adapter gets filled, but my listview wount refresh, I am seeing just a blank site.
here is my code:
package com.example.elevator;
import java.util.Set;
import android.os.Bundle;
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.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter mBluetoothAdapter = null;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_main);
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
// newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClickbtnActivateBluetooth(View view)
{
if (mBluetoothAdapter == null)
{
Toast.makeText(this, "Bluetooth ist nicht verfügbar!", Toast.LENGTH_LONG).show();
finish();
return;
}
else if (!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
Toast.makeText(this, "Bluetooth wurde aktiviert!", Toast.LENGTH_LONG).show();
findViewById(R.id.btnSearchDevices).setEnabled(true);
}
public void onClickbtnSearchDevices(View view)
{
mBluetoothAdapter.startDiscovery();
Toast.makeText(this, "Bluetooth Geräte werden gesucht!", Toast.LENGTH_LONG).show();
// Find and set up the ListView for newly discovered devices
}
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver 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);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
mNewDevicesArrayAdapter.notifyDataSetChanged();
}
}
}
};
}
the activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/btnSearchDevices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btnEnableBT"
android:layout_alignRight="#+id/btnEnableBT"
android:layout_below="#+id/btnEnableBT"
android:enabled="false"
android:onClick="onClickbtnSearchDevices"
android:text="Geräte suchen" />
<Button
android:id="#+id/btnEnableBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="onClickbtnActivateBluetooth"
android:text="Enable Bluetooth" />
<ListView
android:id="#+id/new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/btnSearchDevices" >
</ListView>
</RelativeLayout>
the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.elevator"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.SET_DEBUG_APP"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.elevator.MainActivity"
android:label="#string/app_name" >
android:debuggable="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I hope you can help me!

You have to pass the list as a constructor argument.
mNewDevicesArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,devicesList);

Instead of
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
you may also try this.
mNewDevicesArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
After that your list view will be updated each time you discover a new device using:
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());

Related

Android app crashes on Bluetooth connect?

I'm trying to connect to other Android devices using Bluetooth via my app. The app works fine while discovering nearby Bluetooth devices. However, upon connecting, the app crashes.
I have two JAVA files other than MainActivity.java that are responsible for discovering & connecting to other Bluetooth devices. Their codes are posted below:
SearchBTDevice.java (for discovering nearby devices)
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Set;
public class SearchBTDevice extends AppCompatActivity {
public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
public ArrayAdapter PairedArrayAdapter;
public ArrayAdapter BTArrayAdapter;
BluetoothDevice btd;
public ListView devicesFound;
private final BroadcastReceiver BTReceiver= new BroadcastReceiver(){
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t" + btd.getAddress() + "\n");
}
}
};
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
#Override
protected void onResume() {
super.onResume();
this.registerReceiver(BTReceiver,filter1);
}
#Override
protected void onPause() {
super.onPause();
BlueAdapter.cancelDiscovery();
this.unregisterReceiver(BTReceiver);
Toast.makeText(SearchBTDevice.this, "Discovery Stopped!!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
searchBTDevices();
}
public void searchBTDevices()
{
if(!BlueAdapter.startDiscovery())
Toast.makeText(SearchBTDevice.this, "Failed to Start Discovery", Toast.LENGTH_SHORT).show();
else
Toast.makeText(SearchBTDevice.this, "Discovery Startred", Toast.LENGTH_SHORT).show();
BTArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
devicesFound = (ListView)findViewById(R.id.searchpagelistView);
devicesFound.setAdapter(BTArrayAdapter);
devicesFound.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent connectedBTintent = new Intent(SearchBTDevice.this, ConnectedBTDevice.class);
connectedBTintent.putExtra("BluetoothDevice", btd);
startActivity(connectedBTintent);
}
});
}
}
This is updated ConnectedBTDevice.java, responsible for connecting devices
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.IOException;
import java.util.UUID;
public class ConnectedBTDevice extends AppCompatActivity {
public BluetoothDevice btd;
public BluetoothSocket btSocket, tempSocket;
private UUID myUUID;
ArrayAdapter arr;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connected_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
arr = new ArrayAdapter(this, android.R.layout.simple_list_item_2);
btd = getIntent().getParcelableExtra("BluetoothDevice");
connectBT();
displayStuff();
}
public void connectBT() {
Thread myThread = new Thread() {
public void run() {
tempSocket = null;
try {
tempSocket = btd.createRfcommSocketToServiceRecord(myUUID);
} catch (IOException e) {
e.printStackTrace();
}
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
try {
tempSocket.connect();
arr.add("CONNECTED TO-->" + btd.getName());
} catch (IOException e) {
e.printStackTrace();
try {
tempSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
};
myThread.start();
}
public void displayStuff()
{
lv = (ListView)findViewById(R.id.connectedBTlistView);
lv.setAdapter(arr);
}
}
This is activity_connected_btdevice.xml for ConnectedBTDevice.java activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="vertex2016.mvjce.edu.bluealert.SearchBTDevice">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.NoActionBar.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.NoActionBar.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_connected_btdevice" />
</android.support.design.widget.CoordinatorLayout>
This is content_connected_btdevice.xml for ConnectedBTDevice.java
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="vertex2016.mvjce.edu.bluealert.ConnectedBTDevice"
tools:showIn="#layout/activity_connected_btdevice">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/connectedBTimageView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:src="#drawable/bluealert_bg"
android:scaleType="centerCrop"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Connected Bluetooth Device"
android:id="#+id/connectedBTtextextView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp"
android:textSize="25dp"
android:textAlignment="center"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/connectedBTlistView"
android:layout_below="#+id/connectedBTtextextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp" />
</RelativeLayout>
This is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vertex2016.mvjce.edu.bluealert">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#mipmap/bluealerticon"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar">
<activity
android:name=".SplashScreen"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<activity
android:name=".SearchBTDevice"
android:label="#string/title_activity_search_btdevice"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="vertex2016.mvjce.edu.bluealert.MainActivity" />
</activity>
<activity
android:name=".ConnectedBTDevice"
android:label="#string/title_activity_connected_btdevice"
android:parentActivityName=".SearchBTDevice"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="vertex2016.mvjce.edu.bluealert.SearchBTDevice" />
</activity>
</application>
</manifest>
Here's the exception that my updated logcat shows
03-24 00:19:40.541 7205-9703/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: Thread-35890
Process: vertex2016.mvjce.edu.bluealert, PID: 7205
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.UUID.getMostSignificantBits()' on a null object reference
at android.os.ParcelUuid.writeToParcel(ParcelUuid.java:129)
at android.bluetooth.IBluetooth$Stub$Proxy.connectSocket(IBluetooth.java:1767)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:309)
at vertex2016.mvjce.edu.bluealert.ConnectedBTDevice$1.run(ConnectedBTDevice.java:63)
I don't understand what the problem is. I have tried several online tutorials, but nothing seemed to work. I know the problem is in my ConnectedBTDevice.java, but can't figure out the point at which it's throwing the exception.
Thank you for your time.
You are assigning BluetoothSocket to tempSocket, and then you try to invoke connect() method on btSocket which is null.

How to know whether the intent is finished or not?

I want to know after my application call an intent, it is finished or not. If it is finished, then call another activity. How can do this? Thank you.
Intent callintent = new Intent(Intent.ACTION_CALL);
callintent.setData(Uri.parse("tel:" + num));
startActivity(callintent);
if(callintent is finished)
{
startActivity(new Intent(MakeCall.this, NewActivity.class));
}
PhoneStateListener helps when a phone call is ended, come back to the original activity (actually, it just restart the activity).
MainActivity .java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
final Context context = this;
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.buttonCall);
// add PhoneStateListener
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager) this
.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
// add button listener
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:1234567890"));
startActivity(callIntent);
}
});
}
//monitor phone call activities
private class PhoneCallListener extends PhoneStateListener {
private boolean isPhoneCalling = false;
String LOG_TAG = "LOGGING 123";
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
Log.i(LOG_TAG, "OFFHOOK");
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended,
// need detect flag from CALL_STATE_OFFHOOK
Log.i(LOG_TAG, "IDLE");
if (isPhoneCalling) {
Log.i(LOG_TAG, "restart app");
// restart app
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
isPhoneCalling = false;
}
}
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="call 1234567890" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

broadCast Receiver is never called

I am trying to detect if the WiFi is connected or not by listening to the "SUPPLICANT_CONNECTION_CHANGE_ACTION" as shown below in the code. But the problem is
when i run the App i receive no notificatio from the broadCast Receiver i am registered to!!
why that is happening and how to solve it?
code:
IntentFilter intentFilter2 = new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityModule();
}
protected void ConnectivityModule() {
// TODO Auto-generated method stub
Log.d(TAG, "#interNetConnectivityModule: called");
registerReceiver(SupplicantReceiver, intentFilter2);
}
BroadcastReceiver SupplicantReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (supplicantState == (SupplicantState.COMPLETED)) {
Log.d(TAG, "#SupplicantReceiver: connected");
}
if (supplicantState == (SupplicantState.DISCONNECTED)) {
Log.d(TAG, "#SupplicantReceiver: not connected");
}
}
}
};
Here is Example :
Main Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// broadcast a custom intent.
public void broadcastIntent(View view)
{
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
My Broadcast Receiver :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
This is how you should declare Broadcast Receiver in your Manifest :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="#+id/btnStartService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/broadcast_intent"
android:onClick="broadcastIntent"/>
</LinearLayout>
Your receiver looks correctly registered (at runtime, not based on Manifest, but whatever, should be good anyway).
I'm guessing.. have you tried putting logs in onReceive method like
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d(TAG, "Reached this point, receiver is working");
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (supplicantState == (SupplicantState.COMPLETED)) {
Log.d(TAG, "#SupplicantReceiver: connected");
}
if (supplicantState == (SupplicantState.DISCONNECTED)) {
Log.d(TAG, "#SupplicantReceiver: not connected");
}
Log.d(TAG, "Checking for an error in retrieving data!");
boolean myTest = intent.getBooleanExtra(EXTRA_SUPPLICANT_CONNECTED, false);
if (myTest) Log.d(TAG, "This way it worked!");
else Log.d(TAG, "This does not mean it didn't work at all! Might just be the correct value as a DISCONNECTED status");
} else Log.d(TAG, "Bizzarre error, action received was different from the one receiver was registered to! [ " + action + " ] ");
}
My guess is that you might be trying to retrieve the information in a wrong way, and with logs so strictly defined you can't see enough of what happens, but the receiver works fine

Why no broadcast's received between two activities?

I don't know why my receiver does not receive any thing.
I want to send broadcast between two activities.
tv1 does not show "msg".
Here is the code
send:
Intent intent = new Intent(action);
intent.putExtra("msg", "a");
sendBroadcast(intent);
startActivity(new Intent(MainActivity.this,sec.class));
receiver:
IntentFilter intentFilter = new IntentFilter(MainActivity.action);
registerReceiver(receiver, intentFilter);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
tv1.setText(intent.getExtras().getString("msg"));
}
};
You can implement like this:
package com.example.broadcastrecieverdemo;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private InternalReciever internalReciever;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
internalReciever = new InternalReciever();
IntentFilter filter = new IntentFilter("kishan");
registerReceiver(internalReciever, filter);
findViewById(R.id.btnSendBroadcast).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("com.example.broadcastrecieverdemo.CUSTOM_INTENT");
sendBroadcast(intent);
}
});
findViewById(R.id.btnInternalSendBroadcast).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("kishan");
sendBroadcast(intent);
}
});
}
#Override
protected void onDestroy() {
unregisterReceiver(internalReciever);
super.onDestroy();
}
}
class InternalReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Inernal Broadcast recieved",
Toast.LENGTH_SHORT).show();
}
}
Reciever.java
package com.example.broadcastrecieverdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class Reciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast recieved", Toast.LENGTH_SHORT)
.show();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.broadcastrecieverdemo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Reciever" >
<intent-filter>
<action android:name="com.example.broadcastrecieverdemo.CUSTOM_INTENT" >
</action>
</intent-filter>
</receiver>
</application>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Broad cast receiver"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/btnSendBroadcast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="21dp"
android:gravity="center"
android:text="Send" />
<Button
android:id="#+id/btnInternalSendBroadcast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/btnSendBroadcast"
android:layout_marginTop="21dp"
android:gravity="center"
android:text="Send Internal" />

how to start the app on power button press

I want to start my app when a user press the power button. I m following This code
but its not showing any Log and toast.
here is my complete code.
MyReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.v("onReceive", "Power button is pressed.");
Toast.makeText(context, "power button clicked", Toast.LENGTH_LONG)
.show();
// perform what you want here
}
}
menifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.powerbuttontest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.powerbuttontest.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF" >
</action>
<action android:name="android.intent.action.SCREEN_ON" >
</action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" >
</action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" >
</action>
<action android:name="android.intent.action.ACTION_SHUTDOWN" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity.java
package com.example.powerbuttontest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I think i m committing a mistake in my menifest file. please have a look on this. thanks.
First, unlike other broad casted intents, for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON you CANNOT declare them in your Android Manifest! so You need to make a service which will keep on running like this
public static 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 Receiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
// your code
} else {
// your code
}
}
}
and your receiver can be something
public class Receiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
Here is my complete code. Hope this helps. I was basically making a look screen app. This will disable your default lock screen. and on power button press it will start a service and runs to look for power button press event.
Layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/toggleButton1"
android:layout_marginTop="72dp"
android:enabled="false"
android:text="Settings" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="72dp"
android:checked="true"
android:textOff="Disable"
android:textOn="Enable" />
</RelativeLayout>
MainActivity.java
package com.example.powerbuttontest;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ToggleButton btnToggleLock;
Button btnMisc;
Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMisc = (Button) findViewById(R.id.button1);
btnToggleLock = (ToggleButton) findViewById(R.id.toggleButton1);
toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
btnToggleLock.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (btnToggleLock.isChecked()) {
toast.cancel();
toast.setText("Unlocked");
toast.show();
Log.i("Unlocked", "If");
Context context = getApplicationContext();
KeyguardManager _guard = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock _keyguardLock = _guard
.newKeyguardLock("KeyguardLockWrapper");
_keyguardLock.disableKeyguard();
MainActivity.this.startService(new Intent(
MainActivity.this, UpdateService.class));
} else {
toast.cancel();
toast.setText("Locked");
toast.show();
Context context = getApplicationContext();
KeyguardManager _guard = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock _keyguardLock = _guard
.newKeyguardLock("KeyguardLockWrapper");
_keyguardLock.reenableKeyguard();
Log.i("Locked", "else");
MainActivity.this.stopService(new Intent(MainActivity.this,
UpdateService.class));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
Log.i("onConfigurationChanged", "Called");
}
}
MyReciever.java
package com.example.powerbuttontest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
UpdateService.java
package com.example.powerbuttontest;
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 {
BroadcastReceiver mReceiver;
#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);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.i("screenON", "Called");
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
// Toast.makeText(getApplicationContext(), "Sleep",
// Toast.LENGTH_LONG)
// .show();
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Menifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.powerbuttontest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver" />
<service android:name=".UpdateService" />
</application>
</manifest>
Here this one is the complete code, which will open your application as soon you presss power button. I am also doing the same project, where i want to open my Application directly after i press power button (turn on).
MainActivity.java
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_power_offon);
startService(new Intent(getApplicationContext(), LockService.class));
}//EOF Oncreate
}//EOF Activity
LockService.java
public class LockService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder
{
LockService getService() {
return LockService.this;
}
}//EOF SERVICE
ScreenReceiver.java
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
public void onReceive(final Context context, final Intent intent) {
Log.e("LOB","onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
// do whatever you need to do here
wasScreenOn = false;
//Log.e("LOB","wasScreenOn"+wasScreenOn);
Log.e("Screen ","shutdown now");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
// and do whatever you need to do here
wasScreenOn = true;
Log.e("Screen ","awaked now");
Intent i = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
{
Log.e("LOB","userpresent");
// Log.e("LOB","wasScreenOn"+wasScreenOn);
}
}
}//EOF SCREENRECEIVER.JAVA
Now this is xml file, Please copy paste and just change the package name you are using
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.userpresent.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.userpresent.LockService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>
</application>

Categories

Resources