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.
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 am new to android.
My project is having one activity and one service. My service is having one broadcast receiver and activity is having broadcast sender which is in PeriodSender method .Dynamically when i am registering the receiver then at the start of the service it is not invoking but if i send some thing after few moment then it invokes.
But I want to register it in Manifest ,I have included the receiver details in Manifest but the receiver is not invoking . My receiver class name is MyReceiver21 and the intent action is MY_ACTION1. actually I want my broadcast receiver to be registered at the starting it self.
Following is my Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.experiment.Test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="3"
android:targetSdkVersion="3" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.experiment.Test.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=".MyReceiver21" >
<intent-filter>
<action android:name="com.experiment.Test.MainActivity.MY_ACTION1" />
</intent-filter>
</receiver>
<service
android:name="Myservice21"
android:enabled="true" />
</application>
</manifest>
my activity code is
public class MainActivity extends Activity {
MediaPlayer OurSong;
Context SavedThis=this;
int i=0;
public Handler handler1 = new Handler();
public Handler handler2= new Handler();
Button Start;
Button Stop;
Button Button21;
Button StopButton;
public int GProgreess=0;
int Rc=0;
int BitCount=0;
int SeekPos=0;
int Period=500;
MyReceiver myReceiver;
final static String MY_ACTION1 = "MY_ACTION1";
public int Data=0;
public int beat=0;
int BreakVar=0;
Thread myThread ;
static public TextView text1,text2,text3,text4;
private SeekBar bar;
private TextView textProgress,textAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StopButton=(Button)findViewById(R.id.buttonstop);
StopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
stopService(new Intent(SavedThis,Myservice21.class));
BitCount=0;
}/****End of on clk******/
});/*****End of set on clk listener*****/
Button21.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Rc=0;
BitCount=13;
stopService(new Intent(SavedThis,Myservice25.class));
SystemClock.sleep(200);
startService(new Intent(SavedThis,Myservice21.class));
PeriodSender();
}/****End of on clk******/
});/*****End of set on clk listener*****/
}
public void PeriodSender()
{
Intent intent1 = new Intent();
intent1.setAction("MY_ACTION1");
intent1.putExtra("kz", Period);
sendBroadcast(intent1);
text3.setText(""+Period);
Toast.makeText(getApplicationContext(), "PeriodSent",Toast.LENGTH_SHORT).show();
}
#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;
}
}
my service class
public class Myservice21 extends Service {
int BitCount=0;
int Rc=0;
int Period=500;
Intent intent = new Intent();
MyReceiver21 myReceiver21;
public Handler handler1 = new Handler();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
intent.setAction(MY_ACTION);
myReceiver21 = new MyReceiver21();
IntentFilter intentFilter1 = new IntentFilter();
intentFilter1.addAction(com.experiment.Test.MainActivity.MY_ACTION1);
registerReceiver(myReceiver21, intentFilter1);
Intent intent1 = new Intent(Myservice21.this,MainActivity.class);
startService(intent1);
handler1.post(runnable1);
}
public class MyReceiver21 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
int data = intent.getIntExtra("kz", 0);
Period=data;
Toast.makeText(getApplicationContext(), "PeriodRceived21",Toast.LENGTH_SHORT).show();
}
}
public void onStart(Intent intent,int StartId)
{
Rc=0;
}
public void onDestroy()
{
}
}
can any one help me to register the receiver in manifest. Thanks in advance
You don't have to add the intent filter for your own broadcasts. Just register the service for that broadcasts with registerReceiver() when the service is started.
Note, that you have to start the service manually when your App starts, for instance in the MainActivity.onCreate():
startService(new Intent(this, Myservice21.class));
When the MainActivity has been created, it will start the service, which itself registers for BroadcastIntents and starts listening for them. This should work.
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));
}
}
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...