sms notification- not working - android

I'm stuck with something that seems easy. I want to create a simple app that contains of two buttons: one to start a service and a second one to stop it. I've created my NotifyService class:
public class NotifyService extends Service {
public NotifyService() {
}
private static final String SMS_RECEIVED="android.provider.Telephony.SMS_RECEIVED";
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
displayNotification(intent);
}
};
private void displayNotification(Intent intent)
{
if(intent.getAction().equals(SMS_RECEIVED)) {
int NOTIFICATION=R.string.local_service_started;
//notification creating
Notification.Builder notificationBuilder = new Notification.Builder(this)
.setContentText("Otrzymano smsa!")
.setContentTitle("SMS!")
.setSmallIcon(android.R.drawable.btn_plus);
Notification note = notificationBuilder.build();
//getting system service
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//displaying notification
notificationManager.notify(NOTIFICATION, note);
}
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
#Override
public void onCreate() {
super.onCreate();
registerReceiver(broadcastReceiver,new IntentFilter(SMS_RECEIVED));
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
And here's the code for my MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startServiceBtn(View view)
{
Intent intent = new Intent(this,NotifyService.class);
startService(intent);
}
public void stopServiceBtn(View view)
{
Intent intent = new Intent(this,NotifyService.class);
stopService(intent);
}
And the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pablo.myapplication" >
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<service
android:name=".NotifyService"
android:enabled="true"
android:exported="true" >
</service>
</application>
Unfortunately, every time I'm simulating a sending of an sms through Android Device Monitor, it doesn't work, it shows me the default system notification (that by the way is shown even without the permission in manifest- ist that right behavior?)
EDIT:
In Android Device Monitor it still keeps showin Permission Denial: ... requires android.permission.RECEIVE_SMS due to sender.com android.... Yet, I've added this into intent filter, then I don't know why it's happening.

The answer to this question was related to some other matters with permissions that I had last times and it's connected with new permission politics with Marshmallow. More info here.
So the problem can be solver by switching to lower sdk version or calling appriopriate methods (look into above link) in runtime.

Related

Broadcast receiver is not working - why so?

I'm studying Android.
I try to implement a Custom static Broadcast Receiver but it is not working.
I search for some issue from Google but I can't find something to solve this.
I work on Android 7.0 Min Level 24 Target Level 28
In fact, MyStaticReceiver isn't launching when I start the Activity (no log)
MyDynamicReceiver work perfectly
Do you have a solution?
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.receiver">
<application
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="test.receiver.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MyStaticReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="#string/StaticAction" />
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity.java :
public class MainActivity extends Activity {
public final static boolean Debug = true;
public final static String TAG = "TagDebug";
private MyDynamicReceiver dynamicReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ComponentName receiver = new ComponentName(this, MyStaticReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
#Override
protected void onResume() {
super.onResume();
if (Debug) Log.i(TAG, "MainActivity:onResume");
configureDynamicReceiver();
}
#Override
protected void onDestroy(){
super.onDestroy();
if (Debug) Log.i(TAG, "MainActivity:onDestroy");
unregisterReceiver(dynamicReceiver);
}
public void onClickButton(View v) {
if (Debug) Log.i(TAG, "MainActivity:onClickButton");
Intent staticIntent = new Intent();
staticIntent.setAction(getString(R.string.StaticAction));
sendBroadcast(staticIntent);
Intent dynamicIntent = new Intent();
dynamicIntent.setAction(getString(R.string.DynamicAction));
sendBroadcast(dynamicIntent);
}
public void configureDynamicReceiver() {
if( dynamicReceiver == null ) {
dynamicReceiver = new MyDynamicReceiver();
}
IntentFilter filter = new IntentFilter(getString(R.string.DynamicAction));
registerReceiver(dynamicReceiver, filter);
}
}
MyStaticReceiver.java (MyDynamicReceiver is the same ...)
public class MyStaticReceiver extends BroadcastReceiver {
public final static boolean Debug = true;
public final static String TAG = "TagDebug";
public MyStaticReceiver() {
if (Debug) Log.i(TAG, "MyStaticReceiver");
}
#Override
public void onReceive(Context context, Intent intent) {
if (Debug) Log.i(TAG, "MyStaticReceiver:onReceive");
}
}
You are actually sending an implicit broadcast, therefore the receiver declared in the manifest will not work.
If your app targets Android 8.0 (API level 26) or higher, you cannot use the manifest
to declare a receiver for most implicit broadcasts (broadcasts that
don't target your app specifically). You can still use a
context-registered receiver when the user is actively using your app. Link
You don't face any issue with MyDynamicReceiver because it is context-registered receiver.
But to make it work for MyStaticReceiver, you can try sending an explicit broadcast by passing the component name in the constructor of the Intent.
Intent staticIntent = new Intent(this, MyStaticReceiver.class);
staticIntent.setAction(getString(R.string.StaticAction));
sendBroadcast(staticIntent);

Getting Android apk to run after installing (reboot)?

Hello I'm trying to get my Android application (it has no UI, its just supposed to be a background service) to run when it's installed or at least when the device is rebooted. Here's my work so far, anyone have any ideas why it won't start when install the apk and reboot the device?
Android Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gitlab.project" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<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_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="#string/app_name" >
<activity
android:name="gitlab.project.MainActivity"
android:label="#string/app_name"
android:theme = "#android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</activity>
<receiver
android:name="gitlab.project.AutoStart"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name="gitlab.project.AlphaService"
android:enabled="true"
android:exported="true" />
</application>
</manifest>
MainActivity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, AlphaService.class);
this.startService(intent);
}
}
AlphaService:
public class AlphaService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Profiler profiler;
private AlphaApiClient alphaApiClient;
private GoogleApiClient googleApiClient;
private int batteryHealth;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
batteryHealth = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 2);
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
googleApiClient.connect();
return Service.START_STICKY;
}
#Override
public void onConnected(Bundle connectionHint) {
ProcService procService = new DefaultProcService();
SystemInformationService systemInformationService = new SystemInformationService(googleApiClient, getContentResolver());
profiler = new Profiler(procService, systemInformationService);
alphaApiClient = new AlphaApiClient(getString(R.string.USERNAME), getString(R.string.PASSWORD));
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
Log.d("Alpha service", "Profiling system info...");
AndroidSystem androidSystem = profiler.profile(batteryHealth);
String url = getString(R.string.API_URL);
alphaApiClient.doPostRequest(androidSystem, url);
}
});
thread.start();
//Stop service once it finishes its task
stopSelf();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onDestroy() {
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.set(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (4000 * 60 * 60),
PendingIntent.getService(this, 0, new Intent(this, AlphaService.class), 0)
);
}
}
AutoStart (Broadcast Receiver):
public class AutoStart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
context.startService(new Intent(context, AlphaService.class));
}
}
Any ideas why my background service won't run? I'm able to get it to run using adb, but not when trying to install manually from the phone/tablet. Any help is greatly appreciated.
The app won't run any services or broadcast receivers unless it's in started state. It's in started state after it's been run from launcher or via ADB.
1) Make an activity which will a) start your service and b) disable itself (How to enable and disable a component?).
2) Make an on boot receiver (Android BroadcastReceiver on startup - keep running when Activity is in Background).
Your on boot receiver is already starting the service, it does not need to start the activity. The activity only needs to be launched once after install. Here's the correct setup.
AndroidManifest.xml
<activity
android:name="gitlab.project.MainActivity"
android:theme = "#android:style/Theme.NoDisplay">
<intent-filter>
<!-- Activity needs to show up in launcher. -->
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="gitlab.project.AutoStart"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
AutoStart.java
public class AutoStart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) {
context.startService(new Intent(context, AlphaService.class));
}
}
}
I think the problem is in your AutoStart class:
Intent i = new Intent(context, MainActivity.class);
Your packaging the intent with your MainActivity. Try changing it to AlphaService.

