want to have sound when the app is installed - android

I want to have a sound when my application is installed. I tried this by using broadcastreciever in my application. In the broadcast reciever iam running a service to start media player. But iam not able to get into on recieve method of the broadcast reciever. but if i try to install another app iam getting the event. how to get the event in my app only.
My permissions in manifest file
<uses-permission android:name = "android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.RESTART_PACKAGES"/>
<receiver android:name=".DemoReceiver" >
<intent-filter >
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_INSTALL" />
<action android:name="android.intent.action.PACKAGE_CHANGED" />
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
<action android:name="android.intent.action.PACKAGE_REPLACED"/>
<action android:name="android.intent.action.USER_PRESENT"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
and in the broadcast reciever
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class DemoReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent bootintent) {
System.out.println("entered broadcast receiver");
if(bootintent.getAction() != null)
{
context.startService(new Intent(context, DemoService.class));
}
}
}
and the service is
public class DemoService extends Service {
MediaPlayer player;
private class LogTask extends TimerTask {
public void run() {
Log.i(LOGTAG, "scheduled");
}
}
private LogTask mLogTask;
#Override
public IBinder onBind(final Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.v("StartServiceAtBoot", "StartAtBootService Created");
player=MediaPlayer.create(this, R.raw.sirensound);
player.setLooping(false);
}
public void onStart(Intent intent, int flags, int startId) {
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
player.start();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v("StartServiceAtBoot", "StartAtBootService Destroyed");
}
}

If you want to execute any code from your app , it has to be already installed , so I think..you cannot receive broadcast from your app when your app is installed.

