I am developing an android application related to geofencing and I tried Broadcast receiver to get a notification when entering into geofence and I will work only when the application is running and then I tried Service to get a notification but now no notification is coming when entering into geofence.
Here is the code
**
package com.example.fypautosilenceapp;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import java.util.List;
public class GeofenceService extends Service {
private static final String TAG = "GeofenceBroadcastRecive";
AudioManager audioManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
NotificationHelper notificationHelper=new NotificationHelper(getApplicationContext());
GeofencingEvent geofencingEvent=GeofencingEvent.fromIntent(intent);
if(geofencingEvent.hasError()){
Toast.makeText(getApplicationContext(), "Geofence has error", Toast.LENGTH_SHORT).show();
Log.d(TAG,"OnRecive:Error recive geofence event...");
}
List<Geofence> geofenceslist=geofencingEvent.getTriggeringGeofences();
//Location geofencelocation=geofencingEvent.getTriggeringLocation();
for (Geofence geofence:geofenceslist){
Log.d(TAG,"OnRecive:"+geofence.getRequestId());
}
int transtiontype=geofencingEvent.getGeofenceTransition();
switch (transtiontype){
case Geofence.GEOFENCE_TRANSITION_ENTER:
// Toast.makeText(getApplicationContext(),"Enter geofence",Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("Enter geofence","",MapsActivity.class);
// audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
// Toast.makeText(getApplicationContext(),"Exit geofence",Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("Exit geofence","",MapsActivity.class);
// audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
break;
case Geofence.GEOFENCE_TRANSITION_DWELL:
// Toast.makeText(getApplicationContext(),"Enter Dwell",Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("Enter Dewell","",MapsActivity.class);
// audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
}
return null;
}
}
**
I am trying to read a file as inputstream to fill in the file with additional data. This data is then supposed to be sent over to a second activity which unwraps the data and displays it on the screen. this is my code
package com.example.daniel.finalproject;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class Secondactivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
}
public void Proceed(View view) {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
}
}
However this line: InputStream is = am.open("madlibsimple.txt");
returns the error. madlibsimple.txt is in the assetsfolder, but I
don't know what goes wrong. Any help would be much appreciated.
open(String file) can throw an error (i expect IOException) that you have to catch with an
try {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
} catch (Exception e) {
e.printStacktrace();
}
statement.
This whole topic is not about what goes wrong, but what COULD go wrong
For more information on the topic of exceptions and errorhandling you can click here
After two days of tests we were able to partially work.
I downloaded the file, but I have no idea where to store it.
I tried to download a picture and the picture appears in the folder /all_downloads
I do not know how to store it in /sdcard/update.
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
public class Upgrade extends ActionBarActivity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrade);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://android.vrt.ro/tv-update/v1.apk"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("file:///sdcard/download/v1.apk"),
"application/vnd.android.package-archive");
startActivity(promptInstall);
}
}
Use this
request.setDestinationInExternalPublicDir("/updates", "update.apk");
Added in API level 9
public DownloadManager.Request setDestinationInExternalPublicDir (String dirType, String subPath)
Set the local destination for the downloaded file to a path within the
public external storage directory (as returned by
getExternalStoragePublicDirectory(String)).
The downloaded file is not scanned by MediaScanner. But it can be made
scannable by calling allowScanningByMediaScanner().
Parameters dirType the directory type to pass to
getExternalStoragePublicDirectory(String)` subPath the path within the
external directory, including the destination filename Returns this
object Throws IllegalStateException If the external storage directory
cannot be found or created.
You can also use this version
String updatePath = Environment.getExternalStorageDirectory() + File.separator + "Updates" + File.separator + "update.apk";
request.setDestinationUri(Uri.fromFile(new File(updatePath)))
I'm working with android xml rpc to mount a server. For that I'm using and intentService. The only problem is that when the server class is launched, my onHandleIntent which contains the server is never called.
I've made some research and I found someone who had the same problem, he managed solving it by using super class but I'm new in programming and didn't manage to do what he did ==> link
Here is my code:
package tfe.rma.ciss.be;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlrpc.android.MethodCall;
import org.xmlrpc.android.XMLRPCServer;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class Server extends IntentService {
public String myData="";
public String streamTitle = "",path="";
public void onCreate() {
Log.d("Server", ">>>onCreate()");
}
public Server() {
super("Server");
}
public void onStart (Intent intent, int startId) {
Log.d("Server", ">>>Started()"); }
#Override
protected void onHandleIntent(Intent intent) {
Log.d("Server", ">>>handlingIntent()");
try {
ServerSocket socket = new ServerSocket(8214);
XMLRPCServer server = new XMLRPCServer();
Log.d("Server", ">>>opening on port" + socket);
while (true) {
Socket client = socket.accept();
MethodCall call = server.readMethodCall(client);
String name = call.getMethodName();
if (name.equals("newImage")) {
ArrayList<Object> params = call.getParams();
// assume "add" method has two Integer params, so no checks done
myData = (String)( params.get(0));
//int i1 = (Integer) params.get(1);
server.respond(client, new Object[] {200});
/*intent = new Intent (this, ParseFunction.class);
startService (intent); */
Toast.makeText(this, myData, Toast.LENGTH_SHORT).show();
Log.d("ParseFunction", ">>>Started()");
Intent i = new Intent( this, B.class );
i.putExtra( "Azo", myData);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( i );
} else {
server.respond(client, null);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
If you got here and nothing worked, check your manifest looks like this:
<service android:name=".subpackage.ServiceClassName" >
</service>
And not like this:
<service android:name=".subpackage.ServiceClassName" />
There's a problem with xml closing tags. The first one works. The second is legal but doesn't work.
In case someone else wants the result here is what I should have done. Adding superclass to onCreate super.onCreate() and change onStart by onStartCommand (plus its superclass super.onStartCommand()), now it works as a charm
package tfe.rma.ciss.be;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlrpc.android.MethodCall;
import org.xmlrpc.android.XMLRPCServer;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class Server extends IntentService {
public String myData="";
public String streamTitle = "",path="";
public void onCreate() {
super.onCreate();
Log.d("Server", ">>>onCreate()");
}
public Server() {
super("Server");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, startId, startId);
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_STICKY;
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("Server", ">>>handlingIntent()");
try {
ServerSocket socket = new ServerSocket(8214);
XMLRPCServer server = new XMLRPCServer();
Log.d("Server", ">>>opening on port" + socket);
while (true) {
Socket client = socket.accept();
MethodCall call = server.readMethodCall(client);
String name = call.getMethodName();
if (name.equals("newImage")) {
ArrayList<Object> params = call.getParams();
// assume "add" method has two Integer params, so no checks done
myData = (String)( params.get(0));
//int i1 = (Integer) params.get(1);
server.respond(client, new Object[] {200});
/*intent = new Intent (this, ParseFunction.class);
startService (intent); */
Toast.makeText(this, myData, Toast.LENGTH_SHORT).show();
Log.d("ParseFunction", ">>>Started()");
Intent i = new Intent( this, B.class );
i.putExtra( "Azo", myData);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( i );
} else {
server.respond(client, null);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
Get rid of onStart(). First, it is obsolete. Second, you are not chaining to the superclass, thereby preventing IntentService from doing its work.
I had the same issue, it turned out the service definition was missing in the App manifest.
Adding:
<service
android:name=".MyIntentServiceName"
android:exported="false" />
solved the problem.
Just to sum up: In case you override onStartCommand, do not forget to call super:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
If not, check your manifest, see answer by Mister Smith.
I was having this problem but only on some devices, more specifically on a Motorola Moto G 1st Gen (4.5" & 4G-less) and the solution was to include the FULL PACKAGE NAME in the Service description in the Manifest.
So changing 'mypackage.MyService' to 'com.android.myapp.mypackage.MyService' solved the onHandleIntent never being called.
Some of you might get to this page because your onHandleIntent() method never gets called, despite you implemented everything just fine.
If it's your first service you try to test, you might not be awared of the importance of permissions. In that case check your permissions.
I hope this helps someone.
I had the same problem. I removed the OnCreate method and it works like a charm now. LMK if it worked for you :)
I have made small app for Android mobile.
In one situation I am not getting any solution.
Actually my app has small functionality for calling to customer.
So after call ended I need that event of which last number will dialed or which app is runs.
AndroidManifest:
<receiver android:name=".PhoneStateBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE">
</action></intent-filter>
</receiver>
Add following permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE">
</uses-permission>
PhoneStateBroadcastReceiver.java (refactored the code a bit)
package com.mobisys.android.salesbooster;
import com.mobisys.android.salesbooster.database.HelperDatabase;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PhoneStateBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "PhoneStateBroadcastReceiver";
Context mContext;
String incoming_number;
private int prev_state;
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); //TelephonyManager object
CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE); //Register our listener with TelephonyManager
Bundle bundle = intent.getExtras();
String phoneNr = bundle.getString("incoming_number");
Log.v(TAG, "phoneNr: "+phoneNr);
mContext = context;
}
/* Custom PhoneStateListener */
public class CustomPhoneStateListener extends PhoneStateListener {
private static final String TAG = "CustomPhoneStateListener";
#Override
public void onCallStateChanged(int state, String incomingNumber){
if( incomingNumber != null && incomingNumber.length() > 0 )
incoming_number = incomingNumber;
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "CALL_STATE_RINGING");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "CALL_STATE_OFFHOOK");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "CALL_STATE_IDLE==>"+incoming_number);
if((prev_state == TelephonyManager.CALL_STATE_OFFHOOK)){
prev_state=state;
//Answered Call which is ended
}
if((prev_state == TelephonyManager.CALL_STATE_RINGING)){
prev_state=state;
//Rejected or Missed call
}
break;
}
}
}
}
Read more here, Source : http://mobisys.in/blog/2011/09/is-your-call-ended-on-android-phone/