I am trying to run a background music in my android application but I am getting errors
IF MY QUESTION FORMAT IS WRONG, PLEASE CORRECT ME
how to solve this problem ?
I have a main activity MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent svc=new Intent(this, BackgroundMusic.class);
startService(svc);
}
in the service activity BackgroundMusic:
package com.example.tttgame;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class BackgroundMusic extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.music);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
in the AndroidManifiest :
<activity
android:name="com.example.tttgame.BoardActivity"
android:label="#string/app_name" >
</activity>
<service android:enabled="true" android:name="com.example.tttgame.BackgroundMusic" />
</application>
my error message :
09-03 21:45:20.387: E/MainActivity(1392): starting Main Activity ..
09-03 21:45:22.077: E/MainActivity(1392): checking if key 'flag' exists in preferences..
09-03 21:45:22.377: E/MediaPlayer(1392): Should have subtitle controller already set
09-03 21:45:22.797: E/MediaPlayer(1392): error (1, -2147483648)
09-03 21:45:22.837: E/AndroidRuntime(1392): FATAL EXCEPTION: main
09-03 21:45:22.837: E/AndroidRuntime(1392): Process: com.example.tttgame, PID: 1392
09-03 21:45:22.837: E/AndroidRuntime(1392): java.lang.RuntimeException: Unable to create service com.example.tttgame.BackgroundMusic: java.lang.NullPointerException
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2563)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread.access$1700(ActivityThread.java:135)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1479)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.os.Handler.dispatchMessage(Handler.java:102)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.os.Looper.loop(Looper.java:137)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread.main(ActivityThread.java:4998)
09-03 21:45:22.837: E/AndroidRuntime(1392): at java.lang.reflect.Method.invokeNative(Native Method)
09-03 21:45:22.837: E/AndroidRuntime(1392): at java.lang.reflect.Method.invoke(Method.java:515)
09-03 21:45:22.837: E/AndroidRuntime(1392): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
09-03 21:45:22.837: E/AndroidRuntime(1392): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
09-03 21:45:22.837: E/AndroidRuntime(1392): at dalvik.system.NativeStart.main(Native Method)
09-03 21:45:22.837: E/AndroidRuntime(1392): Caused by: java.lang.NullPointerException
09-03 21:45:22.837: E/AndroidRuntime(1392): at com.example.tttgame.BackgroundMusic.onCreate(BackgroundMusic.java:21)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2553)
09-03 21:45:22.837: E/AndroidRuntime(1392): ... 10 more
player = MediaPlayer.create(this, R.raw.music);
I think this is the problem
Because error is java.lang.NullPointerException
Look at my Class for sound and take reference with that.
public class SoundService extends Service {
private static MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
try {
if (player != null) {
player.stop();
player.release();
player= null;
}
player = MediaPlayer.create(this, R.raw.background);
player.setLooping(true);
player.start();
} catch (Exception e) {
}
}
public static boolean isMediaPlaying() {
if (player != null) {
try {
return player.isPlaying();
} catch (Exception e) {
}
}
return false;
}
#Override
public void onDestroy() {
if (player!= null) {
player.stop();
player.release();
player = null;
}
super.onDestroy();
}
}
I have realesed mediaplayer in onStart if it is already there. and no need to use onstart command.
Related
I have a Popup window (non-Activity class) that have some buttons. one of them (btn_audio), play or pause sound and it works like a charm.
Now I want to call two method, play() and pause() in my HomeActivity and inside of onStop() method in all of my Activities. it doesn't work, call play() and pause() in other Activity's occur NullPointException.
public class Popup_Menu extends Activity implements OnClickListener {
Button btn_audio;
public static MediaPlayer player; String play_or_pause;
int num_ply, tim_pos; int [] resID;// Audio
SharedPreferences sp;
void showPopup(final Activity context) {
this.context=context;
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = layoutInflater.inflate(R.layout.popup_layout_menu, viewGroup);
sp = context.getSharedPreferences("text", MODE_PRIVATE);
btn_audio = (Button) layout.findViewById(R.id.btn_audio); // audio
layout.findViewById(R.id.btn_audio).setOnClickListener(this);
#Override
public void onClick(View whichButtonIsClicked) {
switch (whichButtonIsClicked.getId()) {
case R.id.btn_audio:
if (play_or_pause.equals("play")) {
pause();
} else {
play(context);
}
sp.edit().putString("play_or_pause", play_or_pause).commit(); // save current stat
} ////// close of showPopup()
//define play and pause methods
public void pause() {
player.pause();
btn_audio.setBackgroundResource(R.drawable.icon_audio_pause);
play_or_pause="pause"; // current state is 'pause'
}
public void play(final Context context) {
if(num_ply==9){num_ply=0; }
resID = new int []{ R.raw.tarane,R.raw.toofan,R.raw.shane,R.raw.kharazmi,R.raw.golhaye_khofte,R.raw.rang,R.raw.naghmeh,R.raw.dar_rahe_to,R.raw.emperor};
player=MediaPlayer.create(context,resID[num_ply]);
player.seekTo(tim_pos);
player.start();
btn_audio.setBackgroundResource(R.drawable.icon_audio_play);
play_or_pause="play"; // current state is 'play'
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer player) {
tim_pos=0; num_ply++; play(context);
}
});
}
}
and my HomeActivity :
public class HomeActivity extends Activity implements OnClickListener {
Popup_Menu ppp;
#Override
protected void onCreate..............
ppp = new Popup_Menu();
SharedPreferences sp = getSharedPreferences("text", MODE_PRIVATE);
if(sp.getString("play_or_pause", "play").equals("pause")){
ppp.play(getApplicationContext()); // ERROR
} // audio
} /// close of onCreate
#Override
public void onStop() {
super.onStop();
if(play_or_pause.equals("play")){
ppp.tim_pos= ppp.player.getCurrentP
Ok, I decided to use service to resolve this problem and it works well for play(). but when playing, still i can't call pause() method from SoundService because player object is null. I think by creating an object, from SoundService class, (ss in Popup_Menu class) , default constructor put player value to null (when playing and player object wasn't null). and calling player.pause occur error.
How PLEASE can i pause this one_week_friend!!!
public class SoundService extends Service {
MediaPlayer player; int num_ply, tim_pos; int [] resID;
public int onStartCommand(Intent intent, int flags, int startId) {
resID = new int []{ R.raw.tarane,R.raw.toofan,R.raw.shane,R.raw.kharazmi,
R.raw.golhaye_khofte,R.raw.rang,R.raw.naghmeh,R.raw.dar_rahe_to,R.raw.emperor };
player=MediaPlayer.create(this,resID[num_ply]);
play();
return Service.START_FLAG_REDELIVERY;
}
public void play() {
if(num_ply==9){num_ply=0; }
player.seekTo(tim_pos);
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer player) {
tim_pos=0; num_ply++; play();
}
});
}
public void resume(){
player.seekTo(tim_pos);
player.start();
}
public void pause() {
tim_pos= player.getCurrentPosition(); ////// ERROR
player.pause(); ////// ERROR
num_ply++;
}
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
And my Popup_Menu class:
#Override
public void onClick(View whichButtonIsClicked) {
switch (whichButtonIsClicked.getId()) {
case R.id.btn_audio:
if (play_or_pause.equals("play")) {
btn_audio.setBackgroundResource(R.drawable.icon_audio_pause);
play_or_pause="pause"; // current state is 'pause'
SoundService ss = new SoundService();
ss.pause(); ////// ERROR
} else {
btn_audio.setBackgroundResource(R.drawable.icon_audio_play);
play_or_pause="play"; // current state is 'play'
Intent sound_Intent = new Intent(context , SoundService.class); // start service
context.startService(sound_Intent);
}
sp.edit().putString("play_or_pause", play_or_pause).commit(); // save current state
break;
LogCat:
08-05 01:03:31.440: E/AndroidRuntime(25356): FATAL EXCEPTION: main
08-05 01:03:31.440: E/AndroidRuntime(25356): java.lang.NullPointerException
08-05 01:03:31.440: E/AndroidRuntime(25356): at com.codegostarNiloo.negar.SoundService.pause(SoundService.java:47)
08-05 01:03:31.440: E/AndroidRuntime(25356): at com.codegostarNiloo.negar.Popup_Menu.onClick(Popup_Menu.java:234)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.view.View.performClick(View.java:4209)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.view.View$PerformClick.run(View.java:17457)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.os.Handler.handleCallback(Handler.java:725)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.os.Handler.dispatchMessage(Handler.java:92)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.os.Looper.loop(Looper.java:153)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.app.ActivityThread.main(ActivityThread.java:5341)
08-05 01:03:31.440: E/AndroidRuntime(25356): at java.lang.reflect.Method.invokeNative(Native Method)
08-05 01:03:31.440: E/AndroidRuntime(25356): at java.lang.reflect.Method.invoke(Method.java:511)
08-05 01:03:31.440: E/AndroidRuntime(25356): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
08-05 01:03:31.440: E/AndroidRuntime(25356): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
08-05 01:03:31.440: E/AndroidRuntime(25356): at dalvik.system.NativeStart.main(Native Method)
08-05 01:03:32.066: D/dalvikvm(25356): threadid=11: interp stack at 0x5f1c9000
First, off, don't extend an Activity if it's a non Activity, as you claim, then passing a Context is preferred over an Activity
Secondly, there is a class called DialogFragment that is intended to be used as a popup dialog
I think you are looking for something like the following, though
public class Popup_Menu implements OnClickListener {
Button btn_audio;
public MediaPlayer player;
String play_or_pause;
int num_ply, tim_pos;
int [] resID;// Audio
SharedPreferences sp;
Context context ;
public Popup_Menu(final Context context) {
this.context= context;
sp = this.context.getSharedPreferences("text", Context.MODE_PRIVATE);
// LinearLayout viewGroup = (LinearLayout) view.findViewById(R.id.popup);
LayoutInflater layoutInflater = LayoutInflater.from(this.context);
layout = layoutInflater.inflate(R.layout.popup_layout_menu, viewGroup);
btn_audio = (Button) layout.findViewById(R.id.btn_audio); // audio
btn_audio.setOnClickListener(this);
}
You can now create a new Popup_Menu(HomeActivity.this)
Yeah...!!! Done. It now working.it doesn't need to create new object. I must change modifire of (object)player and pause() methode and everything in it, to STATIC. So righte now i can access all objects and variables.
Thanks cricket_007...
I'm developing an app with eclipse and arduino which connects to a bluetooth module. I can then control the LEDS on the board. However my code shows no errors but the app force closes everytime I hit a button. Here is my code:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BluetoothTest extends Activity
{
TextView labelConnect;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
Button closeButton = (Button)findViewById(R.id.close);
Button onButton = (Button)findViewById(R.id.onButton);
Button offButton = (Button)findViewById(R.id.offButton);
Button redButton = (Button)findViewById(R.id.redButton);
Button greenButton = (Button)findViewById(R.id.greenButton);
Button blueButton = (Button)findViewById(R.id.blueButton);
labelConnect = (TextView)findViewById(R.id.mylabel);
//Open Bluetooth
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Close Bluetooth
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
//Red Button
redButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
redButton();
}
catch (IOException ex) { }
}
});
//Green Button
greenButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
greenButton();
}
catch (IOException ex) { }
}
});
//Blue Button
blueButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
blueButton();
}
catch (IOException ex) { }
}
});
//On Button - set strip to white
onButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
onButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
//Off Button - set strip to all OFF
offButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
offButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
} // end onCreate
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
labelConnect.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("BTNode0")) // Change to match RN42 - node name
{
mmDevice = device;
Log.i("ArduinoBT", "findBT found device named " + mmDevice.getName());
Log.i("ArduinoBT", "device address is " + mmDevice.getAddress());
break;
}
}
}
labelConnect.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
labelConnect.setText("BT << " + mmDevice.getName() + " >> is now open ");
}
void closeBT() throws IOException
{
mmOutputStream.close();
mmSocket.close();
labelConnect.setText("Bluetooth Closed");
}
void offButton() throws IOException
{
mmOutputStream.write("0".getBytes());
}
void redButton() throws IOException
{
mmOutputStream.write("1".getBytes());
}
void greenButton() throws IOException
{
mmOutputStream.write("2".getBytes());
}
void blueButton() throws IOException
{
mmOutputStream.write("3".getBytes());
}
void onButton() throws IOException
{
mmOutputStream.write("4".getBytes());
}
}
And here is my log for what happens when I hit the connect button
04-25 12:15:10.771: W/asset(22604): Copying FileAsset 0x74c0a9d8 (zip:/data/app/Android.Arduino.Bluetooth-2.apk:/resources.arsc) to buffer size 1912 to make it aligned.
04-25 12:15:10.821: D/RenderPolicy(22604): ViewRootImpl.enableHardwareAcceleration -> enableRenderPolicy
04-25 12:15:10.881: I/Adreno-EGL(22604): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
04-25 12:15:10.881: I/Adreno-EGL(22604): OpenGL ES Shader Compiler Version: 17.01.10.SPL
04-25 12:15:10.881: I/Adreno-EGL(22604): Build Date: 02/04/14 Tue
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Remote Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Patches:
04-25 12:15:10.881: I/Adreno-EGL(22604): Reconstruct Branch:
04-25 12:15:12.363: W/dalvikvm(22604): threadid=1: thread exiting with uncaught exception (group=0x41625e18)
04-25 12:15:12.373: E/AndroidRuntime(22604): FATAL EXCEPTION: main
04-25 12:15:12.373: E/AndroidRuntime(22604): Process: Android.Arduino.Bluetooth, PID: 22604
04-25 12:15:12.373: E/AndroidRuntime(22604): java.lang.NullPointerException
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest.openBT(BluetoothTest.java:185)
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest$1.onClick(BluetoothTest.java:53)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View.performClick(View.java:4480)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View$PerformClick.run(View.java:18673)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.handleCallback(Handler.java:733)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.dispatchMessage(Handler.java:95)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Looper.loop(Looper.java:157)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.app.ActivityThread.main(ActivityThread.java:5872)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invokeNative(Native Method)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invoke(Method.java:515)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
04-25 12:15:12.373: E/AndroidRuntime(22604): at dalvik.system.NativeStart.main(Native Method)
As they have already said in the comments, the mmDevice you are trying to use in the openBT method is null, because no device was found in the findBT method and the variable was not initialized. You need to fix your code so that you don't try to open the connection if the device was not found.
The other main issue in your code, once you solve this, is the SocketConnection you are trying to open in the Main Thread. Button handlers and GUI events are executed in the main thread, so your openBT should be moved to a separate thread (or better, a Service).
Hi I am trying to use the service class for first time and have been facing problems. What I want is an infinitely running (unless killed by Android System) service with an active Network connection. I have written the code which works fine on Android 4.3 and 4.4 but the application crashes when I try running on Android 2.2. My code is as follows:
public class BackgroundMusicService extends Service {
private MediaPlayer mp;
private int id;
private static class BackgroundAsyncTaskClass extends AsyncTask<Void, Void, Void>{
protected Void doInBackground(Void... params) {
Log.v("Async","Async Called");
/*Network connection will be created here*/
return null;
}
}
private class ForThread implements Runnable{
public void run() {
while (true) {
try {
Log.v("ThreadSleeping","5 sec");
BackgroundAsyncTaskClass task = new BackgroundAsyncTaskClass();
task.execute();
Thread.sleep(5000);
} catch (InterruptedException e) {
}finally{
Log.v("Finally called","Finally called");
}
}
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("onStartCommand Called","onStart Command Called");
Thread t;
ForThread ft = new ForThread();
t = new Thread(ft);
t.start();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if(null != mp){
mp.stop();
mp.release();
Log.v("Destroyed","onDestroy Called");
}
}
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(),
this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(
getApplicationContext(), 1, restartServiceIntent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext()
.getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
}
and the exception thrown by Android 2.2 is as follows:
04-28 09:51:41.435: W/dalvikvm(280): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
04-28 09:51:41.435: E/AndroidRuntime(280): FATAL EXCEPTION: Thread-8
04-28 09:51:41.435: E/AndroidRuntime(280): java.lang.ExceptionInInitializerError
04-28 09:51:41.435: E/AndroidRuntime(280): at com.example.backgroundservicedemo.BackgroundMusicService$ForThread.run(BackgroundMusicService.java:45)
04-28 09:51:41.435: E/AndroidRuntime(280): at java.lang.Thread.run(Thread.java:1096)
04-28 09:51:41.435: E/AndroidRuntime(280): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.Handler.<init>(Handler.java:121)
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
Also, when I try using handler.post(new Runnable(){.... run(){}....} The UI hangs up but the background thread continues running and exits after it becomes out of memory.
Another thing that I have doubts about is:
When the application restarts, I want this active Service to stop, but how do I get a reference to this thread running in Background and how do I stop this? I would appreciate if anyone can redirect me to a suitable link/reference or could help me out with the code. Thanks
You have this inside a thread's run method
BackgroundAsyncTaskClass task = new BackgroundAsyncTaskClass();
task.execute();
Threading rules from the docs
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
i have a service running which receive broadcast messages in LAN and i have started the service from fragment and i want to stop the service when the fragment is destroyed but its giving NPE when i call stopservice.
My service calling fragment is:
public class Receive extends Fragment {
TextView tv1,tv2;
Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView =inflater.inflate(R.layout.receive, container, false);
intent = new Intent(getActivity(), Server.class);
tv1=(TextView)rootView.findViewById(R.id.textView1);
tv2=(TextView)rootView.findViewById(R.id.textView2);
//getActivity().startService(intent);
return rootView;
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}};
private void updateUI(Intent intent) {
Toast.makeText(getActivity().getApplicationContext(), "Yea!!! Service called", Toast.LENGTH_SHORT).show();
String message = intent.getStringExtra("messages");
String senderip = intent.getStringExtra("sender");
tv2.setText(message);
tv1.setText(senderip);
}
#Override
public void onResume() {
super.onResume();
getActivity().startService(intent);
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(
Server.UDP_BROADCAST));
Log.i("UDP", "reg started");
}
#Override
public void onPause() {
super.onPause();
getActivity(). unregisterReceiver(broadcastReceiver);
getActivity().stopService(intent);
Log.i("UDP", "unreg started");
}
}
My service is:
public class Server extends Service {
static String UDP_BROADCAST = "soft.b.peopleassist";
//Boolean shouldListenForUDPBroadcast = false;
DatagramSocket socket;
//Intent intent;
private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception {
byte[] recvBuf = new byte[15000];
if (socket == null || socket.isClosed()) {
socket = new DatagramSocket(port, broadcastIP);
socket.setBroadcast(true);
}
//socket.setSoTimeout(1000);
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
Log.e("UDP", "Waiting for UDP broadcast");
socket.receive(packet);
String senderIP = packet.getAddress().getHostAddress();
String message = new String(packet.getData());
Log.e("UDP", "Got UDB broadcast from " + senderIP + ", message: " + message);
broadcastIntent(senderIP, message);
socket.close();
}
private void broadcastIntent(String senderIP, String message) {
Intent intent = new Intent(Server.UDP_BROADCAST);
intent.putExtra("sender", senderIP);
intent.putExtra("messages", message);
sendBroadcast(intent);
}
Thread UDPBroadcastThread;
void startListenForUDPBroadcast() {
UDPBroadcastThread = new Thread(new Runnable() {
public void run() {
try {
InetAddress broadcastIP = InetAddress.getByName("192.168.1.255"); //172.16.238.42 //192.168.1.255
Integer port = 11111;
while (shouldRestartSocketListen) {
listenAndWaitAndThrowIntent(broadcastIP, port);
}
//if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
} catch (Exception e) {
Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
}
}
});
UDPBroadcastThread.start();
}
private Boolean shouldRestartSocketListen=true;
void stopListen() {
shouldRestartSocketListen = false;
socket.close();
}
#Override
public void onCreate() {
};
#Override
public void onDestroy() {
stopListen();
//stopService(intent);
Log.i("UDP", "Service stoped");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
shouldRestartSocketListen = true;
startListenForUDPBroadcast();
Log.i("UDP", "Service started");
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
My logcat is:
09-03 09:17:21.995: D/gralloc_goldfish(908): Emulator without GPU emulation detected.
09-03 09:17:28.763: I/UDP(908): reg started
09-03 09:17:28.853: I/UDP(908): Service started
09-03 09:17:28.993: I/UDP(908): no longer listening for UDP broadcasts cause of error bind failed: EADDRNOTAVAIL (Cannot assign requested address)
09-03 09:17:30.653: I/UDP(908): unreg started
09-03 09:17:30.893: D/AndroidRuntime(908): Shutting down VM
09-03 09:17:30.893: W/dalvikvm(908): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
09-03 09:17:30.963: E/AndroidRuntime(908): FATAL EXCEPTION: main
09-03 09:17:30.963: E/AndroidRuntime(908): java.lang.RuntimeException: Unable to stop service soft.b.peopleassist.Server#4137dbb8: java.lang.NullPointerException
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread.handleStopService(ActivityThread.java:2405)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread.access$2000(ActivityThread.java:122)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.os.Handler.dispatchMessage(Handler.java:99)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.os.Looper.loop(Looper.java:137)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread.main(ActivityThread.java:4340)
09-03 09:17:30.963: E/AndroidRuntime(908): at java.lang.reflect.Method.invokeNative(Native Method)
09-03 09:17:30.963: E/AndroidRuntime(908): at java.lang.reflect.Method.invoke(Method.java:511)
09-03 09:17:30.963: E/AndroidRuntime(908): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-03 09:17:30.963: E/AndroidRuntime(908): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-03 09:17:30.963: E/AndroidRuntime(908): at dalvik.system.NativeStart.main(Native Method)
09-03 09:17:30.963: E/AndroidRuntime(908): Caused by: java.lang.NullPointerException
09-03 09:17:30.963: E/AndroidRuntime(908): at soft.b.peopleassist.Server.stopListen(Server.java:68)
09-03 09:17:30.963: E/AndroidRuntime(908): at soft.b.peopleassist.Server.onDestroy(Server.java:78)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread.handleStopService(ActivityThread.java:2388)
09-03 09:17:30.963: E/AndroidRuntime(908): ... 10 more
09-03 09:17:33.533: I/Process(908): Sending signal. PID: 908 SIG: 9
Thanks in Advance.
In the stopListen() method you set the stop boolean and then immediately close the socket.
It is possible, that your other thread is deeply in work with that. I would suggest, that you close sockets in the thread in which they where created. e.g. socket.close() in the catchblock and remove it from stopListen().
I created an overlay "always on top button", which is a service HUD, and I can't start an activity screen from there, it gives the error: "Unfortunately App has stopped". In the beginning, all I used to know if there was any TouchEventwas a toast, and that toast was created, but it was created several times, so I don't know if it gives that error because this code, which is on TouchEvent body , is repeated several times too.
here is my code:
public class HUD extends Service implements OnClickListener, OnTouchListener, OnLongClickListener {
Button mButton;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//mView = new HUDView(this);
mButton = new Button(this);
mButton.setId(1);
mButton.setText("Button");
mButton.setClickable(true);
mButton.setOnTouchListener(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.OPAQUE);
params.gravity = Gravity.LEFT | Gravity.TOP;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mButton, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mButton != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mButton);
mButton = null;
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getX()<mButton.getWidth() & event.getY()>0)
{
Toast.makeText(this,"Overlay button event", Toast.LENGTH_SHORT).show(); //this my toast
Intent i = new Intent(); //this is my new acivity (intent)
i.setClass(HUD.this, screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
HUD.this.stopSelf();
}
return false;
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(this,"Click", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
System.exit(1);
return false;
}
}
So my question is, is this code on TouchEvent body being repeated several times? If it is, is that the cause of the error?
log cat:
07-20 22:11:06.962: I/Choreographer(1620): Skipped 52 frames! The application may be doing too much work on its main thread.
07-20 22:11:08.062: D/AndroidRuntime(1620): Shutting down VM
07-20 22:11:08.062: W/dalvikvm(1620): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-20 22:11:08.132: E/AndroidRuntime(1620): FATAL EXCEPTION: main
07-20 22:11:08.132: E/AndroidRuntime(1620): android.app.SuperNotCalledException: Activity {com.example.screenshot/com.example.screenshot.screen} did not call through to super.onCreate()
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2146)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Looper.loop(Looper.java:137)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-20 22:11:08.132: E/AndroidRuntime(1620): at dalvik.system.NativeStart.main(Native Method)
screen.java:
public class screen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Toast.makeText(getApplicationContext(), "Made it", 0).show();
finish();
}
}
See android start activity from service
Intent i= new Intent(getBaseContext(), screen.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(i);
You error seems to be inside screen activity. There are many thread which might help to figure out the error that you are getting for the activity:
Error in Android "SuperNotCalledException:Activity did not call through to super.OnCreate()"
android.app.SuperNotCalledException: Activity did not call through to super.onStop()
Update
The error is because you haven't called: super.onCreate(savedInstanceState); in your screen activity's onCreate(). That should be the first thing to be called in onCreate(). Do something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.... other stuff
}
Hope this helps.