I just created a service as shown below :
package com.example.timepass;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class alarm extends Service{
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Entered in service", Toast.LENGTH_SHORT).show();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand...", Toast.LENGTH_LONG).show();
return 1;
// Log.i("YourService", "Yes this works.");
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Changed", Toast.LENGTH_SHORT).show();
return null;
}
}
Now when I startservice from mainactivity by the following command:
Intent myIntent = new Intent("com.example.timepass.ALARM");
MainActivity.this.startService(myIntent);
By doing this there is no error, but no TOAST of Service class are dipslayed
My manifest is :
<service class=".alarm" android:name=".alarm" android:enabled="true">
<intent-filter>
<action android:value="com.example.timepass.ALARM"
android:name=".alarm" />
</intent-filter>
</service>
Please guide me!!!
Probably you don't have the service in your manifest, or it does not have an that matches your action. Examining LogCat should turn up some warnings that may help.
More likely, you should start the service via:
startService(new Intent(this, alarm.class));
Related
package com.vkstechnologies.servicedemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;
/**
* Created by Vipul-Laptop on 03-01-2018.
*/
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(!hasFocus) {
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
}
I want to make an application that runs in background and detects whenever a power key is pressed to shut down the phone and it just dismisses the "power off" window.
If I run this method in MainActivity, then it runs smoothly, but not in service.
The Error says : cannot resolve method onWindowFocusChanged
I am implementing Service for receiving push notifications in Android device. The notifications are successfully received when app is in foreground. When app is closed and its instance is cleared from task manager, notifications are not received.
I want to keep the service running at all the times and it should not stop even if the app is cleared from the task manager.
I start the service from my activity in a button click. When i click the button my service starts and it gives me Toast notification every one minute but if I press the back button then also my service is running but , as soon as i clear my app from the recent activity list which is shown on long press of home button my service is stoped and if again i start my app and check the status of the service but its not running.
I want my service to run even if my app is closed.
This is my activity class
package com.example.hello;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
Button btnSer;
int Pointer=0;
ListView lv;
ArrayList<String> alist=new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSer=(Button) findViewById(R.id.btnstart);
btnSer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//start the service when the button is clicked
Log.e("","status of service : "+isMyServiceRunning(MyService.class));
//if(!isMyServiceRunning(MyService.class))
startService(new Intent(getApplicationContext(), MyService.class));
}
});
}
//check if the service is running
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
This is my Service class.
package com.example.hello;
import java.util.Calendar;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service{
private Handler handlerList = new Handler();
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
Toast.makeText(getApplicationContext(), "On start command called", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
public void updateLists(){
handlerList.postDelayed(mUpdateListTask, 1000*60);
}
private Runnable mUpdateListTask = new Runnable() {
public void run() { //will make a toast notification every 1 minute.
Calendar cal = Calendar.getInstance();
Log.e("","Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":");
Toast.makeText(getApplicationContext(), "Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":", Toast.LENGTH_LONG).show();
handlerList.postDelayed(this, 1000*60);
}};
#Override
public void onCreate() {
updateLists();
Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d("", "onCreate in service");
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d("", "onStart in service");
}
#Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d("", "onDestroy in service");
}
}
also added the permission in manifest file
<uses-permission android:name="android.permission.WAKE_LOCK" />
Start it as foreground service in the activity use startforeground(intent name) and return it as sticky in the service onstartCommand() method.
I'm trying to run startService() in my android app, but it is not working.
Here is the code from the call to start the service:
Intent mPositioningIntent = new Intent(this, MyGeoloqiPositioning.class);
stopService(mPositioningIntent);
startService(mPositioningIntent);
Here is the code from MyGeoloqiPositioning.java (note, this is taken with minor modifications from the source code of MapAttack)
package com.example.manhunttwopointoh;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.util.Pair;
import android.widget.Toast;
import com.example.manhunttwopointoh.MyFix;
import com.example.manhunttwopointoh.MyGeoloqiFixSocket;
import com.example.manhunttwopointoh.MyUDPClient;
public class MyGeoloqiPositioning extends Service implements LocationListener {
public static final String TAG = "GeoloqiPositioning";
private int batteryLevel = 0;
MyGeoloqiFixSocket fixSocket;
#Override
public void onCreate() {
android.os.Debug.waitForDebugger();
Toast.makeText(MyGeoloqiPositioning.this, "MyGeoloqiPositiong in onCreate()", Toast.LENGTH_LONG).show();
if (isConnected()) {
fixSocket = MyUDPClient.getApplicationClient(this);
} else {
// TODO: This is a crude check. Should probably be rolled into UDPClient class directly.
Log.w(TAG, "Network unavailable! Stopping positioning service.");
stopSelf();
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(MyGeoloqiPositioning.this, "MyGeoloqiPositiong in onStart()", Toast.LENGTH_LONG).show();
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
for (String provider : ((LocationManager) getSystemService(LOCATION_SERVICE)).getAllProviders()) {
if (!provider.equals("passive")) {
MyADB.log("Registering for updates with " + provider);
((LocationManager) getSystemService(LOCATION_SERVICE)).requestLocationUpdates(provider, 0, 0, this);
}
}
}
public void onStop() {
unregisterReceiver(batteryReceiver);
((LocationManager) getSystemService(LOCATION_SERVICE)).removeUpdates(this);
}
#Override
public void onDestroy() {
unregisterReceiver(batteryReceiver);
((LocationManager) getSystemService(LOCATION_SERVICE)).removeUpdates(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startid) {
Toast.makeText(MyGeoloqiPositioning.this, "MyGeoloqiPositiong in onStartCommand()", Toast.LENGTH_LONG).show();
onStart(intent, startid);
return Service.START_REDELIVER_INTENT;
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(MyGeoloqiPositioning.this, "MyGeoloqiPositiong in onLocationChanged()", Toast.LENGTH_LONG).show();
#SuppressWarnings("unchecked")
MyFix lqLocation = new MyFix(location, new Pair<String, String>("battery", "" + batteryLevel));
if (isConnected()) {
fixSocket.pushFix(lqLocation);
} else {
// TODO: This is a crude check. Should probably be rolled into UDPClient class directly.
Log.w(TAG, "Network unavailable, failed to push location fix!");
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
batteryLevel = intent.getIntExtra("level", 0);
}
};
/** Determine if the network is connected and available. */
private boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
return (activeNetwork != null && activeNetwork.isConnected());
}
}
I tried inserting a breakpoint in MyGeoloqiPositioning, but nothing ever comes of it. I also put various Toast() calls, but still no dice. My GeoloqiPositioning.java is never called. What am I doing wrong?
EDIT:
Here is the new code from the manifest file:
<service
android:name="com.manhunttwopointoh.MyGeoloqiPositioning"
android:enabled="true"
android:exported="false"
android:process=":lqRemote" >
<intent-filter>
<action android:name="com.manhunttwopointoh.MyGeoloqiPositioning" />
</intent-filter>
</service>
I tried adding the intent-filter tags, but still nothing. I also have nothing registering on the logs. Here is the code (commented out stopService()):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geoloqi);
Intent mPositioningIntent = new Intent(this, MyGeoloqiPositioning.class);
//stopService(mPositioningIntent);
startService(mPositioningIntent);
Toast.makeText(PreyGeoloqi.this, "testing mPositioningIntent: " + mPositioningIntent.toString(), Toast.LENGTH_LONG).show();
}
I still get nothing. Do I need to explicitly call methods in MyPreyGeoloqi.java? I am fairly confused...
Try adding an intent filter your service definition in the AndroidManifest:
<!-- snippet from Android Manifest file -->
<service android:name="com.manhunttwopointoh.MyGeoloqiPositioning" android:enabled="true" android:process=":lqRemote" >
<intent-filter>
<action android:name="com.manhunttwopointoh.MyGeoloqiPositioning" />
</intent-filter>
</service>
This allows your service to receive the intent sent from your Activity.
I made a service that every 5 second he put on the screen a TAG (I think this is the name of this). When I make a boot it needs to put the TAG on the screen but he says that the app crashed. Why?
The code:
Android Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="com.YuvalFatal.MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name="com.YuvalFatal.MyService"/>
BroadcastReceiver:
package com.YuvalFatal.ineedhelp;
import java.util.Timer;
import java.util.TimerTask;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastreceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context arg0, Intent arg1) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Intent startServiceIntent = new Intent(arg0, MyService.class);
arg0.startService(startServiceIntent);
}
}, 0, 5000);
}
}
IntentService:
package com.YuvalFatal.ineedhelp;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyService extends IntentService {
private static final String TAG = "com.YuvalFatal.ineedhelp";
public MyService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG, "Intent Service started");
}
}
I think (yep, I am magician and have great intuition :) your Service constructor should be default:
public class MyService extends IntentService {
...
public MyService() { // Default constructor! Without params!
super("MyService"); // Or another string
}
...
}
Other code looks normal
I want to pop up the alert dialog on location change through service. Here i have attached my manifest , Service and broadcastReciever codes.
In the console it is giving that .apk has been installed.
But i'm not getting any toast or alertdialog.
PLease correct me if i'm wrong.
Thanks.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name="com.ser.Myreceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<service android:enabled="true"
android:name="com.ser.RunService">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
</application>
</manifest>`
package com.ser;
import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class RunService extends Service implements LocationListener{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
System.out.println("**inside onCreate");
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
//Intent call = new Intent(Intent.ACTION_CALL,Uri.parse("tel:+5555"));
//startActivity(call);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("ALERT")
.setTitle("Location")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
}
#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
}
}
//Reciver
package com.ser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
//import android.widget.Toast;
//import android.util.Log;
public class Myreceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("MYRECEIVER");
//Toast.makeText(Myreceiver.this, "MyReciver", Toast.LENGTH_SHORT).show();
Intent serviceLauncher = new Intent(context, RunService.class);
context.startService(serviceLauncher);
//Log.v("TEST", "Service loaded at start");
}
}
create an Activity and and register receiver in this activity and start service from this activity and use alert dialog in activity class
i have modified your code and its working fine with my testing mobile device (sony xperia)
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ser"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name" android:debuggable="true">
<service android:enabled="true" android:name=".MyService">
<intent-filter>
<action android:name="com.ser.MyService">
</action>
</intent-filter>
</service>
<receiver android:enabled="true" android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action></intent-filter>
</receiver>
</application>
MyReceiver.java
package com.ser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "MyReceiver Started..",Toast.LENGTH_SHORT).show();
Log.v("Debug", "MyReceiver Started..");
Intent myIntent=new Intent(context,MyService.class);
context.startService(myIntent);
}
}
MyService.java
package com.ser;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
#Override
public IBinder onBind(Intent intent) {return null;}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(getBaseContext(), "Service Started..", Toast.LENGTH_SHORT).show();
Log.v("Debug", "Service Started..");
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try{
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex){}
try{
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch(Exception ex){}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
Log.v("Debug", "gps_enabled..");
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
Log.v("Debug", "network_enabled..");
}
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
private class myLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
if(location!=null){
Toast.makeText(getBaseContext(),"on location changed called..",Toast.LENGTH_SHORT).show();
Log.v("Debug", "on location changed method called..");
}
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}//service closed
still have any doubts for Receiver,Service and GPS classes let me know!!
or even your can check Start Service from Broadcast Receiver and Get Current Location links for details. hope it helps!!