Starting Android application at boot completion: is my solution overly complicated?

I have an application that I would like to have automatically start following boot completion. The following code seems overly complicated and I get erratic application starts when swiping to a neighbouring workspace.
What am I missing here? I have an activity class, a service class, as well as a broadcast receiver. Below is my code (in that order) followed by the manifest.
public class BlueDoor extends Activity implements OnClickListener{
Button btnExit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
btnExit = (Button) this.findViewById(R.id.ExitButton);
btnExit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ExitButton:
System.exit(0);
break;
}
}
}
service.class
public class BlueDoorStartService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callIntent.setClass(this, BlueDoor.class);
startActivity(callIntent);
// do something when the service is created
}
}
broadcast receiver
public class StartBlueDoorAtBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, BlueDoorStartService.class);
context.startService(serviceIntent);
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluedoor"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver
android:name=".StartBlueDoorAtBootReceiver"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".BlueDoorStartService" >
</service>
<activity
android:name=".BlueDoor"
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>
UPDATE Solution(s), 10/22/2015:
Changing the service to:
public class BlueDoorStartService extends Service {
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}
and the receiver to:
public class StartBlueDoorAtBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Start Service On Boot Start Up
Intent serviceIntent = new Intent(context, BlueDoorStartService.class);
context.startService(serviceIntent);
//Start App On Boot Start Up
Intent App = new Intent(context, BlueDoor.class);
App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(App);
}
}
resulted in a working configuration using a service w/no misbehaving. However deleting the service all together and modifying the receiver thus:
public class StartBlueDoorAtBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent App = new Intent(context, BlueDoor.class);
App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(App);
}
}
also resulted in a functional as well as a more concise configuration that starts the application following boot completion.
Your BroadcastReceiver calls
context.startService(serviceIntent)
so the service will be created if it doesn't exist yet (which will be the case shortly after booting) and thus start the activity from its onCreate() method. So the app works, to a certain extent.
BUT when you call startService(), the system always calls the service's onStartCommand() method. You did not override that method, so the system uses the standard implementation from class android.app.Service.
As you can read on grepcode.com, the method will return a value like START_STICKY by default. This tells the system to keep the service alive until it is explicitly stopped.
In your case, I suppose the system reacted to the swiping by temporarily killing and then reanimating (= creating) the service, which in turn started your activity.
Some information on the service lifecycle can be found here.
What you can do:
Override onStartCommand() to start the activity from there instead of from onCreate(). Then use stopSelf(int) like described here
One last thing: when exiting from the activity, don't use System.exit(0) but call finish() instead, see this SO answer for "why".

