Unable to create service - android

I'm new to android and creating a service in one of my reminder application. but I my service is triggering when i call the startService() in my onCreate() method of my activity I am unable to see the toasts which are used in different methods of my service class.As new to android unable to figure out the problem.
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_show_reminders);
isReminders = false;
dataSrc = new RemitDataSrc(this);
dataSrc.open();
rem = dataSrc.findALL();
refreshDisplay();
}
private void refreshDisplay(){
if(isMyServiceRunning(GeofencingService.class)){
Intent intent = new Intent(this, GeofencingService.class);
stopService(intent);
Toast.makeText(this, "yes service", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "No service", Toast.LENGTH_LONG).show();
}
if(rem.size()==0){
Toast.makeText(this, "No Reminders in Database", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(this, GeofencingService.class);
startService(intent);
ArrayAdapter<Reminders> remAdpt = new RemindersListAdapter(this, rem);
setListAdapter(remAdpt);
}
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;
}
GeofencingService:
public class GeofencingService extends Service{
RemitDataSrc dataSrc;
/**
* Geofence Store
*/
private GeofenceStore mGeofenceStore;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "GeoFencing Service created", Toast.LENGTH_LONG).show();
dataSrc = new RemitDataSrc(this);
dataSrc.open();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "GeoFencing Service Started", Toast.LENGTH_LONG).show();
serviceTest sT= new serviceTest();
dataSrc.open();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "GeoFencing Service Stoped", Toast.LENGTH_LONG).show();
dataSrc.close();
}
}
manifest.xml:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SetReminderActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyD5GMap3cZBiMYWEiK0WX-2whx0xuqBwW4" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".AddReminderActivity"
android:label="#string/title_activity_add_reminder" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ActivityShowReminders"
android:label="#string/title_activity_activity_show_reminders" >
</activity>
<activity
android:name=".RemindersDetailActivity"
android:label="Reminder Details" >
</activity>
<service
android:name=".LocationCheckerService"
>
</service>
<service
android:name=".GeofencingService"
android:exported="false"
>
</service>
</application>

As you have mentioned in one of one of your comments that the package name of service is different from the package containing activity, use the fully qualified class name in manifest with package name.
<service
android:name="com.afifa.projectreminder.service.GeofencingService" android:exported="false"
>
</service>

Please register your service to your manifest as a children of your application like:
<application ..>
..
<service
android:name=".GeofencingService"
android:enabled="true">
</service>
</application>

Mention the service in the manifest of your project under application Tag.
like so
<service android:name=".ServiceName" />

Related

How to make an application start on factory reset/first startup?

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>

trigger a receiver if system date change automatically in android

