Update UI from static BroadcastReceiver - android

I've checked this example of how to handle network connectivity changes:
Android Check Internet Connection and found a very nice piece of code of how to handle this changes:
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context); //some internal class to determinate which type is connected
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
To make this thing work I need to declare this BroadcastReceiver inside my manifest file:
<application ...>
...
<receiver
android:name="net.viralpatel.network.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
...
</application>
Now I want to update UI, when wifi/mobile data is connected.
I can either make the NetworkChangeReceiver class inner static or external. But what I need is that I can work with my MainActivity UI from public void onReceive. How I can do this?

The answer was easy. I don't need to register my broadcast in order to get broadcast about connectivity change:
private BroadcastReceiver networkConnectivityReciever = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (dialog != null) {
if(currentNetworkInfo.isConnected()){
dialog.dismiss();
webView.reload();
}else{
dialog.show(((MainActivity) context).getSupportFragmentManager(), "");
}
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(networkConnectivityReciever,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(networkConnectivityReciever);
}
And only thing I need in manifest is this:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Related

BroadcastReceiver doesn't work?

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);

How to get the activity which called the BroadcastReceiver?

I have a BroadcastReceiver which checks for NetworkChange, whether connected to Internet or not.
So in my application when the network is disconnected or connected, I want to know which activity has called the BroadcastReceiver, so that I can go back to previous activity after showing an alert informing about the network.
My code,
public class NetworkChangeReceiver extends BroadcastReceiver {
private android.widget.Toast Toast;
#Override
public void onReceive(final Context context, final Intent intent) {
try {
boolean isVisible = MyApplication.isActivityVisible();
Context appContext = context.getApplicationContext();
if (isVisible == true) {
if (checkInternet(context)) {
/*Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);*/
Toast.makeText(context, "Network Available Do operations", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(context, NoNetworkAlert.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Toast.makeText(context, "Network NOT Available Do operations", Toast.LENGTH_LONG).show();
}
.........
......
Here in the above code, when Internet is reconnected,
if (checkInternet(context))I just want to get to the activity which triggered this.
I assume the current activity on the top is the one which triggers the NetworkChangeListener. If so you can use below code snippet,
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
which will give the current Activity on the top.
Do something like this in your activity
BroadcastReceiver br=new NetworkChangeReceiver ();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(br, filter);
And in your menifest
<receiver
android:name=".NetworkChangeReceiver "
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
I have a BroadcastReceiver which checks for NetworkChange, whether connected to Internet or not.
So in my application when the network is disconnected or connected, I want to know which activity has called the BroadcastReceiver, so that I can go back to previous activity after showing an alert informing about the network.
To get the current Activity in Broadcast receiver use the ActivityManager in Broadcast receiver to get the Activity without instance
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.i("ActivityManager ", "ActivityManager" + cn.toString());
To get Activity in the preferred Activity with instance better use Getter and Setter.
MyApplication.Java:
public class MyApplication extends Application {
private Activity mCurrentActivity = null;
// Gloabl declaration of variable to use in whole app
public static boolean activityVisible; // Variable that will check the
// current activity state
public static boolean isActivityVisible() {
return activityVisible; // return true or false
}
public static void activityResumed() {
activityVisible = true;// this will set true when activity resumed
}
public static void activityPaused() {
activityVisible = false;// this will set false when activity paused
}
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
MainActivity.Java:
public class MainActivity extends AppCompatActivity {
private static TextView internetStatus;
protected MyApplication mMyApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMyApp = (MyApplication) this.getApplicationContext();
internetStatus = (TextView) findViewById(R.id.internet_status);
// At activity startup we manually check the internet status and change
// the text status
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
changeTextStatus(true);
} else {
changeTextStatus(false);
}
}
// Method to change the text status
public void changeTextStatus(boolean isConnected) {
// Change status according to boolean value
if (isConnected) {
internetStatus.setText("Internet Connected.");
internetStatus.setTextColor(Color.parseColor("#00ff00"));
} else {
internetStatus.setText("Internet Disconnected.");
internetStatus.setTextColor(Color.parseColor("#ff0000"));
}
}
#Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();// On Pause notify the Application
clearReferences();
}
#Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();// On Resume notify the Application
mMyApp.setCurrentActivity(this);
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences() {
Activity currActivity = mMyApp.getCurrentActivity();
Log.e("Activity", "Activity" + currActivity);
if (this.equals(currActivity))
mMyApp.setCurrentActivity(null);
}
}
InternetConnector_Receiver.Java:
public class InternetConnector_Receiver extends BroadcastReceiver {
public InternetConnector_Receiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
try {
boolean isVisible = MyApplication.isActivityVisible();
Log.i("Activity is Visible ", "Is activity visible : " + isVisible);
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.i("ActivityManager", "Activity Name:" + cn.toString());
// If it is visible then trigger the task else do nothing
if (isVisible == true) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
// Check internet connection and accrding to state change the
// text of activity by calling method
if (networkInfo != null && networkInfo.isConnected()) {
new MainActivity().changeTextStatus(true);
} else {
new MainActivity().changeTextStatus(false);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Manifest Permission:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.internetconnection_demo.MyApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>
<!-- Broadcast receiver declaration in manifest file and make sure to enable it -->
<receiver
android:name="com.internetconnection_demo.InternetConnector_Receiver"
android:enabled="true" >
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
</application>

Twilio Device defined in sticky Service is not starting activity if app closed

I need to be able to receive incoming Twilio calls regardless of whether the app is currently running or not.
Once the user has started the app and logged into our server, I start the service shown below.
The Service is started sticky, and at no point is stopService or stopSelf etc ever called, so the service should still be running after the App is closed.
When the App is running, IncomingCallActivity starts fine in response to a Twilio call.
If the App is in the background, IncomingCallActivity still starts fine in response to a Twilio call.
If however the App is closed, IncomingCallActivity no longer starts in response to a Twilio call.
Why isn't IncomingCallActivity started if the App has been closed??
public class CallService extends Service implements Twilio.InitListener, DeviceListener, ConnectionListener {
private Device mDevice;
private Connection mConnection;
#Override
public void onCreate() {
super.onCreate();
registerBroadcastReceiver();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Initialize the Twilio SDK if required
if (!Twilio.isInitialized()) {
Twilio.initialize(getApplicationContext(), this);
} else {
getCapabilityToken("CallService", getUser());
}
...
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
// Unregister broadcast receiver
final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
#Override
public void onInitialized() {
getCapabilityToken("CallService", getUser());
}
#Override
public void onError(Exception e) {
}
private void getCapabilityToken(String string, User user) {
// Request the capability token from the server.
...
}
protected void setCapabilityToken() {
// Create device using the capability token
mDevice = Twilio.createDevice(getUser().capabilityToken, this);
// Set pending intent for Twilio device
Intent intent = new Intent(this, IncomingCallActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mDevice.setIncomingIntent(pendingIntent);
// Broadcast that CallService is ready, to any registered receivers
Intent broadcastIntent = new Intent(App.ACTION__TWILIO_SERVICE_READY);
LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
}
public void connect() {
mConnection = mDevice.connect(null /* parameters */, null /* ConnectionListener */);
if (mConnection == null) {
...
} else {
...
}
}
private void answerCall(Device device, Connection connection) {
if (mConnection != null) {
mConnection.disconnect();
}
mConnection = connection;
mConnection.accept();
}
/**
* BroadcastReceiver
*/
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case App.ACTION__CAPABILITY_TOKEN_OBTAINED:
setCapabilityToken();
break;
case App.ACTION__CONNECT:
connect();
break;
}
}
};
#Override
public void onStartListening(Device device) {
}
#Override
public void onStopListening(Device device) {
}
#Override
public void onStopListening(Device device, int i, String s) {
}
#Override
public boolean receivePresenceEvents(Device device) {
return false;
}
#Override
public void onPresenceChanged(Device device, PresenceEvent presenceEvent) {
}
#Override
public void onConnecting(Connection connection) {
}
#Override
public void onConnected(Connection connection) {
}
#Override
public void onDisconnected(Connection connection) {
}
#Override
public void onDisconnected(Connection connection, int i, String s) {
}
}
Edit:
To clarify how I've declared my services etc, here is my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="au.com.encall.encall"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".IncomingCallActivity"
android:screenOrientation="portrait"/>
<service android:name=".services.CallService"/>
<service android:name=".services.DownloadService"/>
<service
android:name="com.twilio.client.TwilioClientService"
android:exported="false"
android:stopWithTask="false" />
<meta-data
... />
...
</application>
</manifest>
if you are using twilio demo than You need to service in Androidmenifest
<service android:name="com.twilio.client.TwilioClientService" android:exported="false" android:stopWithTask="true"/>
its working for me.
twilio provide their own service. so you need to just declare it on menifest.so does't need to create new service.
jusr remove this service and put it on android menifest.it will automatically start after app close.
Its Work for me no need extra service
<service android:name="com.twilio.client.TwilioClientService" android:exported="false" android:stopWithTask="false"/>
But How can we Handle if token is Expired ? At that time IncomingCallActivity no longer starts

BroadcastReceiver not working as expected on Android

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.

Why my BroadcastReceiver doesn't work?

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);}

Categories

Resources