Why do dynamically register broadcast receiver didn't work after reboot

I have a onBootCompleted broadcast receiver registered in the manifest.
It runs starts MyService. My service in the onCreate registers 3 more broadcast receivers dynamically.
The 3 new receivers filter on the following intent actions
LOCALE_CHANGED,
TIMEZONE_CHANGED and
CONNECTIVITY_CHANGED.
These works correctly when I run the application from Eclipse but, after I reboot the device and my service starts up none of receivers work.
I have a work around implementation but, I would like to know why this is happening?
Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".receiver.BootCompletedReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<service
android:name=".MyService"
android:enabled="true"
android:exported="false"
android:stopWithTask="false" >
</service>
Service:
public class MyService()
{
LocationTimeZoneC‌​hangedReceiver mLocationTimeZoneC‌​hangedReceiver = new LocationTimeZoneC‌​hangedReceiver()
NetworkChangedReceiver mNetworkChangedReceiver = new NetworkChangedReceiver()
public void onCreate()
{
registerReceiver(mLocationTimeZoneChangedReceiver, new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
registerReceiver(mLocationTimeZoneC‌​hangedReceiver, new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED));
registerReceiver(mNetworkChangedReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
BootCompletedReceiver:
public class BootCompletedReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent){}
}
MyApplication:
public class MyApplication extends Application
{
ServiceConnection mServiceConnection = new ServiceConnection() { anonymous class...}
public void onCreate()
{
bindService(new Intent(this, MyService.class), mServiceConnection,Context.BIND_AUTO_CREATE);
}
}
Edited:
Edited code for Plinio.Santos.
It's a big app with many moving parts so at best I can post small code snippets.
Following are the steps I am following for testing:
Push app via Eclipse,
test that network change receiver is working
leave wifi off
Now restart the device
wait for the process to start and turn on wifi.
I believe that the service is not started or bound due errors. Unfortunately I can not say it for sure without all binding/starting code.
Anyway, you can see bellow a code that worked fine after I rebooted (the app started, registered the receiver and is receiving the CONNECTIVITY_CHANGED broadcast.
AndroidManifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".TestReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".TestService"
android:exported="true" />
Receiver class:
public class TestReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Toast.makeText(context, "Intent.ACTION_BOOT_COMPLETED receiverd !", Toast.LENGTH_SHORT).show();
context.startService(new Intent(context, TestService.class));
}
}
}
Service class:
public class TestService extends Service {
private BroadcastReceiver mConnectivityChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Toast.makeText(context, "ConnectivityManager.CONNECTIVITY_ACTION receiverd !", Toast.LENGTH_SHORT).show();
}
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
registerReceiver(mConnectivityChangedReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}