in my application I managed to create sound when a user shakes the device while my application is running....
public class SensorTest extends Activity implements SensorEventListener,
OnCompletionListener {
private SensorManager sensorManager;
private boolean color = false;
private long lastUpdate;
private MediaPlayer mMediaplayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
lastUpdate = System.currentTimeMillis();
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float[] values = event.values;
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 2) //
{
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
if (color) {
} else {
try {
AssetFileDescriptor afd = getAssets().openFd(
"gavel_single.wav");
mMediaplayer = new MediaPlayer();
mMediaplayer.setDataSource(afd.getFileDescriptor(), afd
.getStartOffset(), afd.getLength());
afd.close();
mMediaplayer.prepare();
mMediaplayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
sensorManager.registerListener(this, sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
// unregister listener
sensorManager.unregisterListener(this);
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mMediaplayer != null) {
mMediaplayer.release();
mMediaplayer = null;
}
}
public void onCompletion(MediaPlayer mp) {
mp.seekTo(0);
mp.release();
}
}

You cannot do this on a standard Android platform, at least when distributing from a normal source (you might be able to do something by opening a web page with javascript and a link to the apk on your own server, but the users would have to enable "unkown sources" in their settings first)
You can, however, play a sound on first run. But an install only becomes a run if the user clicks "open" from the installer or launches it from the home screen, etc.

Related

creating android service for simple radio

I've been reading a while and all about services, I'm not all in dev, I'm new to this stuff and wanna learn, as a test I'm trying to make an online radio stream app. I already made it and it works perfect, my only problem is I can't seem to find the way to make the services work or how to do so, I know most of you all are great devs on android and all but just looking for a teacher or someone willing to show me how
this is my code:
public class MainActivity extends AppCompatActivity
{
Button b_play1;
MediaPlayer mediaPlayer;
boolean prepared;
String stream = "http://73.160.214.181:8000/stream";
private boolean started;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, mServices.class));
b_play1 = (Button) findViewById(R.id.play1);
b_play1.setEnabled(false);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
if (started) {
started = false;
mediaPlayer.pause();
b_play1.setBackground(getDrawable(play));
} else {
started = true;
mediaPlayer.start();
b_play1.setBackground(getDrawable(pause));
}
}
});
}
#Override
protected void onPause()
{
super.onPause();
if(started){
mediaPlayer.pause();
}
}
#Override
protected void onResume()
{
super.onResume();
if(started){
mediaPlayer.start();
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if(prepared){
mediaPlayer.release();
}
}
class PlayerTask extends AsyncTask<String, Void, Boolean>
{
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
b_play1.setEnabled(true);
}
}}
I wrote an Android audio chapter in my book, and in it I present an app that plays music using a background service.
So here I am going to summarize it and slightly adapt it using your code to show how you should be able to stream from background service. Instead of using the Async task in your Activity, your are going to have a mainActivity that binds to a Service that does the streaming.
First, you need to define the service in your manifest: (obviously use your package name, not mine shown below)
<application
<service
android:name="com.wickham.android.musicservice.MusicService"
android:label="Music Service"
android:enabled="true">
</service>
Then, you need to bind your Activity to the service. The Activity can be used to control the service, such as starting and stopping the stream: (the following code block go in your Main Activity, that is where you have everything now)
// Bind the Service
bindService(new Intent(this,MusicService.class), Scon,Context.BIND_AUTO_CREATE);
// Connect to Service
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicService.ServiceBinder)binder).getServiceInstance();}
// Start the service
Intent music = new Intent();
music.setClass(this,MusicService.class);
startService(music);
// Controlling the service
mServ.resumeMusic();
mServ.pauseMusic();
Then, in your service class that will be doing the actual streaming, you can implement it like this: (I did not include the two methods called resumeMusic() and pauseMusic(), but those go in the service and do basically what you had already in your activity.
public class MusicService extends Service implements MediaPlayer.OnErrorListener{
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MusicService() { }
public class ServiceBinder extends Binder {
public MusicService getServiceInstance() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0){return mBinder;}
#Override
public void onCreate () {
super.onCreate();
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setOnErrorListener(this);
mPlayer.setLooping(false);
mPlayer.setVolume(100,100);
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
}
Hope this can help a little bit.
create a service class like
public class MyService extends Service {
MediaPlayer mPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
mPlayer = MediaPlayer.create(this, R.raw.laila);
mPlayer.setLooping(false); // Set looping
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
mPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
mPlayer.stop();
}
}
Add below line in your Manifest.xml file
<service android:name=".service.MyService" android:enabled="true"/>
You can start service by calling
startService(new Intent(this, MyService.class));
and stop service
stopService(new Intent(this, MyService.class));
This is the basic flow how to start and stop a service. You can read more here Service

How can I run this Android code in Background

This is a actually a collage project. The requirements are:
Make an app that will change Android Profile to Ringer, Vibration and Silent using any two sensors (I used Proximity and Accelerometer).
Make sure the app runs in Background even after App is closed.
Continuously running sensors consumes too much battery, Do something about is so battery power can be saved as much as possible.
I already fulfilled NO: 1 and functioning as expected, Just 2 and 3 remains.
What will be the easiest way to run this code in Background: I have an idea like this:
I want to Start and Stop the Background service using the Two Buttons.
Here is the Code for NO: 1.
public class SensorActivity extends Activity implements SensorEventListener{
private SensorManager mSensorManager;
private Sensor proxSensor,accSensor;
private TextView serviceStatus,profileStatus;
private Button startService,endService;
private boolean isObjectInFront,isPhoneFacedDown;
private AudioManager audioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
proxSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
accSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
isObjectInFront = false;
isPhoneFacedDown = false;
serviceStatus = (TextView) findViewById(R.id.textView_serviceStatus);
profileStatus = (TextView) findViewById(R.id.textView_profileStatus);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if(event.values[0] > 0){
isObjectInFront = false;
}
else {
isObjectInFront = true;
}
}
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if(event.values[2] < 0){
isPhoneFacedDown = true;
}
else {
isPhoneFacedDown = false;
}
}
if(isObjectInFront && isPhoneFacedDown){
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
profileStatus.setText("Ringer Mode : Off\nVibration Mode: Off\nSilent Mode: On");
}
else {
if(isObjectInFront){
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
profileStatus.setText("Ringer Mode : Off\nVibration Mode: On\nSilent Mode: Off");
}
else {
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
profileStatus.setText("Ringer Mode : On\nVibration Mode: Off\nSilent Mode: Off");
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
You definitely should use a Service.
The Android user interface is restricted to perform long running jobs to make user experience smoother. A typical long running tasks can be periodic downloading of data from internet, saving multiple records into database, perform file I/O, fetching your phone contacts list, etc. For such long running tasks, Service is the alternative.
A service is an application component used to perform long running tasks in the background.
A service doesn’t have any user interface and neither can it directly communicate to an activity.
A service can run in the background indefinitely, even if the components that started the service is destroyed.
Usually a service always performs a single operation and stops itself once intended task is complete.
A service runs in the main thread of the application instance. It doesn’t create its own thread. If your service is going to do any long running blocking operation, it might cause Application Not Responding (ANR). And hence, you should create a new thread within the service.
Example
Service class
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 declaration
<?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>
To start your service
Intent intent = new Intent(this, HelloService.class);
startService(intent);
Reference

Communication Between Two Services using BroadcastReceiver

I m new on android
I want to start two services and one service sendbroadcast another will catch this broadcast but it is not working even if I register another service in this broadcasting
here is my code am I doing something wrong ?
Thanks advice.
public class MainActivity extends Activity {
Intent i;
Intent i2;
static final String LOG_TAG = "ServiceActivity";
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//Start service
i = new Intent(this, com.example.user.sensorservicetest.SimpleService.class);
i2= new Intent(this,com.example.user.sensorservicetest.AnotherService.class);
Log.d(LOG_TAG, "onCreate/startService");
}
#Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "onResume/registering receiver");
//Register BroadcastReceiver to receive accelerometer data from service
startService(i);
startService(i2);
}
}
#Override
public void onPause() {
super.onPause();
Log.d(LOG_TAG, "onPause/unregistering receiver");
stopService(i);
stopService(i2);
}
#Override
protected void onStop() {
super.onStop();
Log.d(LOG_TAG, "onStop");
stopService(i);
stopService(i2);
}
}
SimpleService
public class SimpleService extends Service implements SensorEventListener {
private String reading;
private SensorManager mgr;
private List<Sensor> sensorList;
static final String LOG_TAG = "SimpleService";
Intent intent = new Intent("com.practice.SimpleService.MY_ACTION");
final static String MY_ACTION = "com.practice.SimpleService.MY_ACTION";
#Override
//public void onStartCommand() {
public void onCreate() {
Log.d(LOG_TAG, "onStartCommand");
mgr = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorList = mgr.getSensorList(Sensor.TYPE_ACCELEROMETER);
for (Sensor sensor : sensorList) {
mgr.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
Log.d(LOG_TAG, "onDestroy");
mgr.unregisterListener(this);
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
Log.d(LOG_TAG, "onSensorChanged");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < event.values.length; i++) {
builder.append(" [");
builder.append(i);
builder.append("] = ");
builder.append(event.values[i]);
builder.append("\n");
}
reading = builder.toString();
//Send back reading to Activity
intent.putExtra("measurement", reading);
sendBroadcast(intent);
}
}
AnotherService
public class AnotherService extends Service {
static final String TAG = "AnotherService";
private AnotherServiceReceiver anotherServiceReceiver = new AnotherServiceReceiver();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"onStartCommand");
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.practice.SimpleService.MY_ACTION");
registerReceiver(anotherServiceReceiver, intentFilter);
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
if (anotherServiceReceiver != null)
unregisterReceiver(anotherServiceReceiver);
super.onDestroy();
}
public static class AnotherServiceReceiver extends BroadcastReceiver {
static final String receiverTag = "AnotherServiceReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(receiverTag, "onReceive");
String measurement = intent.getStringExtra("measurement");
Log.d(receiverTag, "measurement - 2 : " + measurement);
}
}
}
Manifest
<service android:name=".SimpleService" ></service>
<service android:name=".AnotherService"></service>
<receiver android:name=".AnotherService$AnotherServiceReceiver" android:enabled="true">
<intent-filter>
<action android:name="here is problem I think"
</intent-filter>
</receiver>
According #Evgeniy Mishustin answer (thanks to him)
Solution is adding service in manifest xml file now working each service communication
<service android:name=".SimpleService" ></service>
<service android:name=".AnotherService"></service>
<receiver android:name=".AnotherService$AnotherServiceReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.practice.SimpleService.MY_ACTION"></action>
</intent-filter>
</receiver>
</application>

