MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends WearableActivity {
private TextView mTextView;
private static MainActivity instance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text);
// Enables Always-on
setAmbientEnabled();
final TextView text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (text.getText().toString().equals("Started")) {
text.setText("Stoped");
stopService(new Intent(MainActivity.this,service.class));
} else {
text.setText("Started");
startService(new Intent(MainActivity.this,service.class));
}
}
});
}
public static MainActivity getInstance() {
return instance;
}
public void showToast(String toastMsg){
Toast.makeText(MainActivity.this, toastMsg, Toast.LENGTH_SHORT).show();
}
}
Service.java
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.MainThread;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class service extends Service {
private boolean started = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("serviceTest", "Service started by user.");
start();
return START_STICKY;
}
#Override
public void onDestroy() {
//Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
Log.i("serviceTest", "Service destroyed by user.");
stop();
super.onDestroy();
}
private Timer timer;
private TimerTask timerTask = new TimerTask() {
#Override
public void run() {
if(started) {
start();
}
Log.i("serviceTest", "ServiceCalled!");
}
};
public void start() {
if(timer != null) {
return;
}
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 0, 10000);
}
public void stop() {
timer.cancel();
timer = null;
}
}
The code runs okay for about 13 or 14 times (i.e. the timer keeps on running for about 13 or 14 times) but suddenly the service stops and onDestroy is called.
Also, during debugging, I have noticed one strange condition: If I delete/comment the onDestroy() method form the code then the service runs always. It never closes on its own. (it only closes upon user input, which is fine)
Please suggest a solution so that the services do not get killed/ destroyed. Or if the OS/ System kills it, then the service starts again on its own.
Thnx
You will have to turn that background service into a foreground service, because of the limitations called Background Execution Limits that started from android Oreo.
Please check out this link for more better understanding: https://developer.android.com/about/versions/oreo/background
Related
This is my first time using the stackoverflow
I am creating a chat program but only coding the broadcast receiver and receiving message notification left. I created an exampleapp for my intent but it only works when app is open. How can i simply create a broadcast receiver?
I am not getting error
My MainActivity:
package com.example.backgroundservice;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Toast;
import com.example.backgroundservice.R;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, BackgroundService.class));
Toast.makeText(this, "Intent Başladı!", Toast.LENGTH_LONG).show();
}
}
(I did not added my other codes because i am getting error and i can not solve because i am coding on android)
My Intent:
import android.app.Service;
import android.content.*;
import android.os.*;
import android.widget.Toast;
public class BackgroundService extends Service {
public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
handler = new Handler();
runnable = new Runnable() {
public void run() {
Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show();
handler.postDelayed(runnable, 10000);
}
};
handler.postDelayed(runnable, 15000);
}
#Override
public void onDestroy() {
/* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
//handler.removeCallbacks(runnable);
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
}
}```
So, I am creating an AI music player app. Everything seems fine but whenever I give it some voice command, it does not display the required message.
I have tried using different emulators and using different android versions. None of those worked.
package com.learning.intelligentmusicplayer;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private RelativeLayout parentRelativeLayout;
private SpeechRecognizer speechRecognizer;
private Intent speechRecogniserIntent;
private String keeper="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkVoiceCommandPermission();
parentRelativeLayout = findViewById(R.id.parentRelativeLayout);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(MainActivity.this);
speechRecogniserIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecogniserIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM );
speechRecogniserIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> matchesFound = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matchesFound!=null)
{
keeper = matchesFound.get(0);
Toast.makeText(MainActivity.this, "Result = "+keeper, Toast.LENGTH_LONG).show();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
parentRelativeLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch(motionEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
speechRecognizer.startListening(speechRecogniserIntent);
keeper="";
break;
case MotionEvent.ACTION_UP:
speechRecognizer.stopListening();
break;
}
return false;
}
});
}
private void checkVoiceCommandPermission()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(!(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO)==PackageManager.PERMISSION_GRANTED))
{
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package: "+getPackageName()));
startActivity(intent);
finish();
}
}
}
}
There is no error message. I hear the beep sound for recording message but it does not display the message on screen.
Downloading Google voice assistant fixed my problem!
I am using the following code with IOIO to act as a motion detector, the problem is the IOIO is disconnected whenever my phone screen goes off! I do not want the screen to stay on all the time to keep the IOIO connected!
any solution please?
package com.LookHin.ioio_pir_motion_sensor;
import ioio.lib.api.AnalogInput;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends IOIOActivity {
private ToggleButton toggleButton1;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_about:
//Toast.makeText(getApplicationContext(), "Show About", Toast.LENGTH_SHORT).show();
Intent about = new Intent(this, AboutActivity.class);
startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class Looper extends BaseIOIOLooper {
private DigitalOutput digital_led0;
private AnalogInput deigital_input;
int i = 0;
private float InputStatus;
#Override
protected void setup() throws ConnectionLostException {
digital_led0 = ioio_.openDigitalOutput(0,true);
deigital_input = ioio_.openAnalogInput(45);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "IOIO Connect", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void loop() throws ConnectionLostException {
try{
digital_led0.write(!toggleButton1.isChecked());
InputStatus = deigital_input.getVoltage();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView1.setText(String.format("%.02f",InputStatus)+" v.");
if(InputStatus >= 3.0){
textView1.setBackgroundColor(Color.RED);
if (i == 0){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
i = 1;
};
}else{
textView1.setBackgroundColor(Color.TRANSPARENT);
i = 0;
}
}
});
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
}
Option 1) Lock the screen so it always stays awake
public void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Option 2) Fix your response to onPause().
When the screen goes off the onPause() method is called and you should handle it as otherwise your activity will be closed.
#Override
protected void onPause() {
// Your code
super.onPause();
}
The onPause() normally calls the ioio.disconnect() so this should be overrode.
IOIOService let´s you run your code on the background even if application goes to the background.
Hi I want to set alarm notification when the mobile screen is off. My code is'
package com.my.timeout;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class ScreenON_OFF_ACTIVITY extends Activity
{
AlarmManager am;
private static final int REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
onCreate1();
}
public void onCreate1() {
// initialize receiver
System.out.println("onCreate1 ");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
System.out.println("onCreate ");
}
#Override
protected void onPause() {
// when the screen is about to turn off
if (ScreenReceiver.screenOff) {
// this is the case when onPause() is called by the system due to a screen state change
System.out.println("SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
System.out.println("this is when onPause() is called when the screen state has not changed ");
display_alarm();
}
super.onPause();
}
#Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.screenOff) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
System.out.println(" this is when onResume() is called when the screen state has not changed ");
}
super.onResume();
}
}
ScreenReceiver.java
package com.my.timeout;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ScreenReceiver extends BroadcastReceiver
{
public static boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("onReceive ");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
System.out.println("SCREEN TURNED OFF on BroadcastReceiver");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
System.out.println("SCREEN TURNED ON on BroadcastReceiver");
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
UpdateService.java
package com.my.timeout;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class UpdateService extends Service {
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
System.out.println("Screen is off");
} else {
System.out.println("Screen is on");
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Now i want to set alarm when the screen has been go off. How can i do this.Can anybody tell me? thanks in advance.
My 'game' keeps crashing after I resume it. Basically, I launch the app and everything works. Then I press the home button and go back to my home screen. Still all the normal stuff. But THEN when I open the app back up, it just freezes and after 1 minute or so, I get a not responding message.
Here is my main activity:
package com.amzoft.android.starraider;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
public class StarRaiderMain extends Activity implements OnTouchListener, OnKeyListener, SensorEventListener{
FastRenderView renderView;
SensorManager sensorManager;
Sensor accelerometer;
Thread mainGameThread;
Player player;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
renderView = new FastRenderView(this);
renderView.setOnKeyListener(this);
renderView.setFocusableInTouchMode(true);
renderView.requestFocus();
setContentView(renderView);
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
mainGameThread = new Thread(new mainGameThread());
player = new Player(this);
}
#Override
protected void onResume()
{
super.onResume();
renderView.resume();
renderView.requestFocus();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause()
{
super.onPause();
renderView.pause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
#Override
public void onSensorChanged(SensorEvent event)
{
player.onSensorChanged(event);
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
player.onKey(v, keyCode, event);
return true;
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
class FastRenderView extends SurfaceView implements Runnable
{
Thread renderThread = null;
SurfaceHolder holder;
volatile boolean running = false;
public FastRenderView(Context context)
{
super(context);
holder = getHolder();
}
public void resume()
{
running = true;
renderThread = new Thread(this);
renderThread.start();
}
public void pause()
{
running = false;
while(true)
{
try{
renderThread.join();
}catch(InterruptedException e){
Log.d("StarRaider", e.getMessage());
}
}
}
#Override
public void run()
{
while(running)
{
if(!holder.getSurface().isValid())
continue;
Canvas canvas = holder.lockCanvas();
onDraw(canvas);
holder.unlockCanvasAndPost(canvas);
}
}
public void onDraw(Canvas canvas)
{
canvas.drawRGB(255, 255, 255);
player.onDraw(canvas);
}
}
class mainGameThread extends Thread
{
mainGameThread()
{
super("mainGameThread");
start();
}
public void run()
{
try{
player.onUpdate();
}catch(Exception e){
}
}
}
}
Any help would be greatly appreciated.
Here is my logcat output: http://pastebin.com/3b09YAkP
I have a main game thread, because I read that if the render thread gets stuck for 2 seconds, it crashes.
It looks like it might be one of two things.
You should probably be explicitly pausing your thread in onPause(). That might cause application deadlock if it tries to resume without having been paused.
You should also take a look at the Google I/O presentation on Replica Island. It's about an hour long. Take note of the part where he talks about garbage collection. This might be what's happening and causing your app to crash because of an ANR error.
I hope this helps!
May be related to this bug http://code.google.com/p/android/issues/detail?id=2566