How to start Alarm Manager on Device Reboot

I've have a simple app to schedule a notification 5 minutes after a button is pressed. It works fine for me. But if I restart the phone within that 5 minutes I don't get the notification. I have done a research on Alarm Manager and Scheduling Notifications on device reboots. I have a basic idea but I really don't know how to implement it into my project. I have 4 classes in my project. They are:
MainActivity
NotificationUtil
NotificationPublisher
NotificationView
This is the my NotificationUtil class:
public class NotificationUtil
{
public static void createNotification(Context context,Class<?> cls, String title, String content)
{
Intent intent = new Intent(context,cls);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
sendNotification(getNotification(pendingIntent,context,title,content),context);
}
private static void sendNotification(Notification notification,Context context)
{
Intent notificationIntent = new Intent(context, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID,1);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION,notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5*60 * 1000,pendingIntent);
}
private static Notification getNotification(PendingIntent pendingIntent, Context context, String title, String content)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"ChannelID");
builder.setSmallIcon(R.drawable.notification_bell);
builder.setContentTitle(title);
builder.setContentText("You have a Notification");
builder.setSubText("Tap To View");
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(content));
builder.setContentIntent(pendingIntent);
return builder.build();
}
}
This is my NotificationPublisher class:
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
#Override
public void onReceive(final Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int notificationId = intent.getIntExtra(NOTIFICATION_ID, 1);
notificationManager.notify(notificationId, notification);
}
}
This is how I call the NotificationUtil class on button click in the MainActivity:
public class MainActivity extends AppCompatActivity {
private Button button;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.notification);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotificationUtil.createNotification(MainActivity.this,NotificationView.class,"Notification","You have a new Task");
}
});
}
}
This is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.notificationtest">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
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"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NotificationView"
android:parentActivityName=".MainActivity"/>
<receiver android:name=".NotificationPublisher">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name=".DeviceBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
I have created a new DeviceBootReceiver class:
public class DeviceBootReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
}
}
}
But I'm not sure what to put in the onReceive function. I tried putting this in the onReceive function
Intent pushIntent = new Intent(context, NotificationPublisher.class);
context.startService(pushIntent);
Works normal, but if I reboot my phone, after 5 minutes I get a message "The Application has stopped working"
I have a basic idea after having gone through these tutorials but I don't know how to implement them into my project
https://www.stacktips.com/tutorials/android/repeat-alarm-example-in-android
https://droidmentor.com/schedule-notifications-using-alarmmanager/
What I need is, to get the notification even after my phone is rebooted. If any one out there who could help me to achieve this, I would be grateful.
you need to create a BroadcastReceiver in order to be able to listen REBOOT event that is delivered by OS and then you can start your alarm manager there again
Well here is a complete example of an AutoStart Application.
Give permission of RECEIVE_BOOT_COMPLETED in manifest file, and register your broadcast for BOOT_COMPLETED.
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<receiver android:name=".autostart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".hello"></activity>
<service android:enabled="true" android:name=".service" />
</application>
</manifest>
autostart.java
public class autostart extends BroadcastReceiver
{
public void onReceive(Context context, Intent arg1)
{
// This callback will be fired automatically when device starts after boot
// Do your alarm alarm manager work here
}
}

Categories

Resources