Empty intent filter gives me problems - android

I have an application that needs to start and stop activities.
So far we are OK with starting the Activity.
The problem comes when I try to stop the Activity.
This is the AlarmManager that broadcasts the intent to close the activity:
Intent ftue = new Intent(ctxt, VideoActivty.class);
ftue.putExtra("finish", true);
PendingIntent pftue = PendingIntent.getBroadcast(ctxt, 0, ftue, 0);
Calendar calSet4 = Calendar.getInstance();
calSet4.set(Calendar.MONTH, c.get(Calendar.MONTH));
calSet4.set(Calendar.YEAR, c.get(Calendar.YEAR));
calSet4.set(Calendar.DAY_OF_WEEK, 3);
calSet4.set(Calendar.HOUR_OF_DAY, hftue);
calSet4.set(Calendar.MINUTE, mftue);
calSet4.set(Calendar.SECOND, 0);
calSet4.set(Calendar.MILLISECOND, 0);
//calSet.setTimeZone(TimeZone.getTimeZone("UTC"));
mgr.setRepeating(AlarmManager.RTC_WAKEUP, calSet4.getTimeInMillis(),
7 * 24 * 60 * 60 * 1000, pftue);
And in my Activty I have implemented a BroadcastReceiver that should shut down the Activty.
#Override
public void onResume() {
super.onResume();
IntentFilter f=new IntentFilter();
registerReceiver(receiver, f);
}
#Override
public void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
BroadcastReceiver receiver=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.e("","intento ricevuto");
if(intent.getBooleanExtra("finish",false))finish();
}
};
My application does not receive the broadcasted intents, and I understand that is because the intent filter is empty.
Please how should I implement the intent filter to receive the broadcasts?
Thanks!

Why your intent filter is blank? You can write intent action as any string (BUT that should not exists in SDK Actions)
// like
IntentFilter f = new IntentFilter("com.android.INTENT_ACTION_TO_CLOSE_ACTIVITY");
And use
Intent mIntent = new Intent("com.android.INTENT_ACTION_TO_CLOSE_ACTIVITY");
sendBroadcast(mIntent);
at the condition, when you want to close the Activity.

Related

How do I use Intent for working perfekt in Android Studio

I try to get a variable on my Android App from 1 Activite to an other.
Ther for I using Intent but I have a Problem with it and I can´t find any answer for it. When I lauch the programm it say´s me every time 90 no matter waht I do.
MainActivitie
`public class MainActivity extends AppCompatActivity {
public static final String EXTRA_NUMBER = "com.example.akkuapp.EXTRA_NUMBER";
int level;
public TextView battery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
battery = (TextView) this.findViewById(R.id.textakku);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
AlarmManager alarmManager = (AlarmManager) MainActivity.this.getSystemService(ALARM_SERVICE);
Intent startServiceIntent = new Intent(MainActivity.this, Hintergrundservice.class);
PendingIntent startServicePendingIntent = PendingIntent.getService(MainActivity.this, 0, startServiceIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
long time = calendar.getTimeInMillis();
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 5, startServicePendingIntent);
}
public final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#SuppressLint("SetTextI18n")
#Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
battery.setText(String.valueOf(level) + '%');
intent.putExtra(EXTRA_NUMBER, level);
}
};
Backgroundservice
`
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
level = intent.getIntExtra(MainActivity.EXTRA_NUMBER,90);
Toast.makeText(getApplicationContext(), String.valueOf(level), Toast.LENGTH_LONG).show();
Log.d("Hintergrundprozess", String.valueOf(level));
return flags;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
Pictur MainActivity
Pictur Hintergrundprozess (Backgroundservice)
Thank you for your Help
There are many problems here. You are using startActivity() but passing an Intent for a Service (HintergrundService). To start a Service you need to call startService().
Also, getIntentOld() is a deprecated method of Intent and is probably not what you want. You already have the Intent as it is passed into onStartCommand(). Just use intent.getIntExtra():
intent.getIntExtra(MainActivity.EXTRA_NUMBER, 90);
EDIT: Add more data after seeing more code
You have used AlarmManager to schedule the triggering of an Intent to start your Service. In that Intent you have not put any extras. This is the reason that your Service doesn't get the "extra".
When your BroadcastReceiver is triggered and onReceive() is called, you extract the battery level from the incoming Intent and add an "extra" with that value back to the same incoming Intent. The value doesn't get magically copied into the Intent that you passed to AlarmManager. You should really find some tutorials and examples and learn more about how all this works.
In general, if your Service wants to get the battery level, it can just do this:
IntentFilter ifilter =
new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
You don't need to actually register a BroadcastReceiver. The battery changed Intent is a "sticky" Intent, which means that the last one broadcast is held by the Android framework and you can always ask for the last one that was broadcast.
See https://developer.android.com/training/monitoring-device-state/battery-monitoring for more information about monitoring the battery state.

