I tried to implement the addProximityAlert method, but it does not fire. Here is my code:
SampleProximityAlert
public class SampleProximityAlert extends Activity {
/** Called when the activity is first created. */
protected LocationManager locationManager;
protected Location location;
public static Location pLocation;
protected Intent intent;
protected PendingIntent pIntent;
protected GeoPoint point;
public float distance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 1,
new ProximityListener());
} catch (RuntimeException e) {
e.printStackTrace();
}
// point = new GeoPoint(49868004, 8626971);
try {
pLocation = new Location(location.getProvider());
} catch (RuntimeException e) {
e.printStackTrace();
}
Log.i("PROVIDER", location.getProvider());
pLocation.setLatitude(49.868004);
pLocation.setLongitude(8.626971);
distance = methodeDistance(pLocation);
Log.i("DISTANCE", String.valueOf(distance));
Log.i("POSITION",
String.valueOf(location.getLatitude()) + ","
+ String.valueOf(location.getLongitude()));
intent = new Intent(this, ProximityAlert.class);
intent.setAction("ProximityAlert");
pIntent = PendingIntent.getService(this, 0, intent, 0);
locationManager.addProximityAlert(49.868004, 8.626971, 429, 50000,
pIntent);
}
public float methodeDistance(Location mLocation) {
float mDistance = location.distanceTo(pLocation);
return mDistance;
}
}
ProximityAlert
public class ProximityAlert extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i("Alert", "fired");
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i("ONCREATE", "create ProximityAlert as Service");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("ONSTARTCOMMAND", "OnStartCommand");
return super.onStartCommand(intent, flags, startId);
}
}
ProximityListener
public class ProximityListener implements LocationListener {
String DEBUG_TAG = "ProximityListener";
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d(DEBUG_TAG, location.toString());
// tvD.setText(String.valueOf(location.distanceTo(pLocation)));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
XML Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsystems.proximityAlert"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SampleProximityAlert"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ProximityAlert">
<intent-filter>
<action android:name="ProximityAlert"/>
<category android:name="com.proaktiveOrtung"/>
</intent-filter>
</service>
<service android:name=".ProximityAlert"></service>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsystems.proximityAlert"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SampleProximityAlert"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ProximityAlert">
<intent-filter>
<action android:name="ProximityAlert"/>
<category android:name="com.proaktiveOrtung"/>
</intent-filter>
</service>
<service android:name=".ProximityAlert"></service>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
Sorry I selected not the complete code.
when you add a ProximityAlert you have to pass a PendingIntent to the LocationManager, these PendingIntent will be fired on a broadcastIntent and i dont see in your code when, where you register a receiver for that PendingIntent.
Now a question... why do you write a service if you add the ProximityAlert on an Activity?
Related
I am looking to have some basic forms run on my android device after it is reset or on the first boot like most smartphones ask you to connect to Wi-Fi, register the device etc. I haven't worked with native android development previously so what are my options and what areas should I look into?
Try this
BootCompleteReceiver.java
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MsgPushService.class);
context.startService(service);
}
}
MyService.java
public class MyService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroy", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MainActivity
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(getBaseContext(), MyService.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newbootservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name=".MyService"/>
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I am developing an application that sends location data to a database. As I need this task to be executed in the background, I used the Service type to send the data, but when the application goes to the background, the service stops executing after a few seconds. I researched the subject and found the JobScheduler class, but this class performs services in the background with a very long time interval (15min) and I needed the service to be performed at least every 2 min and to be canceled only by the user. Is there a way to do this? I thank anyone who can help.
https://developer.android.com/reference/android/app/job/JobScheduler
My service:
public class GPSservice extends Service {
private String TAG = "INICIAR SERVIÇO GPS";
private Context context;
private HandlerThread handlerThread;
private Handler handler;
private final int TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS = 60; //tempo de sessenta segundos
#Override
public void onCreate() {
handlerThread = new HandlerThread("HandlerThread");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
//Previne que seja executado em subsequentes chamadas a onStartCommand
if(!handlerThread.isAlive()) {
Log.d("NotifyService","Notificações iniciadas");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
Runnable runnable = new Runnable() {
#Override
public void run() {
AtualizarLocalizacaoBanco();
handler.postDelayed(this, 1000 * TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS);
}
};
handler.post(runnable);
}
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("NotifyService","Notificações Finalizadas");
Intent broadcastIntent = new Intent(this, BroadCastReceiver.class);
sendBroadcast(broadcastIntent);
//handlerThread.quit();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
}
public void AtualizarLocalizacaoBanco(){
context = this;
ModeloAtualizacao model = new ModeloAtualizacao();
SharedPreferences preferences = this.context.getSharedPreferences("user_preferences", MODE_PRIVATE);
model.setId(preferences.getString("usuario_id", ""));
model.setLati(preferences.getString("user_latitude", ""));
model.setLongi(preferences.getString("user_longitude", ""));
model.setEmpresa(preferences.getString("usuario_empresa", ""));
model.setEscola(preferences.getString("usuario_escola", ""));
Call<String> call = new RetrofitConfig().postAtualizacao().atualizarLocalizacao(model);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d("Sucesso: ", "ok");
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("Erro atualizar", t.getMessage());
}
});
}
Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true">
<activity android:name=".ActivityGPS"></activity>
<activity android:name=".Activity_Lista_Aluno" />
<activity
android:name=".ProfessorActivity"
android:label="#string/title_activity_professor" />
<service
android:name=".GPSservice"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false"/>
<activity
android:name=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".Activity_Login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I'm making this simple app where when a button is placed users gps location should be displayed and it works fine with emulator but when i try that in a real phone both longitude and latitude are zero.
this is my code:
Main Activiy:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView longS = (TextView) findViewById(R.id.longi);
final TextView latiS = (TextView) findViewById(R.id.lati);
Button btn_show_location = (Button) findViewById(R.id.button1);
btn_show_location.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
LocationManager mlocManager=null;
LocationListener mlocListener;
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(MyLocationListener.latitude>0)
{
longS.setText("Latitude:- " + MyLocationListener.latitude);
latiS.setText("Longitude:- " + MyLocationListener.longitude + '\n');
}
else
{
longS.setText("Please wait");
}
} else {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
}
});
}
MyLocationListener:
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
// loc.getLatitude();
//loc.getLongitude();
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
//print "Currently GPS is Disabled";
}
#Override
public void onProviderEnabled(String provider)
{
//print "GPS got Enabled";
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.databasecollect"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
was trying to implement an service that disables bluetooth and wifi when ever user tries to enable bluetooth and Wifi as they are few ways of getting infected.
i have disable use of application use of app locker.
this is what i tried with the tutorials available but so far i have failed to run it on the bootup
Service class
public class MyService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
BroadcastReceiver mReceiver = new StatusReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
}
Reciver
public class StatusReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
wifiManager.setWifiEnabled(false);
}
}
}
Activity
public class TestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("HI","I am on activity");
startService(new Intent(this,MyService.class));
finish();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.active"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".TestActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" >
</service>
<receiver android:name=".StatusReceiver" >
</receiver>
</application>
</manifest>
I'm trying to use this very simple Service and BroadcastReceiver but I'm getting a
ClassNotFound exception. If I don't use startService things are fine so the problem it's with the receiver. I have registered it in the android manifest file so why do I get the ClassNotFound exception?
I will be using this method of communication for polling a php file and updating a ListView. Is this the appropriate way of communicating (broadcast intent)?
public class MessengerServiceActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this,MessengerService.class));
}
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle b=intent.getExtras();
if(b==null)
return;
String msg=b.getString("message");
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText(msg);
}
}
}
public class MessengerService extends Service {
HttpClient hc;
HttpPost hp;
String s[]={"pratik","harsha","dayal","hritika"};
public MessengerService() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
hc=new DefaultHttpClient();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t=new Thread(new Runnable(){
public void run()
{
int k=0;
while(true)
{
Intent i=new Intent("com.pdd.messenger.MyAction");
i.putExtra("message",s[k]);
sendBroadcast(i);
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG)
.show();
}
k=(k+1)%4;
}
}
});
t.start();
return super.onStartCommand(intent, flags, startId);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pdd.messenger"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MessengerServiceActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.pdd.messenger.MyAction"/>
</intent-filter>
</receiver>
<service android:name=".MessengerService"></service>
</application>
</manifest>