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>
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.
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 am trying to make an app which shows a user selected image which can be set by double-clicking on the button. The app does ask me for an image (which is good) but I don't know how to set it on ImageView if this onActivityResult is not getting called.
MainActivity:
package com.forever.bobby.cheater20;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.tomerrosenfeld.customanalogclockview.CustomAnalogClock;
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE = 100;
Button hiddenOnClickListener;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = findViewById(R.id.imageView);
CustomAnalogClock customAnalogClock = (CustomAnalogClock) findViewById(R.id.analog_clock);
customAnalogClock.setAutoUpdate(true);
hiddenOnClickListener = (Button) findViewById(R.id.touchButtonHidden);
hiddenOnClickListener.setOnClickListener(new DoubleClickListener() {
#Override
public void onSingleClick(View v) {
Log.e ("mPressesOnce -_-","..");
}
#Override
public void onDoubleClick(View v) {
Log.e ("mPressesTwice -_-","..");
openGallery();
}
});
}
private void openGallery () {
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, 0);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode,data);
Log.e ("SHould Be Steeted","");
if (requestCode == 0) {
Uri imgUri;
imgUri = data.getData();
// img.setImageURI(imgUri);
}
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.forever.bobby.cheater20">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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>
Any Kind of help is appreciated as I am a newbie
With android sdk >= 23, some permissions e.g. WRITE_EXTERNAL_STORE, READ_EXTERNAL_STORE, etc. you must request it in java code.
Therefore, when user starts using feature need permission, android will show a dialog and user can grant or cancel a permission. You can read more about it on developer.android.com.
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>