ANDROID: How to receive broadcast of specific application's notifications? - java

I am creating an application which perform specific task on receiving broadcast notification from specific application like whats app, viber etc .I have searched about this but did not get any solution. is there any possibility exist to do this action? if exist then please guide me how? :)

Simple Only follow this code and read the documentation from this link
Manifest File
<receiver android:name=".callbroadcastreceiver"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
In Java callbroadcastreceiver file
public class callbroadcastreceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra( TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//Phone is ringing
}
else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
//Call received
Toast.makeText( context,"call received",Toast.LENGTH_SHORT ).show();
context.startService( new Intent( context,BoundService.class ) );
}
else if (state.equals( TelephonyManager.EXTRA_STATE_IDLE)) {
//Call Dropped or rejected
context.stopService( new Intent( context,BoundService.class ) );
}
}
}

You can check on the status bar notification but you can't read them. If it can be it really danger situation for vulnerabilty.
But using Accessibility Service, you can only listen to all notification on the notification bar. 

you can create a NotificationListenerService for this. Users may not be interested in giving your app the rights to monitor their notifications, though, which is why the user must manually enable this for your app.
but you can not read the content.

Try this to access your Notification form any Application
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.Notification;
import android.media.AudioManager;
import android.os.Parcelable;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import com.qna.vbage.Pref;
import static com.qna.vbage.FieldVerification.setRingerMode;
public class NotificationService extends AccessibilityService {
protected void onServiceConnected() {
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
info.notificationTimeout = 3000;
setServiceInfo(info);
}
#Override
public void onAccessibilityEvent(AccessibilityEvent e) {
//Toast.makeText(this, "onAccessibilityEvent", Toast.LENGTH_SHORT).show();
Log.d("VBage", "FML");
if (e.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
// Toast.makeText(this, "onAccessibilityEvent 2", Toast.LENGTH_SHORT).show();
Log.d("VBage", "Recieved event");
Parcelable data = e.getParcelableData();
if (data instanceof Notification) {
// Toast.makeText(this, "onAccessibilityEvent 3", Toast.LENGTH_SHORT).show();
Log.d("VBage", "Recieved notification");
Notification notification = (Notification) data;
Log.d("VBage", "ticker: " + notification.tickerText);
Log.d("VBage", "icon: " + notification.icon);
Log.d("VBage", "notification: " + e.getText());
}
}
}
#Override
public void onInterrupt() {
setRingerMode(NotificationService_API18.this, AudioManager.RINGER_MODE_SILENT);
}
}
Set Permission in your Manifest
<uses-permission
android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"
tools:ignore="ProtectedPermissions" />
set Service in Manifest to Call when App Start
<service android:name=".NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" >
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/accessibilityservice" />
</service>
Create xml in you Values folder res/Values/xml/accessibilityservice.xml
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeNotificationStateChanged"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100" />
You have to Enable Accessibility Manually for your App put below code in your Activity where you want to start Using this Service
if (!isAccessibilitySettingsOn(getApplicationContext())) {
AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);
dialog.setNegativeButton("Go!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
}
});
showCusDialog(dialog, "Warning!", R.drawable.ic_warning, getString(R.string.accessiblityString));
}
to Start Service from Activity
startService(new Intent(mActivity, NotificationService_API18.class));

Related

How to stop JobService Scheduled to when app is removed from background?