Stop Service from PendingIntent after Notifcation is opened

I want the service to perform a stopForeground and a stopSelf after the notification is clicked followed by the running of pendingIntent.
I have tried using a BroadcastReceiver which is never called as I checked during debugging. I have added it to manifest as well.
Intent intentHide = new Intent(this, StopServiceReceiver.class);
PendingIntent hide = PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(), intentHide, PendingIntent.FLAG_CANCEL_CURRENT);
Added it to the builder
builder.setContentIntent(hide);
And the Broadcast Rec is done separately -
public class StopServiceReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 333;
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, TimerService.class);
context.stopService(service);
}
}
Manifest -
<receiver
android:name=".StopServiceReceiver"
android:enabled="true"
android:process=":remote" />
This is not working. The notification and the service both are alive.
Questions - Should I use addContent instead of setContentIntent ? If yes, then what should the parameters be ?
Is there anything I went wrong with? What could possibly be wrong with such kind of implementation? Thank you.
I had the same problem in the notification.
This code is working perfectly.
void creatnotifiaction()
{
public static final String STOP = "com.example.android";
public static final int REQUEST_CODE = 333;
filter = new IntentFilter();
filter.addAction(STOP);
Intent intentHide = new Intent(STOP);
PendingIntent hide = PendingIntent.getBroadcast(this,REQUEST_CODE,intentHide,PendingIntent.FLAG_CANCEL_CURRENT);
registerReceiver(broadcastReceiver, filter);
}
There no need to separate broadcast receiver use in same class.
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#SuppressLint("ResourceAsColor")
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d("notification", "Received intent with action " + action);
switch (action) {
case STOP:
//your code to stop notifications or service.
break;
}
});
Let me know if that work for you.
Thanks...Happy coding.

Why does my BroadcastReceiver continually receive the same broadcast?

My Application class creates an alarm and receives the system broadcast once per day. In the onReceive() it sends an application broadcast that is received by my MainActivity class.
The problem is that the onReceive() in the MainActivity class is continually called whenever an orientation change occurs. I understand why onResume() is called across orientation changes, but I don't understand why onReceive() is also getting called.
I assumed that because the Application class only sends out the local broadcast once, my
MainActivity would only receive the broadcast once.
Does anyone know why onReceive() in my MainActivity class is continually called?
Here is the onCreate() in my Application class:
#Override
public void onCreate()
{
super.onCreate();
// register a receiver in the Application class to receive a broadcast
// at the start of each day
IntentFilter intentFilter = new IntentFilter(START_OF_DAY_ACTION);
startOfDayReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(TaskReminderApp.this,
"Application: startofday broadcast received",
Toast.LENGTH_LONG).show();
// send a broadcast to MainActivity
Intent i = new Intent();
i.setAction(TEST_ACTION);
context.sendBroadcast(i);
}
};
this.registerReceiver(startOfDayReceiver, intentFilter);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 19); // for testing purposes
calendar.set(Calendar.MINUTE, 51); // for testing purposes
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Intent intent = new Intent(START_OF_DAY_ACTION);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
}
Here is onResume() and onPause() in MainActivity:
#Override
protected void onResume()
{
super.onResume();
IntentFilter intentFilter = new IntentFilter(TEST_ACTION);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
// This is getting called on every orientation change
// and every time the activity resumes.
Toast.makeText(MainActivity.this,
"MainActivity: broadcast received",
Toast.LENGTH_LONG).show();
}
};
this.registerReceiver(receiver, intentFilter);
}
#Override
protected void onPause()
{
super.onPause();
// I thought this might be the problem, but it makes no
// difference if I comment it out.
this.unregisterReceiver(receiver);
}
Because you need to create the Receiver in your onCreate(). Else it will be created again and again and again..
The registering is just fine, same as the unregistering.
I solved this by sending a local application broadcast instead of a system broadcast.
In my class that extends Application, I send a local broadcast like this:
Intent i = new Intent(TEST_ACTION);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
Then in my MainActivity class, I define a BroadcastReceiver like this:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(MainActivity.this,
"MainActivity: broadcast received",
Toast.LENGTH_LONG).show();
}
};
I register the receiver in MainActivity's onCreate():
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(TEST_ACTION));
Then I unregister the receiver in MainActivity's onDestroy():
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
It works well now and I only receive a single broadcast.

