Reputation: 41
How do I use Intent.ACTION_TIME_TICK correctly? I would like to create a receiver which checks the battery-level every minute.
I use a Broadcast-receiver class witch is first started from main-Activity. Starting the broadcast receiver is not the problem. When the app is open everything works fine. However, if the app ends, I will no longer receive broadcast information.
Now to my problem: how can I continue to receive information after completing the app?
My Sourcecode.
Start the Broadcast:
public class Main extends AppCompatActivity {
[...]
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String app = getResources().getString(R.string.app_name);
[...]
btnStart.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
registerReceiver(receiver, new IntentFilter(Intent.ACTION_TIME_TICK));
Log.d(app + ".Main", "register receiver with '" + Intent.ACTION_TIME_TICK + "'");
}
});
}
}
Receive information in Receiver.class:
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
BatteryManager bm = (BatteryManager)context.getSystemService(context.BATTERY_SERVICE);
int akku = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
Calendar calendar = Calendar.getInstance();
int minute = calendar.get(Calendar.MINUTE);
if(action.equals(Intent.ACTION_TIME_TICK))
{
Log.d(app + ".Receiver", "Receiver detected '" + action + "'");
if(minute%5 == 0) {
startNotification(akku);
}
}
}
}
Manifest:
<receiver android:name=".Receiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_TIME_TICK"></action>
</intent-filter>
</receiver>
Upvotes: 4
Views: 5758
Reputation: 1
You can use the service for running in the background even after your app is closed and will notify the required.
Upvotes: 0
Reputation: 1
you need to register your broadcaster subclass either on subclassed applicant onCreate() {...} or in your activity..
Upvotes: 0
Reputation: 31
You need to registre the receiver in Service, than it will work on background. I dont know it on 100%, but I think that TIME_TICK doesnt work if you define it in manifest, you must register it in class.
Upvotes: 3