Android - Service does not start - java

I am making app for me and my class mates, that checks for new homeworks and exams. It has service that may not be killed beacuse of checking school server (like every 5 minutes) for changed size of file with list of exams and stuff like this. I tried following code:
MayinActivity.java
package com.test.simpleservice;
import android.app.ActivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//checking runings services - remove later
ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);
String message = null;
for (int i=0; i<rs.size(); i++) {
ActivityManager.RunningServiceInfo
rsi = rs.get(i);
System.out.println("!!!!!!!!!!Service" + "Process " + rsi.process + " with component " + rsi.service.getClassName());
message = message + rsi.process;
}
Button btnStart = (Button) findViewById(R.id.startBtn);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ServiceManager.startService(getApplicationContext());
}
});
}
}
MyServices.java
package com.test.simpleservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyServices extends Service {
private static final String LOGTAG = "MyServices";
#Override
public void onStart(Intent intent, int startId) {
System.out.println("start...");
//some code of your service starting,such as establish a connection,create a TimerTask or something else
Toast.makeText(this, "service start", Toast.LENGTH_LONG).show();
}
#Nullable
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//this will start service
System.out.println("startcommand...");
Toast.makeText(this, "service startcomand", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
//this will NOT kill service
//super.onDestroy();
Toast.makeText(this, "task destroyed", Toast.LENGTH_LONG).show();
Intent in = new Intent();
in.setAction("PreventKilling");
sendBroadcast(in);
}
#Override
public void onTaskRemoved(Intent intent){
Toast.makeText(this, "task removed", Toast.LENGTH_LONG).show();
intent = new Intent(this, this.getClass());
startService(intent);
}
}
Reciever.java
package com.test.simpleservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class Receiver extends BroadcastReceiver {
private static final String LOGTAG = "Receiver";
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, MyServices.class);
context.startService(serviceIntent);
}
Log.d(LOGTAG, "ServiceDestroy onReceive...");
Log.d(LOGTAG, "action:" + intent.getAction());
Log.d(LOGTAG, "ServiceDestroy auto start service...");
ServiceManager.startService(context);
}
}
ServiceManager
package com.test.simpleservice;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ServiceManager {
private static final String LOGTAG = "ServiceManager";
public static void startService(Context context) {
Log.i(LOGTAG, "ServiceManager.startSerivce()...");
Intent intent = new Intent(MyServices.class.getName());
intent.setPackage("com.test.simpleservice");
context.startService(intent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.simpleservice">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyServices" />
<receiver android:name=".Receiver" >
<intent-filter>
<action android:name="PreventKilling" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.RECIEVE_BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.test.simpleservice.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_btn"
android:id="#+id/startBtn"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
When I run the app and click button "start", the service wont start - no toasts, no logs, nothing in setting->apps->services. Why? Any better way to make unkillable process without anoying notification?
logcat
last few lines becouse that before are just listed services:
01-16 14:10:15.567 13753-13772/com.test.simpleservice I/OpenGLRenderer: Initialized EGL, version 1.4
01-16 14:10:15.567 13753-13772/com.test.simpleservice W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
01-16 14:10:15.587 13753-13772/com.test.simpleservice D/OpenGLRenderer: Enabling debug mode 0
01-16 14:10:17.597 13753-13753/com.test.simpleservice I/ServiceManager: ServiceManager.startSerivce()...
And one more question: will this app start after boot? If not, what did I do wrong?
im sorry for my poor english

Intent intent = new Intent(context, MyServices.class);
intent.setPackage("com.test.simpleservice");
context.startService(intent);
Because your context is:
public static void startService(Context context)
And here :
public void onReceive(Context context, Intent intent)
For above Intent name -> intent

Related

How to open app running in background programmatically

I have an App where a background service running . When a phone call is detected I want that app to open and show me a particular Intent. How should I do this.
My code is
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.lang.reflect.Method;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view){
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener phoneStateListener = new PhoneStateListener(){
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String number = incomingNumber;
Log.d("gaandu", number);
if(state == TelephonyManager.CALL_STATE_RINGING){
Toast.makeText(MainActivity.this, "incoming call from" + incomingNumber, Toast.LENGTH_SHORT).show();
}
if(state == TelephonyManager.CALL_STATE_OFFHOOK){
Toast.makeText(MainActivity.this, "Phone is currently in a call", Toast.LENGTH_SHORT).show();
}
if(state == TelephonyManager.CALL_STATE_IDLE){
Toast.makeText(MainActivity.this, "Phone is neither Ringing nor in a Call", Toast.LENGTH_SHORT).show();
}
}
};
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
public void stopService(View view){
Intent i = new Intent(MainActivity.this, MyService.class);
stopService(i);
}
}
MyService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
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_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.admin.abab">
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService"
android:exported="false"
/>
</application>
</manifest>
In MainActivity.java, after a phone call has been detected, I want to launch my app running in background to open to its first Activity.
You might want to look into the Android cookbook:
You want to act on an incoming phone call and do something with the incoming number.
Solution:
This can be achieved by implementing a Broadcast receiver and listening for a TelephonyManager.ACTION_PHONE_STATE_CHANGED action.
You probably need to do some more research; depending the version of Android you are targeting!
Try this link. hope this will help you. Transparent your activity will help you some what.
Go through this link also
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

unable to start android service from activity that is in the different package

I am new to android stack. I am trying to start android service from the launcher activity. Service and Activity are defined in separate packages but it is not being started. In the logcat there is no exception or error. I have checked many questions on stackoverflow regarding this issue but that didn't worked. Below are the source code of my app. I have spent almost 8 hours on this issue. Any help would be great appreciation.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.test.app">
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".ui.LoginActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".messaging.AlertService"
android:enabled="true"
android:exported="true">
</service>
</application>
</manifest>
AlertService.java:
package nl.test.app.messaging;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class AlertService extends Service {
public AlertService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(), "on create called\n", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
LoginActivity.java
package nl.test.app.ui;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
import nl.test.app.R;
public class LoginActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
// function for service testing
public void onStartButtonClick(View view) {
Intent myIntentToStartAlertListActivity = new Intent();
String pkg = "nl.test.app.messaging";
String cls = "nl.test.app.messaging.AlertService";
myIntentToStartAlertListActivity.setComponent(new ComponentName(pkg, cls));
if (startService(myIntentToStartAlertListActivity) != null) {
Log.i("Service Started","Service started");
Toast.makeText(getApplicationContext(), "Service is running\n", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Service is not running\n", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStop() {
super.onStop();
}
}
Try this
public void onStartButtonClick(View view) {
Intent myIntentToStartAlertListActivity = new Intent(LoginActivity.this, AlertService.class);
if (startService(myIntentToStartAlertListActivity) != null) {
Log.i("Service Started","Service started");
Toast.makeText(getApplicationContext(), "Service is running\n", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Service is not running\n", Toast.LENGTH_LONG).show();
}
}
// function for service testing
public void onStartButtonClick(View view) {
Intent myIntentToStartAlertListActivity = new Intent(LoginActivity.this,AlertService.class);
String pkg = "nl.test.app.messaging";
String cls = "nl.test.app.messaging.AlertService";
myIntentToStartAlertListActivity.setComponent(new ComponentName(pkg, cls));
//startService(myIntentToStartAlertListActivity)
if (startService(myIntentToStartAlertListActivity) != null) {
Log.i("Service Started","Service started");
Toast.makeText(getApplicationContext(), "Service is running\n", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Service is not running\n", Toast.LENGTH_LONG).show();
}
}

Splash screen in Android glitch

I have developed a splash screen in Android which comes for 2 seconds and go to the main activity. The problem is that when I start the application the main activity comes for few milliseconds and then goes to the splash screen activity. Can I know the solution for this?
splashscreen.java
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
public class splashscreen extends Activity {
private static int splashInterval = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
etWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(splashscreen.this, MainActivity.class);
startActivity(i);
this.finish();
}
private void finish() {
// TODO Auto-generated method stub
}
},
splashInterval);
};
}
splashscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >
<ImageView android:src="#drawable/splash" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scaleType="fitXY"/>
<ProgressBar android:id="#+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="58dp" />
</RelativeLayout>
Android Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="asdf.splashtest1" >
<application android:allowBackup="true" android:icon="#drawable/ic_launcher" android:label="#string/app_name" android:theme="#style/AppTheme" >
<!-- Splash screen -->
<activity android:name=".splashscreen" android:label="#string/app_name" android:screenOrientation="portrait" android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Main activity -->
<activity android:name=".MainActivity" android:label="#string/app_name" ></activity>
</application>
</manifest>
//MainActivity.java
package asdf.splashtest1;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
This is my Splash Code Maybe This will helps,
Thread Background = new Thread() {
public void run() {
try {
sleep(2000);
Intent intent = new Intent(splashscreen.this, MainActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
}
};
Background.start();
}
At sleep(2000), enter your desired time in milliseconds.
Edit
private class SplashTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
finish();
Intent intent = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(intent);
}
}
Call This Async with in onCreate Method new SplashTask().execute();

