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 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:
BROADCAST RECEIVER:
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.
Finally I unregister the screen on/off in the onDestroy() of my service:
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:
In other words, you've created a custom
broadcast receiver class
, but you haven't used it.And also please check this.
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
Main Activity Class
public class MainActivity extends Activity {
}
My broadcast receiver
public class Broadcast extends BroadcastReceiver {
}
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:
} this is the manifest: