I am trying to making lock screen so I made Service class n inside it broadcastReceiver, and MainActivity.
its working till screen is off, whn screen is went on that time main activity close and showing exception.
Please help me to solve it.
MyService.java
package com.example.broadcast_receiver;
import android.app.Service;
...
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i("[myService]", "onCreate");
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.i("[myService]", "onStart");
}
#Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.i("[myService]", "onDestroy");
}
BroadcastReceiver mybroadcast = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
Intent i=new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
context.startActivity(i);
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
}
MainActivity.java
package com.example.broadcast_receiver;
import android.os.Bundle;
...
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("[MainActivity]", "Created");
try{
boolean a=isMyServiceRunning();
if(a==false){
startService(new Intent(this,MyService.class));
}
}catch (Exception e) {
// TODO: handle exception
Log.i("Error", e.getMessage().toString());
Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
AndroidManifest.xml
(No User Permission added)
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name="com.example.broadcast_receiver.MyService"
android:label="#string/app_name"
android:icon="#drawable/ic_launcher" ></service>
<activity
android:name="com.example.broadcast_receiver.MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Please help me to solve dis problem.
The error is telling you that you can't call startActivity() from outside of a Activity without setting the Intent flag NEW_TASK. Add Intent.FLAG_ACTIVITY_NEW_TASK TO YOUR Intent before calling startActivity()
Intent i=new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Related
I am new android I want to implement in my that when I press power button I need to open the app but the app is killed in the background from recent app tray. I am trying all the solutions which I got but I didnt get solution
MainActivity.class
public class MainActivity extends ActionBarActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
setContentView(R.layout.activity_main);
/*Toast.makeText(getApplicationContext(),"main Activity run",Toast.LENGTH_SHORT).show();
intent = new Intent(new Intent(getBaseContext(), PowerService.class));
startService(intent);*/
// /* new Handler().post(new Runnable() {
// #Override
// public void run() {
Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
startService(intent);
// }
// });
//*/
// Intent notificationIntent = new Intent(this, PowerService.class);
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
//
//
//
}
#Override
protected void onStart() {
Toast.makeText(getApplicationContext(),"inside mainactivity onStart",Toast.LENGTH_SHORT).show();
super.onStart();
}
#Override
protected void onResume() {
Toast.makeText(getApplicationContext(),"inside mainactivity onResume",Toast.LENGTH_SHORT).show();
super.onResume();
}
#Override
protected void onRestart() {
Toast.makeText(getApplicationContext(),"inside mainactivity onRestart",Toast.LENGTH_SHORT).show();
super.onRestart();
}
#Override
protected void onDestroy() {
Toast.makeText(getApplicationContext(),"inside mainactivity onDestroy",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
protected void onStop() {
Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
startService(intent);
Toast.makeText(getApplicationContext(),"inside mainactivity onStop",Toast.LENGTH_SHORT).show();
super.onStop();
}
}
Service.class
public class PowerService extends Service {
BroadcastReceiver mReceiver;
IntentFilter filter;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock cpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
cpuWakeLock.acquire();
registerReciver();
return Service.START_STICKY;
}
public class LocalBinder extends Binder {
PowerService getService() {
return PowerService.this;
}
}
#Override
public boolean onUnbind(Intent intent) {
System.out.println("inside powerservice onUnbind");
Toast.makeText(getApplicationContext(),"inside powerservice onUnbind",Toast.LENGTH_SHORT).show();
return super.onUnbind(intent);
}
#Override
public void onRebind(Intent intent) {
System.out.println("inside powerservice onRebind");
Toast.makeText(getApplicationContext(),"inside powerservice onRebind",Toast.LENGTH_SHORT).show();
super.onRebind(intent);
}
#Override
public void onStart(Intent intent, int startId) {
System.out.println("inside powerservice onStart");
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
//unregisterReceiver(mReceiver);
//registerReciver();
System.out.println("inside powerservice onDestroy");
Toast.makeText(getApplicationContext(),"inside powerservice ondestroy",Toast.LENGTH_SHORT).show();
startService(new Intent(this, PowerService.class));
super.onDestroy();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
/*registerReciver();
startService(new Intent(this,PowerService.class));*/
Toast.makeText(getApplicationContext(),"inside powerservice onTaskRemoved",Toast.LENGTH_SHORT).show();
/*Intent broadcastIntent = new Intent(this,AppReciever.class);
sendBroadcast(broadcastIntent);
super.onTaskRemoved(rootIntent);*/
/* Intent restartServiceTask = new Intent(this,PowerService.class);
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
startService(new Intent(this,PowerService.class));*/
super.onTaskRemoved(rootIntent);
}
public void registerReciver()
{
filter= new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_LOCKED_BOOT_COMPLETED);
mReceiver = new AppReciever();
registerReceiver(mReceiver, filter);
}
}
BroadcastReciever
public class AppReciever extends BroadcastReceiver {
public static boolean wasScreenOn = true;
public void onReceive(final Context context, final Intent intent) {
Log.e("LOB", "onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
Toast.makeText(context,"inside ACTION_SCREEN_OFF",Toast.LENGTH_SHORT).show();
//Log.e("LOB","wasScreenOn"+wasScreenOn);
Log.e("Screen ", "shutdown now");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.e("Screen ", "awaked now");
Toast.makeText(context,"inside ACTION_SCREEN_ON",Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.e("LOB", "userpresent");
Toast.makeText(context,"inside ACTION_USER_PRESENT",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(ii);
wasScreenOn = true;
// Log.e("LOB","wasScreenOn"+wasScreenOn);
}
else if(intent.getAction().equals(Intent.ACTION_LOCKED_BOOT_COMPLETED))
{
Toast.makeText(context,"inside ACTION_LOCKED_BOOT_COMPLETED",Toast.LENGTH_SHORT).show();
Log.e("LOB", "userpresent");
Intent ii = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(ii);
}
/* Log.v("##%#%#", "Power button is pressed.");
Toast.makeText(context, "power button clicked",Toast.LENGTH_LONG).show();*/
}
}
Manifestfile
package="com.benayah.app.sampleapp">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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=".PowerService"
android:enabled="true"
android:exported="false"
android:stopWithTask="false"
android:process=":my_process"
>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
</service>
</application>
Please let me know where I am going wrong in my code and I need to run the service in background to check for the screen on even after the app is killed in background because now when I killed app I couldn't restart my app but if I didn't kill the it is working fine
Use following might be helpfull...
***in Manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent= new Intent(context, ActivitySample.class);
context.startActivity(intent);
}
}
You below might be helpfull...
In Manifest
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
public class MyReceiver extends BroadcastReceiver {
static int countPowerOff=0;
private Activity activity=null;
public MyReceiver (Activity activity)
{
this.activity=activity;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.v("onReceive", "Power button is pressed.");
Toast.makeText(context, "power button clicked", Toast.LENGTH_LONG)
.show();
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
countPowerOff++;
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
if(countPowerOff==5)
{
Intent i =new Intent(activity,NewActivity.class);
activity.startActivity(i);
}
}
}
And,
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
MyReceiver mReceiver = new MyReceiver (this);
registerReceiver(mReceiver, filter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The only way i know to monitor the power button is by listening to the ScreenOn and ScreenOff events. So you can try to write a service that is listening to ScreenOn or ScreenOff and then each time that this event is firing you can launch the desired app.
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, ScreenOnOffService.class);
startService(intent);
}
}
Service:
public class ScreenOnOffService extends Service {
private ScreenOnOffReceiver mScreenReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
registerScreenStatusReceiver();
}
#Override
public void onDestroy() {
unregisterScreenStatusReceiver();
}
private void registerScreenStatusReceiver() {
mScreenReceiver = new ScreenOnOffReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(mScreenReceiver, filter);
}
private void unregisterScreenStatusReceiver() {
try {
if (mScreenReceiver != null) {
unregisterReceiver(mScreenReceiver);
}
} catch (IllegalArgumentException e) {}
}
}
Manifest:
<service android:name="com.benayah.app.sampleapp.ScreenOnOffService" />
BroadcastReceiver:
(here you need to put the package name of the app that you want to launch)
in my example i put your package name: com.benayah.app.sampleapp
public class ScreenOnOffReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.d("StackOverflow", "Screen Off");
startApp(context);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d("StackOverflow", "Screen On");
startApp(context);
}
}
private void startApp(Context context) {
PackageManager pm = context.getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage("com.benayah.app.sampleapp");
context.startActivity(launchIntent);
}
}
When I run my app in an emulator and kill the process, my service gets started and runs in the background (Toast: "Service Called") BUT it does not get called at all on a real device and no logcat runs because the broadcast receiver or my service does not get called:
MainFest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Service -->
<service android:name=".MyService">
<intent-filter>
<action android:name="com.mypackage.myapp.MyService" />
</intent-filter>
</service>
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="true"
android:label="BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<!-- Service -->
MainActivity:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
//TODO your background code
Intent i = new Intent(MainActivity.this, PushNotification.class);
startActivity(i);
}
});
PushNotification.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = this;
if (!isMyServiceRunning()){
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent);
finish();
}
else
{
finish();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
BootReceiver:
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent);
}
}
}
MyService:
public class MyService extends Service {
Handler handler;
#Override
public int onStartCommand(Intent intent, int flags, int startId){
// START YOUR TASKS
Toast.makeText(MyService.this, "Service Called", Toast.LENGTH_SHORT).show();
Context context = this;
Intent in = new Intent(context, FragmentMain.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.putExtra("valuerunInBG", "1");
context.startActivity(in);;
//loop();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// STOP YOUR TASKS
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
Modify your manifest as given below
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="true"
android:label="BootReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
I made a small change in it just given the priority by which it will start as early as possible
also change the code given below
#Override
public int onStartCommand(Intent intent, int flags, int startId){
// START YOUR TASKS
Toast.makeText(MyService.this, "Service Called", Toast.LENGTH_SHORT).show();
Context context = this;
Intent in = new Intent(context, FragmentMain.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.putExtra("valuerunInBG", "1");
context.startActivity(in);;
//loop();
return START_STICKY; //THIS WILL RESTART YOUR SERVICE IF IT GETS STOPPED BY ANDROID OS DUE TO LOW MEMORY
}
android.intent.action.BOOT_COMPLETED Takes time after your device starts, try waiting 3-4 minutes
Start your service again in your service class's onDestroy() method. This way when your application will be closed, then onDestroy() will be called and that will start your service again.
Some time Toast does not work inside of Service so please use Log to know whether your code is running or not.
I am creating a notification and I add "addAction" to my notification.
I want to when I click on the "addAction", the notification remove and run another one code.
How I can do this?
Intent intent = new Intent(context, Activity.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
.........
.addAction(R.drawable.eye, "View", pi)
I want to run Activity.class in background, I mean to that this activity doenst open but the code in this activity run.
How I can do this?
If you want to run code in background, You have to create a service
ex
service code
package com.javatechig.serviceexample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class HelloService extends Service {
private static final String TAG = "HelloService";
private boolean isRunning = false;
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
isRunning = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
#Override
public void run() {
//Your logic that service will perform will be placed here
//In this example we are just looping and waits for 1000 milliseconds in each loop.
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
if(isRunning){
Log.i(TAG, "Service running");
}
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javatechig.serviceexample" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HelloActivity"
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 declared in manifest -->
<service android:name=".HelloService"
android:exported="false"/>
</application>
</manifest>
To start the servcie , add below code to the activity
Intent intent = new Intent(this, HelloService.class);
startService(intent);
I am currently working on an android project and I am trying to start a service and when the service has started running some code to initialise some stuff.
Below is the code I am using for the service.
Context context;
PowerManager.WakeLock wakeLock;
public PowerDetectionService(Context context)
{
this.context = context;
}
public PowerDetectionService()
{}
public void onCreate()
{
super.onCreate();
PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
}
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void receivedPowerConnected()
{
try
{
Toast.makeText(context, "Power connected", Toast.LENGTH_LONG).show();
wakeLock.acquire();
}
catch (Exception ex)
{
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
}
public void receivedPowerDisconnected()
{
try
{
Toast.makeText(context, "Power disconnected", Toast.LENGTH_LONG).show();
wakeLock.release();
}
catch (Exception ex)
{
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
}
The wake lock is always null as that bit of code never gets executed in the oncreate or onstart. I've tried putting it in the bind function but still no joy.
When I go into the android settings I can see that my app has the service running but I need that code to be initialised before anything would work.
Thanks for any help you can provide.
UPDATE
I've discovered that the functions are being called thanks to the previous comment. For some reason the debugger doesn't get fired.
Below is the code that shows how to create the server as requested.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(this);
}
public void onResume()
{
super.onResume();
startService(this);
}
private void startService(Context context)
{
Intent service = new Intent(context, PowerDetectionService.class);
context.startService(service);
}
UPDATE 2
As requested below is all the code that starts the service and performs the wake lock.
Below is the main activity that starts the service
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StartPowerService(this);
//getActionBar().setDisplayHomeAsUpEnabled(true);
}
public void onResume()
{
super.onResume();
StartPowerService(this);
}
private void StartPowerService(Context context)
{
Intent service = new Intent(context, PowerDetectionService.class);
startService(service);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//case android.R.id.home:
// NavUtils.navigateUpFromSameTask(this);
// return true;
}
return super.onOptionsItemSelected(item);
}
}
Below is the class for the service
public class PowerDetectionService extends Service {
Context context;
PowerManager.WakeLock wakeLock;
public PowerDetectionService(Context context)
{
this.context = context;
}
public PowerDetectionService()
{}
public void onCreate()
{
super.onCreate();
Log.d("SERVICE", "ON CREATE CALLED");
PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
}
public int OnStartCommand(Intent intent, int flags, int startId)
{
Log.d("SERVICE", "ONSTARTCOMMAND Called");
PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
return START_STICKY;
}
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Log.d("SERVICE", "ON START CALLED");
PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void receivedPowerConnected()
{
try
{
Toast.makeText(context, "Power connected", Toast.LENGTH_LONG).show();
wakeLock.acquire();
}
catch (Exception ex)
{
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
}
public void receivedPowerDisconnected()
{
try
{
Toast.makeText(context, "Power disconnected", Toast.LENGTH_LONG).show();
wakeLock.release();
}
catch (Exception ex)
{
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
And below is the mainfest file.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.BoardiesITSolutions.ScreeenStay"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>
<service android:name="PowerDetectionService"
android:process=":ScreenStay"
android:icon="#drawable/ic_launcher"
android:label="Screen Stay">
</service>
<receiver android:name="BroadcastReceiveDetection">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
</application>
</manifest>
Hope this helps.
You are starting service in different process.
<service android:name="PowerDetectionService"
android:process=":ScreenStay"
android:icon="#drawable/ic_launcher"
android:label="Screen Stay">
The debugger is attached to your main process. When the new one starts, it has no debugger attached, so it will ignore your breakpoints. If you want to debug remote process, you can do it via Eclipse in DDMS perspective. Under devices, you can see its processes. Then you can select one and press debug selected process (green bug icon). This is also useful when you only want to start debugging your app at some point.
As for debugging onCreate(), you have to attach debugger after the process started, but before onCreate() is called. You can for example put some Thread.sleep() in the beginning of onCreate() for few seconds so you can attach debugger.
Which class are you extending? Service?
The method onStart() is only used for old Android versions (<2.0). For more recent versions you should use onStartCommand() as bellow:
#Override
public int onStartCommand(Intent intent, int flags, int startId)
And you need to return START_STICKY from the method above if you want the service to keeps running after executing the code. If service is not kept alive the PowerManager.FULL_WAKE_LOCK will be released. Probably you can also get away making wakeLock static.
To start service use:
Intent i=new Intent(this, PowerDetectionService.class);
startService(i);
--EDITED--
As per the topic here: getApplication() vs. getApplicationContext() you may get different Context object when getting the context using getApplicationContext(). Try change the following line:
PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
by:
PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
regrads.
Just a note :
onStart() method is deprecated, and you should use onStartCommand() instead (which will be called only if you start your service with Context.startService().
However, onCreate() should called if your service does run (but only once).
I'm trying to use this very simple Service and BroadcastReceiver but I'm getting a
ClassNotFound exception. If I don't use startService things are fine so the problem it's with the receiver. I have registered it in the android manifest file so why do I get the ClassNotFound exception?
I will be using this method of communication for polling a php file and updating a ListView. Is this the appropriate way of communicating (broadcast intent)?
public class MessengerServiceActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this,MessengerService.class));
}
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle b=intent.getExtras();
if(b==null)
return;
String msg=b.getString("message");
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText(msg);
}
}
}
public class MessengerService extends Service {
HttpClient hc;
HttpPost hp;
String s[]={"pratik","harsha","dayal","hritika"};
public MessengerService() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
hc=new DefaultHttpClient();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t=new Thread(new Runnable(){
public void run()
{
int k=0;
while(true)
{
Intent i=new Intent("com.pdd.messenger.MyAction");
i.putExtra("message",s[k]);
sendBroadcast(i);
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG)
.show();
}
k=(k+1)%4;
}
}
});
t.start();
return super.onStartCommand(intent, flags, startId);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pdd.messenger"
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=".MessengerServiceActivity"
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=".MyReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.pdd.messenger.MyAction"/>
</intent-filter>
</receiver>
<service android:name=".MessengerService"></service>
</application>
</manifest>