Android service not running
My application follows the following scripts ...
1.[Main Activity]
- re-sleep stream (5000)
- if thread is sleep (), startService ()
2.[Service.class] sendBroadcast()
3.[Main Activity - BroadcastReceiver] Toast()
the thread runs clean, but the service is not called.
I am registering with Manifest.xml
And I am creating a BroadcastReceiver dynamic.
manifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/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>
<service android:name=".Service"
android:enabled="true" />
</application>
MainActivity.java
public class MainActivity extends ActionBarActivity implements Runnable {
Thread mThread;
Boolean mSleep = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Activity", "onCreate()");
}
@Override
protected void onStart() {
super.onStart();
Log.d("Activity", "onStart()");
mThread = new Thread(this);
mThread.start();
}
@Override
public void run() {
Log.d("Thread", "run()");
while(true) {
try {
mThread.sleep(5000);
} catch (InterruptedException e) {
//empty
}
Log.d("Thread", "sleep");
mSleep = true;
Log.d("Thread1", mSleep.toString());
Context context = getApplicationContext();
context.startService(new Intent(MainActivity.this, Service.class));
mSleep = false;
Log.d("Thread2", mSleep.toString());
}
}
@Override
protected void onResume() {
super.onResume();
Log.d("Activity", "onResume()");
Log.d("Is it main thread?", mThread.currentThread().getName());
IntentFilter filter = new IntentFilter();
//No Action
registerReceiver(mBroadcastReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
Log.d("Activity", "onPause()");
unregisterReceiver(mBroadcastReceiver);
}
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "sleep sleep sleep", Toast.LENGTH_SHORT).show();
}
};
}
Service.class
public class Service extends android.app.Service {
@Override
public void onCreate() {
super.onCreate();
Log.d("Service", "onCreate()");
Intent intent = new Intent();
sendBroadcast(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
sendBroadcast(intent);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
Log.d("Service", "onBind()");
return null;
}
}
+3
source to share