Android NFC not opening correct class on tap

I have an app with 2 classes, I need my app to open the second class CardActivity when the NFC tag tapped/swiped. The app opens fine, but MainActivity is run, instead of CardActivity.
I would hazard a guess that this is an issue with my manifest, but it looks correct. Here it is regardless:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spotsofmagic.spotsofmagic"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<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>
<activity
android:name=".CardActivity"
android:label="#string/app_name" >
<!-- Handle a collectable card NDEF record -->
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<data android:mimeType="application/vnd.spotsofmagic.spotsofmagic"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
I'm confident the tag itself is correct, as I have opened it in another app to view it's contents.
Below are the two classes.
CardActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.bluetooth.*;
public class CardActivity extends Activity implements OnClickListener {
private static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.card_activity);
// see if app was started from a tag and show game console
Intent intent = getIntent();
Log.e(TAG, "Hello world. Intent Type: "+ intent.getType());
if(intent.getType() != null && intent.getType().equals(MimeType.NFC_DEMO)) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
NdefRecord cardRecord = msg.getRecords()[0];
String payload = new String(cardRecord.getPayload());
turnBluetoothOn(payload);
}
}
private void turnBluetoothOn(String payload) {
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Alert Dialog");
builder.setMessage(payload);
builder.setIcon(android.R.drawable.ic_dialog_alert);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
android.os.Process.killProcess(android.os.Process.myPid());
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
MainActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "Activity...";
private NfcAdapter mAdapter;
private TextView mTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// grab our NFC Adapter
mAdapter = NfcAdapter.getDefaultAdapter(this);
// TextView that we'll use to output messages to screen
mTextView = (TextView)findViewById(R.id.text_view);
displayMessage("Loading payload...");
}
private void displayMessage(String message) {
mTextView.setText(message);
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Here is the code I used to write the tag. This is done on a different app incidentally:
NdefRecord appRecord = NdefRecord.createApplicationRecord("com.spotsofmagic.spotsofmagic");
// record that contains our custom "retro console" game data, using custom MIME_TYPE
byte[] payload = getPayload().getBytes();
byte[] mimeBytes = MimeType.NFC_DEMO.getBytes(Charset.forName("US-ASCII"));
NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes,
new byte[0], payload);
NdefMessage message = new NdefMessage(new NdefRecord[] { cardRecord, appRecord});
// Some code here removed for readability
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
ndef.writeNdefMessage(message);
Does the NDEF message on the tag contain an Android Application Record? That could explain how MainActivity is launched. However, that can only be the cause if the AAR is the first record of the NDEF message on the tag or if the first record does not match the intent filter.

Service starts on emulator but on device not

I'am trying to learn how to create services in Android and I've made very simple one.
The problem is that is works like a charm on an AVD but on physical device it is not.
Simply it not starting on boot...
Have a look at the code:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myservice" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name">
<receiver android:name=".ServiceStarter" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name=".MyService" />
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
Service starter:
package com.example.myservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.example.myservice.MyService;
public class ServiceStarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
Intent pushIntent = new Intent(context, MyService.class);
//pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(pushIntent);
}
}
}
and service it self:
package com.example.myservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
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");
}
}
I'am running it on android 4.0.3
You need to add an activity to your application, and the user must launch that activity manually first, before your app will function on Android 3.1+. Until that time, your <receiver> will be ignored. I blogged about this ~9 months ago.

Categories

Resources