Probably an easy question for you guys, but its my first attempt at creating a service that should run in the background when my app closes. My problem is: The service doesnt start when I click on my "start service" button. I don't see any of the toast, and nothing in the logcat (no errors either). Thanks in advance!
Service class
public class MyService extends Service {
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
My main activity
public void startServiceClick(View v){
Log.d("foo", "onClick: starting srvice");
startService(new Intent(this, MyService.class));
}
public void stopServiceClick(View v){
Log.d("foo", "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
}
Manifest xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="se.johanberntsson.main"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<application
android:icon="#drawable/maps1"
android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".LongitudeActivity"
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=".DebugActivity" />
<activity android:name=".GoogleMapsActivity" />
<service android:enabled="true" android:name=".MyService" />
</application>
</manifest>
this is suggestion as all else looking fine
should call super in each function like super.onCreate();
as may be possible service is already started and try to stop and start again and check it toast appears ....
try
<service android:enabled="true" android:name="se.johanberntsson.servies.MyService" />
You may have already figured this out. In your code you override several native functions so you could add a toast and a catlog entry. Don't forget to add super.{whatever function you are calling}. What that does is it tells the android device to do whatever the function would have done had the function not been overrided, then do the extra stuff. In your case, if you call your oncreate function, it then the computer will make the toast and add a catlog entry, but it will not create the service.
#Override //forget about doing whatever onCreate usually does.
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();//toast
Log.d(TAG, "onCreate");//Add message to cat- log
//note: Service not created because function was overrided
}
however, if you add super.onCreate, the phone will create the service, then it will do what you tell it to do.
#Override //forget about doing whatever onCreate usually does.
public void onCreate() {
super.onCreate(); // do whatever onCreate usually does. Then do whatever is after me.
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();//toast
Log.d(TAG, "onCreate");//Add message to cat- log
}
I hope this helps.
I added your service into my code and it is working fine for me. please see below code and match with yours.
Activity >>
public class TestActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bt = (Button)findViewById(R.id.button11);
bt.setOnClickListener(this);
}
public void startServiceClick(View v){
Log.d("foo", "onClick: starting srvice");
startService(new Intent(this, MyService.class));
}
public void stopServiceClick(View v){
Log.d("foo", "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
}
#Override
public void onClick(View v) {
startServiceClick(v);
}
Manifest File >>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
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=".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:enabled="true" android:name=".MyService" />
</application>
Related
I have sent a broadcast here:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("com.example.administrator.broadcasttest.MY_BROADCAST");
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
// Toast.makeText(MainActivity.this, "You have send a broadcast just now.", Toast.LENGTH_SHORT).show();
}
});
}
}
But i can't receive it in my broadcast receiver:
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received in MyBroadcastReceiver",
Toast.LENGTH_SHORT).show();
}
And here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.broadcasttest">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.administrator.broadcasttest.MY_BROADCAST"/>
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In addition, my andriod version is 7.1.1, and my API version is 26.
I have tried many ways to solve it, but none worked.
I am searching for a long time to no avail
Please help or try to give me some ideas about how to achieve this.Thanks in advanced.
You cannot have more than one public class in a java file. Move your broadcast receiver class into a separate file.
I usually register receivers via XML AND code.
Try to register it:
BroadcastReceiver whatever = new MyBroadcastReceiver();
registerReceiver(whatever, intentFilter);
//Intentfilter is the intent you get in MyBroadcastReceiver
Hope it helps.
EDIT: DO NOT FORGET TO UNREGISTER IT:
unregisterReceiver(whatever);
I have been trying to workout this problem for the past couple of hours looking at various code samples here but still haven't found a solution.
I want a service to start when app starts and when the phone is reboot the service should start again automatically without starting the app. (Neither the toast or log appears when i restart my phone). Please see my code below:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
MyService.java
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startid){
Toast.makeText(this, "Service Running ...", Toast.LENGTH_LONG).show();
Log.v("Service","Service Running ...");
return super.onStartCommand(intent, flags, startid);
}
}
Autostart.java
public class Autostart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MyService.class);
context.startService(myIntent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xxxxx.receiverservice" >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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>
<receiver
android:name=".Autostart"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".MyService" />
</application>
</manifest>
Seems like this is a bug on Xiaomi. I haven't encountered this problem with any other device
For some reason, the service is not started, none of my debug logs are being called, nor are the toasts I created within the service being shown (Toasts displayed via a handler, toast code not shown, simple guide here for reference: http://www.jjoe64.com/2011/09/show-toast-notification-from-service.html)
public class MainActivity extends Activity {
Intent locationPollingIntent;
Button updateLocationButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationPollingIntent = new Intent(this, LocationService.class);
updateLocationButton = (Button) findViewById(R.id.updateLocationButton);
updateLocationButton.setText("Start");
updateLocationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, updateLocationButton.getText().toString());
if (updateLocationButton.getText().toString() == "Start") {
MainActivity.this.startService(locationPollingIntent);
updateLocationButton.setText("Stop");
} else if (updateLocationButton.getText().toString() == "Stop") {
MainActivity.this.stopService(locationPollingIntent);
updateLocationButton.setText("Start");
}
}
});
}
}
A snippet from my Service class looks like so:
public class LocationService extends Service {
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Location service started");
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Starting Service" );
grabLocation();
return super.onStartCommand(intent, flags, startId);
}
// No implementation
#Override
public IBinder onBind(Intent arg0) {
return null;
}
Lastly, my manifest contains the following
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rperryng.intellilocation"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service
android:name=".LocationService"
android:label="Location Service" />
<activity
android:name="com.rperryng.intellilocation.activities.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>
It is also worth noting that my mainActivity is in a package com.rperryng.intellilocation.activities and my service in com.rperryng.intellilocation.backgroundServices
I found the following log that is probably related to the issue:
01-27 12:53:58.804: W/ActivityManager(262): Unable to start service Intent { cmp=com.rperryng.intellilocation/.backgroundServices.LocationService }: not found
Try specifying the full package name in your manifest android:name="com.rperryng.intellilocation.backgroundServices.LocationService"
i am trying to develop a android application using broadcast receiver,my application means that,first i want to define and store a PARENT number to the database on my first activity ,when we install the app this activity will launch and the parent number saved to the database,then broadcast receiver want to active and its listen for call state changing,if any call is make through that phone i want to send a message to the parent number...??...here how can i use broadcast receiver...is it possible...and i mentioning my codes below......i hope you can help me for this .i try to do this many ways but i cant get the result.here first i create my first activity inside that i accessing my database values and trying to activate broadcast receiver.
public class PARENT_CALLActivity extends Activity
{
String PARENT=null;
EditText edparent;
Button submit;
String parent_number;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edparent=(EditText)findViewById(R.id.editText1);
submit=(Button)findViewById(R.id.btnsubmit);
submit.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
PARENT=edparent.getText().toString();
MyDabasehandler db=new MyDabasehandler(getApplicationContext());
if(db.getContact().equals(null))
{
db.addContact(new Contacts(PARENT));
}
else
{
db.editContact();
}
Intent reciver=new Intent(getApplicationContext(),myBroadcast.class);
startActivity(reciver);
}
});
}
}
my broadcast receiver....
public class myBroadcast extends BroadcastReceiver
{
String out_number;
String myparent;
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
out_number=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
MyDabasehandler db=new MyDabasehandler(context);
myparent=db.getContact().toString();
//Toast.makeText(context, out_number+"number", Toast.LENGTH_LONG).show();
SmsManager sm=SmsManager.getDefault();
sm.sendTextMessage(myparent, "5554", "calling..to"+out_number, null, null);//5554 is my emulator number to check its in emulator
Toast.makeText(context, "send"+out_number, Toast.LENGTH_SHORT).show();
}
}
and my Manifest is..
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sha.pcall"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".PARENT_CALLActivity"
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=".MyDabasehandler"
android:label="#string/app_name">
</activity>
<activity android:name=".Contacts"
android:label="#string/app_name">
</activity>
<receiver android:name=".myBroadcast"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
/manifest>
and i am getting force to close when i press the submit button.
You should put the LogCat output that shows the exception StackTrace.
What I can spot in the code that it seems that you are missing
<uses-permission android:name="android.permission.READ_PHONE_STATE" >
I m trying to start an IntentService from the main activity of y application and it won't start. I have the service in the manifest file. Here's the code:
MainActivity
public class Home extends Activity {
private LinearLayout kontejner;
IntentFilter intentFilter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
kontejner = (LinearLayout) findViewById(R.id.kontejner);
intentFilter = new IntentFilter();
startService(new Intent(getBaseContext(), HomeService.class));
}
}
Service:
public class HomeService extends IntentService {
public HomeService() {
super("HomeService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(getBaseContext(), "TEST", Toast.LENGTH_LONG).show();
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.salefinder"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Home"
android:label="#string/title_activity_home" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".HomeService" />
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
How can I make it work?
onHandleIntent gets called from a background thread. You can't modify the UI, or in this case, make Toast from outside the UI thread. So, I wouldn't expect anything to happen with your service.
Just try writing something out with Log.d() to see if your service is getting called.
It seams that android cached a bad version of the app - I forced closed it and started it again, and it worked...