Currently i am working with an application and my app has a feature that the user will be able to click on a Navigate button and my app will start the Google Map. Till now it's fine and i have done it. But the fact where i am stuck is that i want my app to perform some tasks. To achieve that i have used JobService and scheduled it to run after every 5 seconds even when the app is in background.
When the user presses the back button then inside onDestroy method i have cancelled the scheduler. But when the app is removed from the background by sliding or pressing the cross icon the JobService keeps running as the onDestroy method can be called or not by the os when it is removed from the background. How can i stop the scheduled job when the app is removed from the background?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="javarank.com.serviceinbackground">
<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">
<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=".MyJobService" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" />
</application>
</manifest>
MyJobService class
public class MyJobService extends JobService {
#Override
public boolean onStartJob(final JobParameters jobParameters) {
Toast.makeText(getApplicationContext(), "Doing job", Toast.LENGTH_SHORT).show();
jobFinished(jobParameters, true);
return false;
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
return false;
}
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
private static final int JOB_ID = 1;
private JobInfo jobInfo;
private JobScheduler scheduler;
private Button navigateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ComponentName componentName = new ComponentName(this, MyJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName);
builder.setPeriodic(5000);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
// if true this job exists even after a system reboot...
builder.setPersisted(false);
jobInfo = builder.build();
scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.schedule(jobInfo);
navigateButton = (Button) findViewById(R.id.navigate_button);
navigateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringBuffer url = new StringBuffer("https://www.google.com/maps/dir/?api=1");
url.append("&origin=23.755736,90.374627");
url.append("&destination=23.754047,90.371682");
url.append("&travelmode=driving");
Uri gmmIntentUri = Uri.parse(url.toString());
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
});
}
#Override
protected void onDestroy() {
Toast.makeText(getApplicationContext(), "Destroy called.", Toast.LENGTH_SHORT).show();
scheduler.cancel(JOB_ID);
super.onDestroy();
}
}
I think you need to override following onStop() method and put stopService() command to stop the JobService.
#Override
protected void onStop() {
// A service can be "started" and/or "bound". In this case, it's "started" by this Activity
// and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call
// to stopService() won't prevent scheduled jobs to be processed. However, failing
// to call stopService() would keep it alive indefinitely.
stopService(new Intent(this, MyJobService.class));
super.onStop();
}
You can create a new service like
MyService.java
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
//stop you jobservice from here
stopSelf();
}
}
and start it from MainActivity.java
startService(new Intent(MainActivity.this,MyService.class));
Android> 7 automatically saves battery power. You must turn on the application's battery saving stop feature.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent intent = new Intent();
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}
add this to AndroidManifest.xml
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
I faced this issue, but I found that after schedule job service, it can't be canceled (From view).
So I turned to stop it inside the job service by calling onStopJob(params)
and it worked.

How to start NotificationListenerService?

Today I started writing for android. I want a simple (I think) app that waits for notification with specified title and then does something. I tried this code for service
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;
public class NotificationListener extends NotificationListenerService {
Context context;
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show();
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
Toast.makeText(this,"NOTIFICATION",Toast.LENGTH_SHORT).show();
String text = "";
String title = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
Bundle extras = extras = sbn.getNotification().extras;
text = extras.getCharSequence("android.text").toString();
title = extras.getString("android.title");
}
Log.i("Package",pack);
Log.i("Title",title);
Log.i("Text",text);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Toast.makeText(this,"NOTIFICATION removed",Toast.LENGTH_SHORT).show();
Log.i("Msg","Notification was removed");
}
}
Then added this to manifest:
<service
android:name=".NotificationListener"
android:enabled="true"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
finally started the service in MainActivity onCreate() startService(new Intent(context, NotificationListener.class));
onNotificationPosted does not work. It seems like service was started correctly, because toasts from onStartCommand and onCreate were shown. I tried on emulator and real device. I also allowed notification access in settings. Please help, I wasted 5 hours on that.

Detect new outgoing call android

I would like my app to detect if a new outgoing call happened
I want to do something like this :
if (there was a new outgoing call) {
do...
} else {
do...
}
You can use the android Broadcast Reciever. To use it all you have to do is first,
Create a new handler class to handle the broadcast receiver.
public class OutgoingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//You can do this to get the phone number, it is only optional
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
//Handle outgoing call event here
}
}
Then register it in the android manifest so it knows where this method is.
<receiver android:name=".OutgoingCallReceiver" >
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
Finally, create a permission in the android manifest.
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
And that should do it, hope I could help. :)
Create a broadcast receiver to catch the outgoing calls:
public class CallReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
// your code
}
}
Then register it in the manifest:
<receiver android:name=".CallReceiver" >
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
Lastly set the permissions:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
Detect outgoing phone call event
1)Create OutgoingCallBroadcastReceiver
public class OutgoingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(OutgoingCallReceiver.class.getSimpleName(), intent.toString());
Toast.makeText(context, "Outgoing call catched!", Toast.LENGTH_LONG).show();
//TODO: Handle outgoing call event here
}
}
Register OutgoingCallBroadcastReceiver in AndroidManifest.xml
Add permission in AndroidManifest.xml