android accelerometer in service stops when screen is turned off

I put accelerometer code in service. But it stops when screen is turned off.
It doesn't stop when phone is plugged via usb but it stops when not plugged.
All posts say that accelerometer in service doesn't stop. But the accelerometer in my code stops even though it is in service. Here's my code. what do I have to add in my code?
(My test phone is Samsung Galaxy S3 3G.)
// Service
public class LocalService extends Service {
private final IBinder mBinder = new LocalBinder();
private final Random mGenerator = new Random();
private SensorManager senSensorManager;
private Sensor senAccelerometer;
#Override
public void onCreate() {
super.onCreate();
Log.i("t", "onCreate");
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senSensorManager.registerListener(mSensorEventListener, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onDestroy() {
super.onDestroy();
senSensorManager.unregisterListener(mSensorEventListener);
// this sound is for checking
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
private SensorEventListener mSensorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// this vibrator is for checking
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
//Log.i("t", "onSensorChanged");
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
};
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
}
// Activity
public class MainActivity extends ActionBarActivity {
LocalService mService;
boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBound) {
int num = mService.getRandomNumber();
Toast.makeText(getBaseContext(), "number: " + num, Toast.LENGTH_SHORT).show();
}
}
});
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
// added
I've decided to use PARTIAL_WAKE_LOCK. It's the best solution for me.
Read this.
http://nosemaj.org/android-persistent-sensors
http://nosemaj.org/android-persistent-sensors
In your code you're using LocalService, which is bound to the Activity (you're calling bindService and unbindService). Doing so causes you service to stop then activity stops, because your service acts as a bound service and stops, whenever last binding is closed. See bound service lifecycle for reference.
If you really want your service to run always don't bind to it - you should just start is somewhere (using startService method), and then stop only then you really no more needed accelerometer tracking.
EDIT
If the problem is not that the service is stopping, but rather that the accelerometer stops, then you should maintain the wakelock, otherwise the device is turning off and the sensors will not report you any data.

Start new Activity On Sensor Changed?

How can i start new Activity on Accelererometer (On Shake): when i shake my phone the app crashes
- the accelerometer run also in background
public class Shaker_Service extends Service implements SensorEventListener{
private static final String TAG = "MyService";
private SensorManager sensorManager;
AppPreferences appPrefs;
#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 STOP", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service START", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
// add listener. The listener will be HelloAndroid (this) class
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
// check sensor type
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
// assign directions
float x=event.values[0];
float y=event.values[1];
float z=event.values[2];
if (x>10){
startActivity(newIntent("com.examles.MESSAGE"));
}
}
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.examples"
android:versionCode="1"
android:versionName="1.0">
<activity android:name=".Message_Note"
android:label="#string/app_name"
>
<intent-filter>
<action android:name="com.examples.MESSAGE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".Shaker_Service" />
</application>
</manifest>
Message_Note.java :
public class Message_Note extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
}
}
image of error (LogCat)
https://mega.co.nz/#!SUpTAbAC!WC9y_Xlh5GEW9AY9_5WbpXwkYA4Xk-o9WgaXvN6jpLk
Try using:
Intent intent = new Intent(this, theActivityYouWantToStart.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
This is the correct way to start an Activity from inside a service.

Categories

Resources