What to write in MyGCMListenerService? - java

I'm trying to add GCM to my new application with this guide: https://developers.google.com/cloud-messaging/android/client#manifest
When I add these lines to my Manifest, It errors and do not recognize the lines
android:name="com.example.MyGcmListenerService"
android:name="com.example.MyInstanceIDListenerService"
yes, I've changed the com.example to my project details.
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service
android:name="com.example.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name="com.example.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
As i read, I have to create my own Java Class for MyGcmListenerService and for MyInstanceIDListenerService, but I have no idea what to write in it?
I got really confused about all this GCM stuff.

this is what you need to write in MyGcmListenerService
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.e(TAG, "From: " + from);
Log.e(TAG, "Message: " + message);
sendNotification(message );
}
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Sorry!!")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
this service will listen for GCM messages. and when a message will receive then onMessageReceived will trigger and then its your responsibility to handle the GCM Message. you generate any notification or what ever you want.

Step 1. Make GCM Utility Class
import android.content.Context;
import android.content.Intent;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class GCMUtils
{
static String TAG = "GCM";
static int NOTIFICATION_ID = 99;
public static String SENDER_ID = "YOUR SENDER ID";
Context context;
public GCMUtils(Context context)
{
this.context = context;
if (checkPlayServices())
{
Intent intent = new Intent(context, RegisterDeviceService.class);
context.startService(intent);
}
}
private boolean checkPlayServices()
{
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS)
{
return false;
}
return true;
}
}
Step 2. Make Register Device Class
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
public class RegisterDeviceService extends IntentService
{
public RegisterDeviceService() {
super(GCMUtils.TAG);
}
#Override
protected void onHandleIntent(Intent intent)
{
try
{
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(GCMUtils.SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(GCMUtils.TAG, "GCM Registration Token: " + token);
}
catch (Exception e)
{
Log.d(GCMUtils.TAG, "Failed to complete token refresh", e);
}
}
}
Step 3 . Make Instance ID Service
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
public class InstanceIdService extends InstanceIDListenerService
{
#Override
public void onTokenRefresh()
{
Intent intent = new Intent(this, RegisterDeviceService.class);
startService(intent);
}
}
Step 4. Make GCMListenerService
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
public class GCMmessageListener extends GcmListenerService
{
#Override
public void onMessageReceived(String from, Bundle data)
{
String message = data.getString("price");
Log.d(GCMUtils.TAG, "From: " + from);
Log.d(GCMUtils.TAG, "Message: " + data);
sendNotification(message);
}
private void sendNotification(String message)
{
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, GCMUtils.NOTIFICATION_ID /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getNotificationIcon())
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(message).setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(GCMUtils.NOTIFICATION_ID /* ID of notification */, notificationBuilder.build());
}
private int getNotificationIcon()
{
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.icon_lolipop : R.drawable.icon;
}
}
Step 5 Add this to your Mainefest
Add these permission
<uses-permission android:name="com.dspl.keyvendors.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
and register these Receiver and Services
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="YOUR PACKAGE NAME" />
</intent-filter>
</receiver>
<service
android:name=".gcm.RegisterDeviceService"
android:exported="false">
</service>
<service
android:name=".gcm.InstanceIdService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<service
android:name=".gcm.GCMmessageListener"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
Hope this will help you out...