Service not starting when button is pressed?

I know this has been asked a million times before, but nothing is working for me. I have a service in a separate class that needs to be started when a button is pushed, after an application is launched from a LaunchIntent.
Long story short, here's my goal:
run commands>wait three seconds for commands to run>launch app>start service
The service is to monitor for the CONFIGURATION_CHANGED broadcast.
Manifest (the parts that matter):
</activity>
<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.CONFIGURATION_CHANGED" >
</action>
</intent-filter>
</receiver>
<service android:enabled="true" android:name=".MyService" />
</application>
</manifest>
MyService.java:
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import android.app.Service;
public class MyService extends Service {
String[] commandsdefault = {"/x"};
public void onCreate() {
Toast.makeText(this, "x", Toast.LENGTH_SHORT);
}
public void onDestroy() {
Toast.makeText(this, "x", Toast.LENGTH_SHORT);
}
public void onReceive(Context context, Intent intent) {
MainActivity ogres = new MainActivity();
ogres.RunAsRoot(commandsdefault);
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "x", Toast.LENGTH_SHORT);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
And then I simply have the following line in my MainActivity.java to call the service to start:
startService(new Intent(getApplicationContext(), MyService.class));
I am more confused than a mosquito in a mannequin shop. LogCat is returning absolutely nothing helpful other than u=0 not found.
Do I have something incorrect here? I'm not even seeing toasts from the service starting.
Make sure your service is declared in Android manifest
try to Override the onStartCommand() method of your service. hope this helps
Try specifying the full name of your service as the android:name attribute (e.g. android:name="com.example.MyService")
Ok, solved my own question.
MyService was running the whole time! I just didn't see the toast notifications to alert me when it started. Now I have a monitor in my main Activity that posts a toast when the service is started/killed, rather than using MyService itself to post toasts.

PreferenceActivity and BroadcastReceiver - Implement dynamic preferences

I'm going by the following code example to dynamically build a preference activity.
http://www.linuxtopia.org/online_books/android/devguide/guide/samples/ApiDemos/src/com/example/android/apis/app/PreferencesFromCode.html
The preference dialog shows, but I'm not able to see any changes after closing it.
Here's where I'm defining the activity in AndroidManifest.xml
<activity
android:name="PreferencesActivity" android:label="#string/preferences_name">
</activity>
Here's where I'm defining the receiver.
<receiver
android:name="FroyVisualReceiver"
android:label="#string/app_name"
android:exported="false">
<intent-filter>
<action android:name="com.starlon.froyvisuals.PREFS_UPDATE"/>
</intent-filter>
</receiver>
And here's the BroadcastReceiver. I never see the "WTF" in logcat. What am I doing wrong?
package com.starlon.froyvisuals;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.util.Log;
public class FroyVisualsReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("WTFWTF", "WTFWTFWTFW");
String action = intent.getAction();
if(action.equals("com.starlon.froyvisuals.PREFS_UPDATE"))
{
((FroyVisuals)context).updatePrefs();
}
}
}
Oh here's onPause where I'm broadcasting the PREFS_UPDATE intent.I do see the logcat message. This method is part of my PreferenceActivity.
/** another activity comes over this activity */
#Override
public void onPause()
{
Log.i(TAG, "onPause ================================ ");
super.onPause();
Intent i = new Intent(this, FroyVisualsReceiver.class);
i.setAction("com.starlon.froyvisuals.PREFS_UPDATE");
sendBroadcast(i);
}
Edit: I think it may have to do with this line. 'this' points to my PreferenceActivity.
Intent i = new Intent(this, FroyVisualsReceiver.class);
Try a simple Intent:
Intent i = new Intent();
i.setAction("com.starlon.froyvisuals.PREFS_UPDATE");
sendBroadcast(i);

Categories

Resources