I am trying to use BroadcastReceiver but it is not working, please help me to solve this problem.
MyReceiver.java
package com.example.broadcast_receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcast_receiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name=".MyReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.SCREEN_OFF"/>
</intent-filter>
</receiver>
<activity
android:name="com.example.broadcast_receiver.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>
</application>
</manifest>
BroadcastReceiver not working and not making any log, please help me to solve this problem.
Hey try using dynamic calling of broadcast,I tried this it will surly work...
public class MainActivity extends Activity {
//Create broadcast object
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}
If you want this receiver to be called by the system, you would need to export it. You set exported = "false", change this to true or remove exported entirely and this will start working. Normally this would be insecure, but as both SCREEN_ON and SCREEN_OFF are protected-broadcasts, and you verify the actions, only more trusted system code can send them too you, so it's pretty safe.
Sadly this wont work in this case as the intents broadcast have the following flags:
Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND
Can you try with getting battery value:
public class Broadcast extends Activity {
//Create broadcast object
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
//Get battery percentage
int batterylevel = intent.getIntExtra("level", 0);
//get progressbar
ProgressBar myprogressbar = (ProgressBar) findViewById(R.id.progressbar);
myprogressbar.setProgress(batterylevel);
TextView tv = (TextView) findViewById(R.id.textfield);
//Set TextView with text
tv.setText("Battery Level: " + Integer.toString(batterylevel) + "%");
}
});
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
Related
My Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:name="android.support.multidex.MultiDexApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadCastRecieverInternet">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
Its my Service code block.
public class MyBroadCastRecieverInternet extends BroadcastReceiver {
public void onReceive(final Context context, Intent intent) {
Log.d("MyLog","Internet Reciever is on");
}
}
Is there any mistake? I didn't find anything. It doesn't work and I don't know why.
From docs:
Apps targeting Android 7.0 (API level 24) and higher do not receive
CONNECTIVITY_ACTION broadcasts if they declare their broadcast
receiver in the manifest. Apps will still receive CONNECTIVITY_ACTION
broadcasts if they register their BroadcastReceiver with
Context.registerReceiver() and that context is still valid.
CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
You can downgrade your targetSdk to 23 or use dynamic broadcast receiver like this:
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
boolean isConnected = ConnectionManager.isConnectedToInternet(context);
if (!isConnected) {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private Context mContext = this;
private ConnectivityReceiver mConnectivityReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mConnectivityReceiver = new ConnectivityReceiver();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mConnectivityReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION
));
}
#Override
protected void onPause() {
unregisterReceiver(mConnectivityReceiver);
super.onPause();
}
}
You may try this approach. You don't need to make a whole new class for your broadcast receiver but you can use it inside your Main Activity like this:
BroadcastReceiver receiveLocationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Your custom action
}
};
IntentFilter receiveLocationFilter = new IntentFilter();
receiveLocationFilter.addAction("android.intent.RECEIVE_LOCATION");
Register the receiver in onStart:
registerReceiver(receiveLocationReceiver, receiveLocationFilter);
Unregister it in onStop:
unregisterReceiver(receiveLocationReceiver);
Then when you need to send the broadcast all you need is :
Intent sendBroadcastIntent = new Intent("android.intent.RECEIVE_LOCATION");
sendBroadcast(sendBroadcastIntent);
I know this was asked already many times but I can't get this to work. I looked all around Android docs and other sources. I got this activity that has a broadcast receiver variable inside and starts a service as such in the constructor:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "Received", Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compass);
Intent mIntent = new Intent(this, GPSTracker.class);
startService(mIntent);
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, new IntentFilter());
}
#Override
protected void onStop() {
unregisterReceiver(mReceiver);
super.onStop();
}
I put the service down in the manifest and I am sure it works properly. Any help will be appreciated.
Broadcast receiver is supposed to receive 2 floats from the service periodically.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jemboy.compass" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service
android:name=".GPSTracker"></service>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<activity android:name=".CompassActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OtherActivity"></activity>
</application>
In the activity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(UPDATE_PLAYER)) {
updateMediaPlayerToggle();
} else if (intent.getAction().equals(BUFFERING)) {
showMediaPlayerBuffering();
}
}
};
private void registerBroadcastReceiver() {
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter updateIntentFilter = new IntentFilter();
updateIntentFilter.addAction(UPDATE_PLAYER);
updateIntentFilter.addAction(BUFFERING);
broadcastManager.registerReceiver(broadcastReceiver, updateIntentFilter);
}
in the service.
private void sendUpdatePlayerIntent() {
Log.d(TAG, "updatePlayerIntent");
Intent updatePlayerIntent = new Intent(MainActivity.UPDATE_PLAYER);
LocalBroadcastManager.getInstance(this).sendBroadcast(updatePlayerIntent);
}
Example from a media player service.
I'm trying to learn to use Android BroadcasReceiver.
I wrote this code but It doesn't work... I tryed for example to change the Time etc...
What is it wrong?
I added in the Manifest:
<receiver android:name="com.example.broadcastreceiverspike.Broadcast" >
<intent-filter android:priority="100">
<action android:name="android.intent.action.ACTION_SCREEN_ON" />
<action android:name="android.intent.action.ACTION_SCREEN_OFF" />
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
My simple BroadcasReceiver:
public class Broadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BROADCAST", "It worked");
Toast.makeText(context, "BROADCAST", Toast.LENGTH_LONG).show();
}
}
My Main Activity (default main Activity)
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 solved!
"unlike other broad casted intents, for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON you CANNOT declare them in your Android Manifest! I’m not sure exactly why, but they must be registered in an IntentFilter in your JAVA code"
http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
Manifest
<receiver android:name=".Broadcast" >
<intent-filter>
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
Main Activity Class
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// INITIALIZE RECEIVER
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new Broadcast();
registerReceiver(mReceiver, filter);
}
}
My broadcast receiver
public class Broadcast extends BroadcastReceiver {
public static String TAG = "BROADCAST";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_TIME_CHANGED))
{
Log.d(TAG, "BROADCAST Cambio di orario");
Toast.makeText(context, "BROADCAST Cambio di orario", Toast.LENGTH_LONG).show();
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
Log.d(TAG, "BROADCAST Screen OFF");
Toast.makeText(context, "Screen OFF", Toast.LENGTH_LONG).show();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
Log.d(TAG, "BROADCAST Screen ON");
Toast.makeText(context, "BROADCAST Screen ON", Toast.LENGTH_LONG).show();
}
}
}
Did you add the needed premissions?
uses-permission android:name="android.permission.READ_PHONE_STATE"
This is a receiver to handle when screen is off or on or locked:
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
{
}
}
}
this is the manifest:
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>
Check out this tutorial about broadcast receivers.
Update:
I'm not sure you're using this tutorial, because there are lots of useful stuff in this tutorial, like this:
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
// handler for received Intents for the "my-event" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
In other words, you've created a custom broadcast receiver class, but you haven't used it.
And also please check this.
I had the same problem and I fixed it (tested on 4.3 and 5.1). I WAS able to declare "android.intent.action.USER_PRESENT" inside the manifest, as long as you have the READ_PHONE_STATE permission, it is OK!! My mini app consists of a Broadcast receiver that reacts to the screen ON/OFF state, and runs a background service that does continuous voice recognition. If the screen is off, the recognition is turned off. Here is the code, enjoy: MANIFEST:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <receiver android:name="classes.VoiceLaunchReceiver" >
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
BROADCAST RECEIVER:
public class VoiceLaunchReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
Intent service = new Intent(ctx, VoiceLaunchService.class);
// service.putExtra(action, true);
Log.i("joscsr","Incoming Voice Launch Broadcast...");
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.i("joshcsr", "************\nCSR Resumed (BC)\n************");
ctx.startService(service);
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("joshcsr", "************\nCSR STOPPED by SCREEN (BC)\n************");
ctx.stopService(service);
}
}
}
As you can imagine, my USER_PRESENT broadcast receiver is not registered anywhere else. I do register ACTION_SCREEN_OFF and ON in the onCreate method of my service, who was triggered by my receiver.
#Override
public void onCreate() {
super.onCreate();
//Register screen ON/OFF BroadCast
launcher=new VoiceLaunchReceiver();
IntentFilter i=new IntentFilter(Intent.ACTION_SCREEN_OFF);
i.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(launcher,i);
Log.d("joshcsr","VoiceLaunch Service CREATED");
}
Finally I unregister the screen on/off in the onDestroy() of my service:
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(launcher);}
I am trying to make an android app that must do some database activities like storing phone number and name etc in the SQLite DB . This all Data Base stuff is done as a service. The service must start as soon as the call comes and when the call ends the stored details must be showed to user as soon as the call ends. For this purpose I am using Broad Cast Receiver. I have also provide the following codes which I have used in my app.
MyServices.java
public class MyServices extends Service {
TelephonyManager Tel;
MyPhoneStateListener MyListener;
RB_SIGNAL_STRENGTH signalobj = new RB_SIGNAL_STRENGTH();
RB_DatabaseHandler db = new RB_DatabaseHandler(getApplicationContext());
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
isMyServiceRunning();
MyListener = new MyPhoneStateListener();
Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
super.onCreate();
Log.i("Serv","Service Started");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
db.close_DB();
Log.i("Serv","Service Stopped");
super.onDestroy();
}
MyReceiver.java
public class MyPhoneReceiver extends BroadcastReceiver {
String state=null;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
try{
Intent i = new Intent(context,MyServices.class);
Log.i("Recv", "In Try");
context.startService(i);
}
catch(Exception e)
{
Log.d("Recv", "Service not starting");
}
}//End if offhook
if(state.equals(TelephonyManager.EXTRA_STATE_IDLE))
{
Log.i("Recv","CALL ENDED");
try
{
Intent i = new Intent(context,EndActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
catch(Exception e){
Log.d("Recv", "Activity not starting");
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.SIGNAL_PERSISTENT_PROCESSES" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity android:name="StartActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="EndActivity" >
</activity>
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
<service
android:name="MyServices"
></service>
</application>
Your class name is MyPhoneReceiver but in your Manifest you are using MyReceiver, these two names must match exactly.
Addition
I just noticed that you are trying to instantiate your database before the Service has a valid Context. This will probably throw an exception in MyServices:
RB_DatabaseHandler db = new RB_DatabaseHandler(getApplicationContext());
You can to declare db as a field variable but leave it null:
RB_DatabaseHandler db;
And inside a method like onStartCommand() initialize it:
db = new RB_DatabaseHandler(getApplicationContext());
Lastly, calling fundamental methods like onCreate() out of order usually creates problems, this is not recommended in onStartCommand():
super.onCreate();
because state variable is null
public class MyPhoneReceiver extends BroadcastReceiver {
String state=null;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
//your code here...
I have read the instructions and examples in SO questions, but still unable to implement a simple BroadcastReceiver, it simply does not receive anything, can someone kindly provide some advice on the following code?
tnx
My activity:
public class Receiver1Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(MyService.MY_ACTION);
registerReceiver(new MyReceiver(), filter);
Intent intent = new Intent();
startService(intent);
}
}
My receiver:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.i("MyReceiver", "onreceive");
}
}
My service, which sends the broadcast:
public class MyService extends Service {
public static final String MY_ACTION = "com.receiver1.myaction";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent intent2 = new Intent(MY_ACTION);
sendBroadcast(intent2);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
My manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.receiver1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".Receiver1Activity"
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=".MyService"></service>
</application>
</manifest>
Are you sure that your service is even getting started? It looks like your just creating a blank intent and calling startService().
Your broadcastReceiver appears to be correct.
You need to register your receiver in your AndroidManifest.xml. Until you do that, the Android OS won't be able to find your BroadcastReceiver.