I am in the process of trying to get an email sent using BroadcastReceiver, the code is working correct using AsyncTask when using onClick but does not work when AlarmReceiver is being called.
Would it be better to use IntentService for this method? If so, what is the best way to write this?
Can anyone help with this problem? I am still new to java and want to help improve my knowledge. :)
Any help would be appreciated! Thank you!
AlarmReceiver.java
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.content.BroadcastReceiver;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import static android.graphics.Color.GREEN;
public class AlarmReceiver extends BroadcastReceiver {
Context cxt;
Activity context;
#Override
public void onReceive(Context arg0, Intent arg1) {
cxt = arg0;
addNotification();
new SendMail().execute();
}
private class SendMail extends AsyncTask<String, Integer, Void> {
protected Void doInBackground(String... params) {
Mail m = new Mail("youremail#gmail.com", "password");
String[] toArr = {"toemail#outlook.com"};
m.setTo(toArr);
m.setFrom("fromemail#gmail.com");
m.setSubject("Achieve Alert!");
m.setBody("This is a reminder about your upcoming assignment or examination!");
try {
if(m.send()) {
Toast.makeText(context.getApplicationContext(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context.getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return null;
}
}
}
First start Intent service from Alarm manager :
private void setAlarm(Calendar targetCal){
/* HERE */ Intent intent = new Intent(getBaseContext(), AlarmService.class);
final int _id = (int) System.currentTimeMillis();
/* HERE */ PendingIntent pendingIntent = PendingIntent.getService(this,_id,intent,PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
......
.....
Now Intent Service class:
public class AlarmService extends IntentService {
PowerManager powerManager;
PowerManager.WakeLock wakeLock;
public AlarmService() {
super("");
}
#Override
protected void onHandleIntent(Intent intent) {
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FCFCFCFC");
wakeLock.acquire();
addNotification();
sendMAIL();
}
public void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.icon_transperent)
.setLights(GREEN, 700, 700)
.setContentTitle("Achieve - Alert!")
.setContentText("This is a reminder for your deadline!");
Intent notificationIntent = new Intent(getApplicationContext(), MainMenu.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
builder.setVibrate(new long[] { 0, 1000, 1000, 1000, 1000 });
manager.notify(0, builder.build());
}
public void sendMAIL(){
Mail m = new Mail("youremail#gmail.com", "password");
String[] toArr = {"toemail#outlook.com"};
m.setTo(toArr);
m.setFrom("fromemail#gmail.com");
m.setSubject("Achieve Alert!");
m.setBody("This is a reminder about your upcoming assignment or examination!");
try {
if(m.send()) {
Toast.makeText(getApplicationContext(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
wakeLock.release();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Now, Manifest add:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service android:name=".AlarmService" android:exported="true" android:enabled="true"/>
Related
I am trying to scan Wifi every 10 seconds. I have produced an Android Foreground service to achieve this. The application has all of the right permissions and does get the list of local Wifi hotspots. However, it does this once. I have tried to implement a thread to do this every 10 seconds, as can be seen in the code below. The Log.d() message is logged every 10 seconds but the Wifi is not printed after the first time it is printed.
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class ForegroundService extends Service {
private WifiManager wifiManager;
public static final String CHANNEL_ID = "ForegroundServiceChannel";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
wifiManager = (WifiManager) getApplicationContext().getSystemService(getApplicationContext().WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
//Toast.makeText(this, "WiFi is disabled ... We need to enable it", Toast.LENGTH_LONG).show();
wifiManager.setWifiEnabled(true);
}
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
new Thread(new Runnable() {
#Override
public void run() {
Looper.prepare();
while (true) {
Log.d("Test","00000000000000");
scanWifi();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
//stopSelf();
return START_NOT_STICKY;
}
private void scanWifi() {
wifiManager.startScan();
Toast.makeText(this, "Scanning WiFi ...", Toast.LENGTH_SHORT).show();
}
BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> results = wifiManager.getScanResults();
unregisterReceiver(this);
for (ScanResult scanResult : results) {
Log.d("WIFI",scanResult.SSID + " - " + scanResult.capabilities);
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
I think you should remove unregisterReceiver(this); from onRecieve and place it onDestroy()
public class NetworkStateChecker {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
try {
TimeUnit.SECONDS.sleep(10); // Sleeps 10 seconds.
} catch (InterruptedException e) {
e.printStackTrace();
}
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork!=null) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkStateChecker.getConnectivityStatus(context);
String status = null;
if (conn == NetworkStateChecker.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkStateChecker.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkStateChecker.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
use the above class to check the available network connections for every 10sec...
Next in broadcase reciever tyr the below code
String status = NetworkStateChecker.getConnectivityStatusString(context);
use the below permissions
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
..............
<receiver
android:name="in.phoenix.services.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
</intent-filter>
</receiver>
trying to start a service from a background service, somehow it work with all android version Lower than api 24, and actually not work in (oreo,Pie,..).
however i try this code below, and this screen for problem i face if testing using +api>24....
Error picture
Glade for your help, Thanks!!
1) Main Activity(Start Services) :
public void startService(View v) {
String input = editTextInput.getText().toString();
Intent serviceIntent = new Intent(this, ExampleService.class);
serviceIntent.putExtra("inputExtra", input);
ContextCompat.startForegroundService(this, serviceIntent);
Toast.makeText(Options.this,"Notification, On.", Toast.LENGTH_LONG).show();
}
public void stopService(View v) {
Intent serviceIntent = new Intent(this, ExampleService.class);
stopService(serviceIntent);
Toast.makeText(Options.this,"Notification, Off.", Toast.LENGTH_LONG).show();
}
2) Background services Class :
package com.demo.testttt;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import static com.demo.testttt.App.CHANNEL_ID;
public class ExampleService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, Home.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
}
else {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, Home.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new Notification.Builder(ExampleService.this)
.setVibrate(new long[] { 350, 350})
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.build();
NotificationManager notifmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/// notifmanager.notify(0,notification);
startForeground(1, notification);
}
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
3) App Class :
package package com.demo.testttt;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
4) manifest xml :
<service
android:name=".ExampleService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:enabled="true"
android:exported="true"/>
where is Your Permission in Manifest.
you should permission of FOREGROUND_SERVICE.
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
I want to make an app that shows a notification as soon as headphone is plugged in and remove it when it is plugged out. My app works fine when it is on or home button is pressed, but doesn't work when back is pressed or app is closed by long pressing home and swiping it away. What should I use in order to make it work?
This is my code
package com.example.earphone;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class HeadsetPlugReceiver extends BroadcastReceiver {
TextView t1;
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
return;
}
boolean connectedHeadphones = (intent.getIntExtra("state", 0) == 1);
// boolean connectedMicrophone = (intent.getIntExtra("microphone", 0) == 1) && connectedHeadphones;
String headsetName = intent.getStringExtra("name");
Log.v("message", "headphone connected" + headsetName);
Intent i = new Intent(context, MainActivity.class);
PendingIntent p = PendingIntent.getActivity(context,0,i,0);
// Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
if(state==1){
Intent intent1 = new Intent(context, ES.class);
context.startForegroundService(intent1);
}
switch (state) {
case 0:
Intent intent1 = new Intent(context, ES.class);
context.stopService( intent1);
Toast.makeText(context, "Headphone ejected", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(context, "I have no idea what the headset state is", Toast.LENGTH_SHORT).show();
}
}
}}
package com.example.earphone;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String C_ID = "noti";
#Override
public void onCreate() {
super.onCreate();
createnoti();
}
private void createnoti(){
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
NotificationChannel nc = new NotificationChannel(
C_ID,"ex", NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager nm= getSystemService(NotificationManager.class);
nm.createNotificationChannel(nc);
}
}
}
package com.example.earphone;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import static com.example.earphone.App.C_ID;
public class ES extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent ni = new Intent(this,HeadsetPlugReceiver.class);
PendingIntent pi = PendingIntent.getActivity(this,0,ni,0);
Notification notification = new NotificationCompat.Builder(this, C_ID)
.setContentTitle("Headphones plugged in")
.setContentText("currently plugged in")
.setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pi).build();
startForeground(1,notification);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
public class MainActivity extends AppCompatActivity {
Button b;
HeadsetPlugReceiver headsetPlugReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = findViewById(R.id.b);
// Intent intent = new Intent(this, ES.class);
//startService(intent);
headsetPlugReceiver = new HeadsetPlugReceiver();
IntentFilter i = new IntentFilter();
i.addAction("android.intent.action.HEADSET_PLUG");
registerReceiver(headsetPlugReceiver,i);
}
}
MainActivity.java
import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements LocationListener {
PendingIntent mGeofencePendingIntent;
public static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 100;
private List<Geofence> mGeofenceList;
private GoogleApiClient mGoogleApiClient;
public static final String TAG = "Activity";
LocationRequest mLocationRequest;
double currentLatitude =12.9141 , currentLongitude = 77.6233;
Boolean locationFound;
protected LocationManager locationManager;
protected LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
mGeofenceList = new ArrayList<Geofence>();
int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resp == ConnectionResult.SUCCESS) {
initGoogleAPIClient();
createGeofences(currentLatitude, currentLongitude);
} else {
Log.e(TAG, "Your Device doesn't support Google Play Services.");
}
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(1 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
}
public void initGoogleAPIClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(connectionAddListener)
.addOnConnectionFailedListener(connectionFailedListener)
.build();
mGoogleApiClient.connect();
}
private GoogleApiClient.ConnectionCallbacks connectionAddListener =
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "onConnected");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
} else {
//If everything went fine lets get latitude and longitude
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.i(TAG, currentLatitude + " WORKS " + currentLongitude);
//createGeofences(currentLatitude, currentLongitude);
//registerGeofences(mGeofenceList);
}
try{
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Saving Geofence");
} else {
Log.e(TAG, "Registering geofence failed: " + status.getStatusMessage() +
" : " + status.getStatusCode());
}
}
});
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
Log.e(TAG, "Error");
}
}
#Override
public void onConnectionSuspended(int i) {
Log.e(TAG, "onConnectionSuspended");
}
};
private GoogleApiClient.OnConnectionFailedListener connectionFailedListener =
new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed");
}
};
/**
* Create a Geofence list
*/
public void createGeofences(double latitude, double longitude) {
String id = UUID.randomUUID().toString();
Geofence fence = new Geofence.Builder()
.setRequestId(id)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(latitude, longitude, 200)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
mGeofenceList.add(fence);
}
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL);
builder.addGeofences(mGeofenceList);
return builder.build();
}
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
return PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
}
#Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.i(TAG, "onLocationChanged");
}
}
GeoTransitionsIntentservices.java
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
public class GeofenceTransitionsIntentService extends IntentService {
private static final String TAG = "GeofenceTransitions";
public GeofenceTransitionsIntentService() {
super("GeofenceTransitionsIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "onHandleIntent");
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
//String errorMessage = GeofenceErrorMessages.getErrorString(this,
// geofencingEvent.getErrorCode());
Log.e(TAG, "Goefencing Error " + geofencingEvent.getErrorCode());
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
Log.i(TAG, "geofenceTransition = " + geofenceTransition + " Enter : " + Geofence.GEOFENCE_TRANSITION_ENTER + "Exit : " + Geofence.GEOFENCE_TRANSITION_EXIT);
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL){
showNotification("Entered the location", "Entered the Location");
}
else if(geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
Log.i(TAG, "Showing Notification...");
showNotification("Exited", "Exited the Location");
} else {
// Log the error.
showNotification("Error", "Error");
Log.e(TAG, "Error ");
}
}
public void showNotification(String text, String bigText) {
// 1. Create a NotificationManager
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
// 2. Create a PendingIntent for AllGeofencesActivity
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 3. Create and send a notification
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Geofence Monitor")
.setContentText(text)
.setContentIntent(pendingNotificationIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.build();
notificationManager.notify(0, notification);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher);
} else {
new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher);
}
}
}
I want to implement Dwell when user exits the region. I have developed the geofence notification when user exits and entry the region and now I want to implement it has to monitor for a certain period of time and after exiting.
It should make toast message and if I implement I am getting error message.
In your IntentService use toaster like this, it will not give error
private void sendNotification(String notificationDetails) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "here is your toast msg", Toast.LENGTH_LONG).show();
}
});
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Define the notification settings.
builder.setSmallIcon(R.drawable.ic_launcher)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher))
.setColor(Color.RED)
.setContentTitle(notificationDetails)
.setContentText(getString(R.string.geofence_transition_notification_text))
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
And in
#Override
protected void onHandleIntent(Intent intent) {
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT){
sendNotification("your notification details");
sendAPICall("some token","body","my call");
}
}
//// Api call
public void sendAPICall(final String reg_token, final String body, final String title) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("body", body);
dataJson.put("title", title);
json.put("notification", dataJson);
json.put("to", reg_token);
RequestBody body = RequestBody.create(JSON, json.toString());
Request request = new Request.Builder()
.header("Authorization", "key=" + Constants.GCM_AUTH_KEY)
.url("http://learnologic.com/send")
.post(body)
.build();
okhttp3.Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
Logger.showDebugLog(finalResponse);
} catch (Exception e) {
Logger.showErrorLog(e.toString());
}
return null;
}
}.execute();
}
// stop monitor geofence
public void stopMonitoringGeofences() {
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
return;
}
try {
// Remove geofences.
LocationServices.GeofencingApi.removeGeofences(
mGoogleApiClient,
// This is the same pending intent that was used in addGeofences().
getGeofencePendingIntent()
).setResultCallback(this); // Result processed in onResult().
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
logSecurityException(securityException);
}
}
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
// addGeofences() and removeGeofences().
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
I'm new at this android stuff and trying to teach myself the language and I'm running into a brick wall here.
I'm trying to program a really simple widge that is just a button. When the button is pressed the phone goes to silent mode. Unfortunately, the onlky thing that I am able to program the button do is pop a toast message.
Can someone please advise me on my errors. Thanks a bunch in advance. Here is my code:
package com.DoNotDisturb.widget;
import com.DoNotDisturb.widget.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class DoNotDisturbWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
Intent active = new Intent(context, DoNotDisturbWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
active.putExtra("msg", "Phone is silent");
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
#Override
public void onReceive(Context context, Intent intent) {
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
// check, if our Action was called
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
String msg = "null";
try {
msg = intent.getStringExtra("msg");
} catch (NullPointerException e) {
Log.e("Error", "msg = null");
}
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification noty = new Notification(R.drawable.icon, "Do Not Disturb Feature Activated", System.currentTimeMillis());
noty.setLatestEventInfo(context, "Notice", msg, contentIntent);
notificationManager.notify(1, noty);
} else {
// do nothing
}
super.onReceive(context, intent);
}
}
private AudioManager getSystemService(String audioService) {
// TODO Auto-generated method stub
return null;
}
}