I am trying to create a notification when an alarm triggers.But alarm is not triggering and also no notification is displaying. Here is Here is the MainActivity.java file -
package com.kaushal28.kaushal1
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleAlarm();
}
public void scheduleAlarm()
{
Long time = new GregorianCalendar().getTimeInMillis()+10000;
Intent intentAlarm = new Intent(this, AlarmReciever.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled", Toast.LENGTH_LONG).show();
}
}
And here is the AlarmReciever Class -
package com.kaushal28.kaushal1;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
public class AlarmReciever extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent1)
{
System.out.println("Notification setup");
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent=new Intent(context,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(context,1,intent,0);
Notification notification=new Notification.Builder(context)
.setContentText("TESTING NOTIFIACTION")
.setContentTitle("Notification")
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setSound(sound)
.build();
NotificationManager notificationManager= (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE) ;
notificationManager.notify(1,notification);
}
}
And here is my menifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kaushal28.kaushal1">
<uses-permission android:name="android.permission.WAKE_LOCK"></uses- permission>
<receiver android:process=":remote" android:name=".Alarm"></receiver>
<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>
</application>
</manifest>
What I'm missing here? Any help will be appreciated.
The receiver is missing from the manifest file you need to add it according to the docs.
For brevity, I paraphrase the relevant bits:
Add the receiver to your app's manifest file:
<receiver android:name=".AlarmReciever"
android:enabled="false">
</receiver>
Related
I was creating a simple notification app, but which is not showing any notification. I have used BroadcastReceiver and service for showing it up. It doesn't showing any errors but still not working.
MainActivity.java
package com.example.myapplication;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
{
int NOTIFICATION_REMINDER_NIGHT = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setBroadcast(this);
}
void setBroadcast(Context context)
{
Intent notifyIntent = new Intent(this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(context, NOTIFICATION_REMINDER_NIGHT, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1000 * 60 * 15, pendingIntent);
}
}
MyNewIntentService.java
package com.example.myapplication;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
public class MyNewIntentService extends IntentService
{
private static final int NOTIFICATION_ID = 1;
#Override
public void onCreate() {
super.onCreate();
startForeground(NOTIFICATION_ID, new Notification());
}
/**
* #param name
* #deprecated
*/
public MyNewIntentService(String name) {
super(name);
}
public MyNewIntentService(){
super("service");
}
#Override
protected void onHandleIntent(#Nullable Intent intent)
{
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("My title");
builder.setContentText("This is the body");
builder.setSmallIcon(R.drawable.ic_launcher_background);
Intent notifyIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
Notification notificationCompat = builder.build();
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(NOTIFICATION_ID, notificationCompat);
}
}
MyReceiver.java
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
public class MyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent intent1 = new Intent(context, MyNewIntentService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, MyNewIntentService.class));
} else {
context.startService(new Intent(context, MyNewIntentService.class));
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication"
tools:targetApi="31">
<service
android:name=".MyNewIntentService"
android:enabled="true"
android:exported="true"></service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<receiver android:name=".MyReceiver"
android:enabled="true"
android:exported="false"/>
</application>
</manifest>
log
android.app.RemoteServiceException:
Bad notification for startForeground
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2275)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:257)
at android.app.ActivityThread.main(ActivityThread.java:8246)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
what's the problem? is there any os validations.
Thanks.
This error is likely because you're just using an empty notification. Take your logic from onHandleIntent, and use it to construct the notification when calling context.startForeground(...)
Also, AlarmManager::setRepeating is not reliable in modern versions of Android. I would recommend you use setAlarmClock or setExactAndAllowWhileIdle instead.
I have a complete example of an alarm app on my GitHub here, which may be useful for you.
What is the proper way to handle Bluetooth media buttons in an Android app? At this point, all I want is an event to fire when I press the pause/play button on my Bluetooth headset. Somehow, I had a working solution yesterday, and today it just doesn't work. Without reinstalling the app, or any update happening on my phone, the onReceive method of my subclass of BroadcastReceiver is never entered. I'm targeting Android 9.0, since this is just for myself.
I used the information in these two questions for the solution:
How to capture key events from bluetooth headset with android
BroadcastReceiver for ACTION_MEDIA_BUTTON not working
This is a bare minimum version of what was working yesterday, which currently does not work:
AndroidManifest.xml
<?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.myapplication">
<uses-permission android:name="android.permission.BLUETOOTH" />
<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>
<receiver android:name=".MediaButtonIntentReceiver">
<intent-filter android:priority="2139999999">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver();
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
AudioManager mAudioManager = null;
ComponentName mReceiverComponent = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mReceiverComponent = new ComponentName(this, MediaButtonIntentReceiver.class);
mediaFilter.setPriority(2139999999);
registerReceiver(mMediaButtonReceiver, mediaFilter);
}
}
MediaButtonIntentReceiver.java
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
Log.i("mylog", "init");
}
#Override
public void onReceive(Context context, Intent intent) {
Log.i("mylog", "receive");
abortBroadcast();
}
}
I am using on receive() to receive broadcast and launch another application(by intent). Whenever the app(wifimann) receives the broadcast, the other app (called kotkot(written in Kotlin)) doesn't launch from initial app despite the Wi-Fi being connected.
My code is as follows:
MainActivity:
package com.wifi.wifimann;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
ConnectivityReciever.java:
package com.wifi.wifimann;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import com.wifi.wifimann.MainActivity;
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities networkAgent = connMgr.getNetworkCapabilities(connMgr.getActiveNetwork());
// NetworkInfo wifi = networkAgent.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
if (networkAgent.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("com.example.kotkot");
if (launchIntent != null) {
context.startActivity(launchIntent);//null pointer check in case package name was not found
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wifi.wifimann">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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">
<receiver android:name=".MyBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
It also says that MyBroadcastReceiver is unresolved. But my build.gradle has the same pkg name("com.wifi.wifimann") as its application ID.
kotkot:
MainActivity:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.core.content.ContextCompat.startActivity
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.content.Context.CONNECTIVITY_SERVICE
import androidx.core.content.ContextCompat.getSystemService
import android.content.BroadcastReceiver
import android.content.Context
import android.net.NetworkCapabilities
import android.os.Build
import androidx.core.content.ContextCompat.getSystemService
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val welcome_greeting: TextView = findViewById(R.id.welcome_greeting)
welcome_greeting.setText("kotleenhere!!")
}
}
I tried to do a broadcast receiver dynamically for incoming SMS will show a toast but the app doesn't show anything.
I register the broadcast dynamically in the mainActivity like this.
MainActivity.java
package com.example.smsreader;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
BroadcastReader reader = new BroadcastReader();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(reader, filter);
}
}
This is brodcast class, the app will show a toast when the phone will receive a SMS but it doesn't
package com.example.smsreader;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class BroadcastReader extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())){
Toast.makeText(context, "it is working", Toast.LENGTH_LONG).show();
}
}
}
I don't register anything in the manifest file.
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smsreader">
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try the following :
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
You need to use the following method for registering local broadcastReceiver ;)
LocalBroadcastManager.getInstance(this).registerReceiver(reader, filter)
I've searched the archives and still can't resolve my issue.
I'm trying to take an user input in seconds that will call the broadcast receiver to create a toast message and vibrate the phone. However, the broadcast receiver is never called and I can't figure it out. My code is below.
Thanks!
package com.example.cs984x.alrm;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText inputSeconds = (EditText) findViewById(R.id.editText1);
int inputTime = Integer.parseInt(inputSeconds.getText().toString());
Toast.makeText(MainActivity.this, "The alarm will go off in " + inputTime + " seconds.", Toast.LENGTH_LONG).show();
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
myIntent.setAction("com.example.cs984x.alrm.vibrate");
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+(inputTime*1000), pendingIntent);
}
});
}
}
Broadcast Receiver Class:
package com.example.cs984x.alrm;
import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.EditText;
import android.widget.Toast;
import static android.content.Context.ALARM_SERVICE;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Your time is up", Toast.LENGTH_LONG).show();
Vibrator v;
v= (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(2000);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cs984x.alrm">
<uses-permission android:name="android.permission.VIBRATE" >
</uses-permission>
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<receiver
android:name=".MyReceiver" android:process=":remote"
android:enabled="true">
<intent-filter>
<action android:name="com.example.cs984x.alrm.vibrate" />
</intent-filter>
</receiver>
</manifest>
Add action to intent:
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
myIntent.setAction("YourPackageName.YourAction");
PendingIntent pendingIntent =PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
in AndroidManifest:
<intent-filter>
<action android:name="YourPackageName.YourAction" />
</intent-filter>