MyGcmListenerService.java
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.google.android.gms.gcm.GcmListenerService;
public class MyGcmListenerService extends GcmListenerService {
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
private Uri defaultSoundUri;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
if (from.startsWith("/topics/")) {
String topic = from.replace("/topics/", "");
try {
if (new SharedPreferencesHelper(this).getGCMTopics().contains(topic)) {
sendNotification(message, 0);
}
} catch (NullPointerException ignored) {
}
} else {
if (message != null) {
switch (message) {
case "0":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.WHOLE_UPDATE)
.putExtra(Constants.CLEAR_UPDATE, true));
break;
case "1":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.BOOKING_UPDATE));
sendNotification(Constants.BOOKING_NOTIFY, Integer.parseInt(message));
break;
case "2":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.PACKAGE_UPDATE));
break;
case "3":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.LOCATION_UPDATE));
break;
case "4":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.MEETING_UPDATE));
sendNotification(Constants.MEETING_NOTIFY, Integer.parseInt(message));
break;
case "5":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.MANAGER_UPDATE));
break;
case "6":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.USER_UPDATE));
break;
case "7":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.WHOLE_UPDATE));
break;
default:
sendNotification(message, 0);
break;
}
}
}
}
private void sendNotification(String message, int i) {
Intent intent = new Intent(this, ActivityDrawer.class).putExtra(Constants.CLEAR_NOTIFICATION, true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Context context = this;
SharedPreferencesHelper sharedPreferencesHelper = new SharedPreferencesHelper(context);
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Book That!")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentText(message)
.setContentIntent(pendingIntent);
int notificationNumber;
if (i == 1) {
notificationNumber = sharedPreferencesHelper.getBookingNotificationNumber();
sharedPreferencesHelper.setBookingNotificationNumber(++notificationNumber);
} else if (i == 4) {
notificationNumber = sharedPreferencesHelper.getMeetingNotificationNumber();
sharedPreferencesHelper.setMeetingNotificationNumber(++notificationNumber);
} else {
notificationNumber = sharedPreferencesHelper.getNotificationNumber();
sharedPreferencesHelper.setNotificationNumber(++notificationNumber);
}
notificationBuilder.setNumber(notificationNumber - 1);
notificationManager.notify(i, notificationBuilder.build());
}
}
MyInstanceIDListenerService.java
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
public class MyInstanceIDListenerService extends InstanceIDListenerService {
#Override
public void onTokenRefresh() {
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
RegistrationIntentService.java
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
import java.util.TreeSet;
public class RegistrationIntentService extends IntentService {
Intent registrationComplete;
private SharedPreferencesHelper sharedPreferencesHelper;
public RegistrationIntentService() {
super("TokenRegistration");
}
#Override
protected void onHandleIntent(Intent intent) {
sharedPreferencesHelper = new SharedPreferencesHelper(this);
registrationComplete = new Intent(GCMConstants.REGISTRATION_COMPLETE);
InstanceID instanceID = InstanceID.getInstance(this);
try {
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
sharedPreferencesHelper.setGCMID(token);
subscribeTopics(token);
sharedPreferencesHelper.tokenStatus(true);
} catch (IOException e) {
if (e.getMessage().equals("SERVICE_NOT_AVAILABLE")) {
registrationComplete.putExtra("Error", Constants.NO_INTERNET);
}
sharedPreferencesHelper.tokenStatus(false);
}
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
private void subscribeTopics(String token) throws IOException {
TreeSet<String> TOPICS = new TreeSet<>();
TOPICS.add("BookThatUpdates");
sharedPreferencesHelper.setGCMTopics(TOPICS);
GcmPubSub pubSub = GcmPubSub.getInstance(this);
for (String topic : TOPICS) {
pubSub.subscribe(token, "/topics/" + topic, null);
}
}
}
GCMConstants.java
public class GCMConstants {
public static final String TOKEN_SAVED_IN_PREFERENCES = "tokenSavedInPreferences";
public static final String REGISTRATION_COMPLETE = "registrationComplete";
public static final String TOKEN = "Token";
public static final String TOPICS = "Topics";
}
If anything is missing please tell in comments.

Related

Cannot get camera access from web view android studio using camerajs

I'm using Android Studio to make my webview app and on my website I'm using webcam.js to access the camera. When it's opening the webcam view, it's returning error "Webcam.js error : could not access webCam: PermissionDeniedError". How do I fix this?
Error picture:
webcam error
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testabsen">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<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/Theme.TestAbsen">
<activity android:name=".MainActivity" android:theme="#style/Theme.AppCompat.DayNight.NoActionBar"></activity>
<activity
android:name=".SplashActivity"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity
package com.example.testabsen;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
WebView webView;
WebSettings webSettings;
private SwipeRefreshLayout mySwipeRefreshLayout;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermission();
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView_frame);
webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setAppCacheEnabled(false);
webSettings.getSaveFormData();
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.getJavaScriptEnabled();
webSettings.setAllowFileAccess(true);
webSettings.setAllowContentAccess(true);
webSettings.setLoadsImagesAutomatically(true);
webView.setWebViewClient(new WebViewClient());
downloadSetting();
uploadSetting();
setMySwipeRefreshLayout();
webView.loadUrl('webviewurl');
}
final void setMySwipeRefreshLayout(){
mySwipeRefreshLayout = findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
}
);
}
#Override
final public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
if (requestCode == REQUEST_SELECT_FILE)
{
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
}
else if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
else
Toast.makeText(getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}
protected void downloadSetting() {
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDescription, String mimetype, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String fileName = URLUtil.guessFileName(url,contentDescription,mimetype);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
DownloadManager dManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloaded", Toast.LENGTH_SHORT).show();
}
});
}
protected void uploadSetting() {
webView.setWebChromeClient(new WebChromeClient(){
final protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try
{
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
Toast.makeText(getApplicationContext() , "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
protected void checkPermission(){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
if(shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
ActivityCompat.requestPermissions(
MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
123
);
}else {
// Request permission
ActivityCompat.requestPermissions(
MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
123
);
}
}
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Apakah anda yakin ingin keluar?");
builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//if user pressed "yes", then he is allowed to exit from application
finish();
}
});
builder.setNegativeButton("Tidak",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//if user select "No", just cancel this dialog and continue with app
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
}

java.lang.ClassCastException: com.example.BellasHBG.LocationService cannot be cast to com.google.android.gms.location.LocationListener

I'm getting
java.lang.ClassCastException: com.example.BellasHBG.LocationService cannot be cast to com.google.android.gms.location.LocationListener
but I don't know how to resolve. Removing keyword abstract does not fix the problem. This is new to me, and I'm not that knowledgeable of java so any help is appreciated. The error seems top be occurring in LocationService on the following line: LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mlocationRequest, (com.google.android.gms.location.LocationListener) this);
The intent is to get location updates and send a notification to the app user if the location sells this particular bakery product.
Below are my MainActivity, LocationService and AndroidManifest.xml
MainActivity
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.view.KeyEvent;
import android.webkit.WebViewClient;
import android.widget.TextView;
import com.google.android.gms.location.LocationRequest;
//import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private WebView webView = null;
public static boolean orignotifsetting = false;
//PendingIntent pendingIntent;
private Alarm alarm;
MyToolBox mtools = new MyToolBox();
LocationIntentService mLocationIntentService = new LocationIntentService();
public LocationManager mlocManager;
//LocationListener mlocListener = new MyLocationListener();
//LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//public static GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
LocationRequest mLocationRequest;
PendingIntent resultPendingIntent;
public Intent resultIntent = new Intent();
LocationServiceImpl mLocationService = new LocationServiceImpl();
public static boolean prevNotificationsSetting;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("myTag", "in onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set the default values first time run but don't overwrite them if they have been set
// ----------------------------------------------------------------| - true will leave them alone, false will clear them every time
PreferenceManager.setDefaultValues(this, R.xml.pref_notification, true);
this.webView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
//myWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//myWebView.setWebViewClient(new WebViewClient());
WebViewClientImpl webViewClient = new WebViewClientImpl(this);
webView.setWebViewClient(webViewClient);
webView.loadUrl("https://www.bellashbg.com");
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
this.webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onResume() {
Log.i("myTag", "in onResume");
super.onResume();
Intent msgIntent = new Intent(MainActivity.this, LocationService.class);
if ((mtools.notificationsSetting(this)) & (prevNotificationsSetting == false)) {
prevNotificationsSetting = true;
startService(msgIntent);
}
else {
if ((!mtools.notificationsSetting(this)) & (prevNotificationsSetting == true)) {
// mLocationService.stopLocationUpdates();
prevNotificationsSetting = false;
boolean result = stopService(msgIntent);
if (result){
Log.d("MainActivity", "stopService true");
}
else {
Log.d("MainActivity", "stopService false");
}
//mLocationService.stopLocationUpdates();
//android.os.Process.killProcess(android.os.Process.myPid());
}
}
}
#Override
public void onPause() {
Log.i("myTag", "in onPause");
super.onPause();
}
#Override
public void onStop() {
Log.i("myTag", "in onStop");
super.onStop();
}
public void onDestroy() {
Log.i("myTag", "in onDestroy");
super.onDestroy();
//if (mSensorManager!=null){mSensorManager.unregisterListener(listener);}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i("myTag", "in onCreateOptionsMenu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings_menu, menu);
return super.onCreateOptionsMenu(menu); // cmnted 10/25/2015
//super.onCreateOptionsMenu(menu);
//return true;
// return true; stack overflow 6439085 says to return true to pop up menu
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i("myTag", "in onOptionsItemSelected");
//LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //added 11/12/2015 to remove updates
switch (item.getItemId()) {
case R.id.settings:
Intent settingsintent = new Intent(MainActivity.this, SettingsActivity.class);
MainActivity.this.startActivity(settingsintent);
break;
case R.id.help:
break;
case R.id.about:
break;
}
return true;
}
// Get the notifications status bar setting
public boolean notificationsSettingNotificationBar() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean notificationsNewMessageNotificationBar = SP.getBoolean("notifications_new_message_notification_bar", true);
return notificationsNewMessageNotificationBar;
}
// Get the notifications ringtone
public String notificationsSettingRingtone() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String notificationsNewMessageRingtone = SP.getString("notifications_new_message_ringtone", "NULL");
return notificationsNewMessageRingtone;
}
// Get the notifications vibrate setting
public boolean notificationsNewMessageSetting() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean notificationNewMessageVibrate = SP.getBoolean("notifications_new_message_vibrate", true);
return notificationNewMessageVibrate;
}
private TextView latituteField;
private Context mContext;
}
LocationService
package com.example.BellasHBG;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.app.TaskStackBuilder;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
//import com.google.android.gms.location.LocationListener;
//import android.support.v7.app.AppCompatActivity;
//import android.support.v4.app.NotificationCompat;
//import android.support.v4.app.TaskStackBuilder;
//import com.google.android.gms.common.ConnectionResult;
//import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
//import com.google.android.gms.location.LocationListener;
//import com.google.android.gms.location.LocationRequest;
//import com.google.android.gms.location.LocationServices;
/**
* Created by craigmartensen on 4/7/16.
*/
public abstract class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 60000 * 1; // 1000 milliseconds in 1 second
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 5;
public static final long LOCATION_DISTANCE_IN_METERS = 3;
MyToolBox mtools = new MyToolBox();
public static GoogleApiClient mGoogleApiClient;
//public static GoogleSignInClient mSignInClient;
public static GoogleSignInAccount mSignInClient;
LocationRequest mlocationRequest;
private boolean isRemoving = false;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#SuppressWarnings("static-access")
#Override
public void onCreate() {
isRemoving = false;
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//alarm.SetAlarm(this);
//return START_STICKY;
super.onStartCommand(intent, flags, startId);
//Toast.makeText(this, "onHandleIntent", Toast.LENGTH_SHORT).show();
//mGoogleApiClient.connect();
Log.d("onStartCommand", "Service Started");
return Service.START_STICKY;
}
#Override
public void onConnected(Bundle connectionHint) {
if (isRemoving) {
stopLocationUpdates();
}
else {
isRemoving = false;
mlocationRequest = new LocationRequest();
mlocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mlocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mlocationRequest.setSmallestDisplacement(LOCATION_DISTANCE_IN_METERS);
Intent locationIntent = new Intent(getApplicationContext(), LocationIntentService.class);
locationIntent.putExtra("ID", "FusedLcation");
PendingIntent locationPendingIntent = PendingIntent.getService(getApplicationContext(), 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mlocationRequest, locationPendingIntent);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mlocationRequest, (com.google.android.gms.location.LocationListener) this);
}
}
public void onLocationChanged(Location loc)
{
Log.d("onLocationChanged", "Entering method");
//Toast.makeText(this, "onLocationChanged", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
//Toast.makeText(getApplicationContext(), "entering onLocationChanged", Toast.LENGTH_SHORT).show();
String myText;
double mlat = loc.getLatitude();
double mlong = loc.getLongitude();
DBHelper myDBHelper = new DBHelper(this);
// use the following line if you just want to know if the location is found ie, sells Bellas
//boolean soldHere = myDBHelper.doesLocationSellBellas("my_table",41.685471,-73.975393);
// the following line retrieves the name of the location that sells bellas, null if it's not found
//String locName = myDBHelper.getLocationName("my_table", 41.685471, -73.975393);
String locName = myDBHelper.getLocationName(DBHelper.LOCATION_TABLE_NAME, mlat, mlong);
// set up for notification in the notification status bar
if (locName != null) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Bella's sold here");
// .setStyle(new NotificationCompat.BigTextStyle().bigText("Bella's sold here"));
// .setSubText(todaysjolt);
// .setDefaults(Notification.DEFAULT_SOUND)
//.setContentText("Bella's sold here");
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mBuilder.setContentText(locName);
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(locName));
// new 10/14/2015 - set up to allow user to go to website from notification
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// end new 10/14/2015
mNotifyMgr.notify(000, mBuilder.build());
Toast.makeText(getApplicationContext(), "You are at " + locName, Toast.LENGTH_SHORT).show();
//LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
}
protected void startLocationUpdates() {
if (mtools.notificationsSetting(this)) {
MainActivity.orignotifsetting = true;
//LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
public void stopLocationUpdates() {
if(!mGoogleApiClient.isConnected()){
isRemoving = true; //added
mGoogleApiClient.connect();
}
else {
//if (mGoogleApiClient != null) {
// if (!mGoogleApiClient.isConnected()) {
PendingIntent locationPendingIntent = PendingIntent.getService(this, 0, new Intent(this, LocationIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT);
//LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationPendingIntent); //moved below 1/28/2016
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) com.example.BellasHBG.LocationService.this);
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
stopSelf(); // stop the service
}
//}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
Log.d("LocationUpdateService", "Connection Suspended");
}
#Override
public void onDestroy(){
stopLocationUpdates();
//reportarGPS.interrupt();
//reportarGPS = null;
//LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
//mGoogleApiClient.disconnect();
//mGoogleApiClient = null;
//mHandler.removeCallbacksAndMessages(null);
//Thread.currentThread().interrupt();
super.onDestroy();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.BellasHBG">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="21"/>
<application
android:allowBackup="true"
android:icon="#drawable/bellas_logo_48x36"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.BellasHBG"
android:usesCleartextTraffic="true">
<activity
android:name="com.example.BellasHBG.SettingsActivity"
android:label="#string/action_settings"/>
<activity
android:name="com.example.BellasHBG.CreateNotificationOnBar"
android:label="create_notification_on_bar"/>
<activity
android:name="com.example.BellasHBG.CustomPreference"
android:label="custom_preference"/>
<activity
android:name=".MainActivity"
android:label="Bella's Home Baked Goods" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.BellasHBG.Alarm" />
<service android:enabled='true' android:name="com.example.BellasHBG.LocationService" />
</application>
</manifest>
Please uncomment the import for com.google.android.gms.location.LocationListener on LocationService and give a try again.

Android Background Wifi Scanning Foreground Service

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>

Can't Start Background Services in Api > 26

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" />

Using IntentService instead of AsyncTask for Broadcast Receiver?

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"/>

Categories

Resources