I am a newbie for android. I have registered receiver in manifest using android.intent.action.DATE_CHANGED and it is working fine when a user changes the date manually. BUT my requirement is receiver has to be called automatically everyday the system date change say at 12:00 am. The user should not change the date.
Thanks in advance.
my code - manifest file
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".NotificationOne"
android:label="#string/title_activity_notification_one"
android:parentActivityName=".FirstActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".FirstActivity" />
</activity>
<service android:name=".MyService">
</service>
<receiver android:name=".MyBroadcastreceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<receiver android:name=".SecondBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.DATE_CHANGED"/>
</intent-filter>
</receiver>
</application>
Broadcast Receiver class
public class SecondBroadcastReceiver extends BroadcastReceiver {
private Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
Toast.makeText(context,"inside second",Toast.LENGTH_SHORT).show();
MyBroadcastreceiver.firstConnect = true;
MyBroadcastreceiver.hasInternet = isInternetAvailable();
if(MyBroadcastreceiver.hasInternet) {
context.startService(new Intent(context, MyService.class));
MyBroadcastreceiver.firstConnect = false;
}
}
public boolean isInternetAvailable() {
Toast.makeText(mContext,"inside isInternetAvailable",Toast.LENGTH_SHORT).show();
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
one service- which has notification
public class MyService extends Service {
private NotificationManager myNotificationManager;
private int notificationIdOne = 111;
private int numMessagesOne = 0;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
displayNotificationOne();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
i have another receiver which will be called when internet is connected/disconnected.

Services in Android is not getting Started in BroadCast receiver

I am trying to make an android app that must do some database activities like storing phone number and name etc in the SQLite DB . This all Data Base stuff is done as a service. The service must start as soon as the call comes and when the call ends the stored details must be showed to user as soon as the call ends. For this purpose I am using Broad Cast Receiver. I have also provide the following codes which I have used in my app.
MyServices.java
public class MyServices extends Service {
TelephonyManager Tel;
MyPhoneStateListener MyListener;
RB_SIGNAL_STRENGTH signalobj = new RB_SIGNAL_STRENGTH();
RB_DatabaseHandler db = new RB_DatabaseHandler(getApplicationContext());
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
isMyServiceRunning();
MyListener = new MyPhoneStateListener();
Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
super.onCreate();
Log.i("Serv","Service Started");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
db.close_DB();
Log.i("Serv","Service Stopped");
super.onDestroy();
}
MyReceiver.java
public class MyPhoneReceiver extends BroadcastReceiver {
String state=null;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
try{
Intent i = new Intent(context,MyServices.class);
Log.i("Recv", "In Try");
context.startService(i);
}
catch(Exception e)
{
Log.d("Recv", "Service not starting");
}
}//End if offhook
if(state.equals(TelephonyManager.EXTRA_STATE_IDLE))
{
Log.i("Recv","CALL ENDED");
try
{
Intent i = new Intent(context,EndActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
catch(Exception e){
Log.d("Recv", "Activity not starting");
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.SIGNAL_PERSISTENT_PROCESSES" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity android:name="StartActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="EndActivity" >
</activity>
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
<service
android:name="MyServices"
></service>
</application>
Your class name is MyPhoneReceiver but in your Manifest you are using MyReceiver, these two names must match exactly.
Addition
I just noticed that you are trying to instantiate your database before the Service has a valid Context. This will probably throw an exception in MyServices:
RB_DatabaseHandler db = new RB_DatabaseHandler(getApplicationContext());
You can to declare db as a field variable but leave it null:
RB_DatabaseHandler db;
And inside a method like onStartCommand() initialize it:
db = new RB_DatabaseHandler(getApplicationContext());
Lastly, calling fundamental methods like onCreate() out of order usually creates problems, this is not recommended in onStartCommand():
super.onCreate();
because state variable is null
public class MyPhoneReceiver extends BroadcastReceiver {
String state=null;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
//your code here...

How to start service at boot on android 4.0.3

I wan't to start service at boot on android 4.0.3 but when i boot my device it not happen in my device and service not start.Help me please thank you
here is my manifest
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<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>
<service android:name="com.android.testsharedpreference.MyService"></service>
<receiver android:name="com.android.testsharedpreference.BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" >
</action>
</intent-filter>
</receiver>
</application>
my boardcast receiver
public class BootReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
context.startService(new Intent(context,MyService.class));
}
}
}
and my service
public class MyService extends Service
{
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
Toast.makeText(MyService.this, "onCreate Service ", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(MyService.this, "onDestroy Service ", Toast.LENGTH_LONG).show();
}
}
you should add add android.permission.RECEIVE_BOOT_COMPLETED as it was not required before ICS so the app was working fine but starting from ICS is you don't have this permission your app wont receive the boot completed intent
Don't forget to override the method "onStartCommand" in your MyService:
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
String action = intent == null ? null : intent.getAction();
Log.d("onStartCommand", "action = " + action);
/* ... */
return START_NOT_STICKY; // for example ...
}

Unable to start service Intent { cmp=com.marie.mainactivity/.BackgroundService }: not found

I've been studying from the book "Pro Android 2." I'm working through a Service example that consists of two classes: BackgroundService.java and MainActivity.java. The MainActivity claims (erroneously?) it starts the Service as indicated by output to logcat from the Log.d call below:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(TAG, "starting service");
Button bindBtn = (Button)findViewById(R.id.bindBtn);
bindBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent backgroundService = new Intent(MainActivity.this, com.marie.mainactivity.BackgroundService.class);
startService(backgroundService);
}
});
Button unbindBtn = (Button)findViewById(R.id.unbindBtn);
unbindBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
stopService(new Intent(MainActivity.this, BackgroundService.class));
}
});
}
}
What puzzles me is the UI provides two buttons: Bind and UnBind as shown above. But according to the documentation if onBind() as shown below returns null that indicates you don't want to allow binding. But as shown above the onClick() method of (the Bind button) bindBtn.setOnClickListener(new OnClickListener() calls startService(backgroundService) which gives this error:"Unable to start service Intent { cmp=com.marie.mainactivity/.BackgroundService }: not found"
public class BackgroundService extends Service {
private NotificationManager notificationMgr;
#Override
public void onCreate() {
super.onCreate();
notificationMgr = NotificationManager)getSystemService(NOTIFICATION_SERVICE);
displayNotificationMessage("starting Background Service");
Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
thr.start();
}
class ServiceWorker implements Runnable
{
public void run() {
// do background processing here...
//stop the service when done...
//BackgroundService.this.stopSelf();
}
}
#Override
public void onDestroy()
{
displayNotificationMessage("stopping Background Service");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void displayNotificationMessage(String message)
{
Notification notification = new Notification(R.drawable.note, message, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Background Service", message, contentIntent);
notificationMgr.notify(R.id.app_notification_id, notification);
}
}
I don't understand the point of this example. If onBind() returns null what's the point of having a Bind button (bindBtn)? I thought the point was to show how to start a BackgroundService. But it doesn't seem to work unless I'm missing something.
I should add I have added to my AndroidManifest.xml:
<service android:name=".BackgroundService"></service>
as follows:
<application android:icon="#drawable/icon" android:label="#string/app_name">
<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>
<service android:name=".BackgroundService"></service>
</activity>
</application>
Remove the service from inside the activity. It is at the same level as the activity within the application. Eg:
<application android:icon="#drawable/icon" android:label="#string/app_name">
<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>
<service android:name=".BackgroundService"></service>
</application>

Categories

Resources