screen off does not Recive Broadcast

Screen Off ,Broadcast Receiver does not call some time it will execute but mostly wifi state change event is called .i have also set up the priority of screen off but does not call or some time call .can you please tell .when my screen off i want to execute first then other wifi state changed will called
BroadcastReceiver wReceiver = new ScreenReciver();
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.setPriority(1);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.setPriority(1000);
registerReceiver(wReceiver, filter);
}
#Override
protected void onPause() {
unregisterReceiver(wReceiver);
super.onPause();
}
public class ScreenReciver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
switch (wifiState) {
case WifiManager.WIFI_STATE_DISABLED:
Intent myintent = new Intent(context, TimerClockActivity.class);
myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myintent);
wifiStateText = "WIFI_STATE_DISABLED";
break;
default:
break;
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Intent myintent = new Intent(context, TimerClockActivity.class);
myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myintent);
}
}
}
You are calling unregisterReceiver(wReceiver); in onPause(). This means that every time that the Activity goes into the background (including when the screen turns off), your Activity is unregistered for that broadcast.
onPause() is likely getting called before your Activity gets a chance to receive the Broadcast.
Perhaps you want to place unregisterReceiver(wReceiver); in onDestroy() instead?

addAction() & Service calling Dilemma

I'm stuck here at my previous struggle >> Prev. Struggle!
Raanan there helped! me a lot but then he I think went away as timing zone is different , now I'm stuck with my service code that I'm using to call my BroadcastReceiver() that is in the activity! and also I'm not getting with what parameter I should load the filter.addAction(action); in place of action??
Kinldy guide me!
CODE in the Server:
Toast.makeText(Server.this, hr +" , " +min, Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, andRHOME.class);
//intent.putExtra("sendMessage","1");
sendBroadcast(intent);
and CODE IN THE ACITIVITY(Broadcast Receiver)
private BroadcastReceiver ReceivefrmSERVICE = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "IN DA BroadCASTER",
Toast.LENGTH_LONG).show();
sendMessage("1");
}
};
IntentFilter filter = new IntentFilter();
You need to add these line to regiester your receiver for some action for example define a Global variable like this:
public static String NOTIFCATION_BROADCAST_ACTION = "com.your_packagename.UPDATE_NOTIFICATION_INTENT";
then register the action like this in your activity onCreate() Method.
IntentFilter filter = new IntentFilter();
filter.addAction(Global.NOTIFCATION_BROADCAST_ACTION);
registerReceiver(ReceivefrmSERVICE, filter);
Then send the broadcast from your service like this
Intent broadcast = new Intent();
broadcast.setAction(Global.NOTIFCATION_BROADCAST_ACTION);
sendBroadcast(broadcast);
Then in your broadcast Receiver filter this action like this
private BroadcastReceiver ReceivefrmSERVICE = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Global.NOTIFCATION_BROADCAST_ACTION)) {
//Do your stuff here :)
}
}
};

Categories

Resources