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);
Related
i want when boot run app server allow for receive message any time
without showing application
this code problem when boot show Notification twice only
but i want receive message any time
Is this "android:exported" important, What used
code AndroidManifest
<service
android:name=".appService"
android:exported="true"
android:enabled="true">
</service>
<receiver
android:name=".ServiceStarterBoot"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
code BroadcastReceiver
public class ServiceStarterBoot extends BroadcastReceiver {
private Context context ;
#Override
public void onReceive(Context context1, Intent intent) {
this.context = context1;
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceLauncher = new Intent(context, appService.class);
context.startService(serviceLauncher);
}}
code Service
public class appService extends Service {
#Override
public void onCreate() {
super.onCreate();
lood();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
//return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
private void lood(){
SystemClock.sleep(3000);
Runnable runnable = new Runnable() {
public void run() {
boolean p= true ;
while(p) {
SystemClock.sleep(5000);
showNotification();
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
please help
thanks
you have to make your service sticky:
Service.START_STICKY
then it is infinite and restarts itself when killed by OS for any reason.
It even starts itself when booting OS and app is NOT opened by user.
Best regards.
pseudo code:
onStartCommand(..){
...
//e.g. wifilisterner
Wifilistener WF = new Wifilistener(Interface yourInterfaceCallBackMethod);
}
something like this.
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 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);
i'm a java noob, so sorry for the noob question...
i have a checkbox that is supposed to fire off a service when checked - kill it when unchecked.
the "attempting..." toast pops up as expected, but the services does not seem to be starting and does not present toast..
here are my mainifest entries, main activity code (abbridged), and the service code:
// manifest entries
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name" >
<activity android:name=".MainMenu" 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=".PPS" android:process=":remote" android:label="#string/service_name" />
</application>
// MainMenu.java
final CheckBox checkBoxStartService = (CheckBox) findViewById(R.id.checkBoxEnable);
checkBoxStartService.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (checkBoxStartService.isChecked() == true)
{ // make toast
Toast toaster = Toast.makeText(MainMenu.this, "attempting to start service...", 500);
toaster.setGravity(Gravity.CENTER, 0, -200);
toaster.show();
Intent startPPS = new Intent();
startPPS.putExtra("com.domain.notlaunchingservice.PPS", false);
startService(startPPS);
}
if (checkBoxStartService.isChecked() == false)
{
Intent closePPS = new Intent();
closePPS.putExtra("com.domain.notlaunchingservice.PPS", true);
stopService(closePPS);
}
}
};
// PPS.java
package com.domain.notlaunchingservice;
import android.app.Service;
import android.view.Gravity;
import android.widget.Toast;
public abstract class PPS extends Service
{
#Override
public void onCreate()
{
Toast toasty = Toast.makeText(PPS.this, "service created!", 500);
toasty.setGravity(Gravity.CENTER, 0, 200);
toasty.show();
};
public void onDestroy()
{
Toast toasted = Toast.makeText(PPS.this, "service destroyed!", 500);
toasted.setGravity(Gravity.CENTER, 0, -200);
toasted.show();
};
};
i have also tried to call the service using:
startService(new Intent(MainMenu.this, PPS.class));
this returns an error on the emulator saying the app quit unexpectedly and i click force close, but the main activity doesn't close, so i'm assuming it's the service that i am force closing.
below is the DDMS output:
java.lang.RuntimeException: Unable to instantiate service com.domain.notlaunchingservice.PPS
i don't care how i get the service started, as long as it can load a SQL base and continue recording audio to a file after the main activity loses focus or is closed.
this will be a free app on the market when finished, so your help will be appreciated by many when the project is ready for prime time.
thanks for reading
One problem is that the intent you use to start and stop the service only specifies an extra.
Intent startPPS = new Intent();
should be
Intent startPPS = new Intent(this, PPS.class);
But there are other problems as well (I don't think your example compiles), I would recommend you to look at the example at http://developer.android.com/guide/topics/fundamentals/services.html#ExtendingIntentService
Edit: (example code below)
public class StartedService extends Service {
#Override
public IBinder onBind(Intent intent) {
// I guess that you don't want to bind to the service
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service is running", Toast.LENGTH_SHORT).show();
// Return sticky if you want it to be restarted in a low memory
// situation
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service is going down", Toast.LENGTH_SHORT).show();
}
}
public class ClientActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startButton = (Button)findViewById(R.id.start_button);
startButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
startService(new Intent(ClientActivity.this, StartedService.class));
}
});
Button stopButton = (Button)findViewById(R.id.stop_button);
stopButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
stopService(new Intent(ClientActivity.this, StartedService.class));
}
});
}
}
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>