The following code keeps throwing null pointer exception...
public class MainActivity extends Activity implements OnClickListener{
Button but;
Button but2;
LocalBinder binder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but = (Button) findViewById(R.id.button1);
but.setOnClickListener(this);
but = (Button) findViewById(R.id.button2);
}
ServiceConnection connection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
Log.d("D1", "connecting");
binder = (LocalBinder) arg1;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
Log.d("D1", "disconnecting");
}
};
public static class ServiceTest extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return new LocalBinder();
}
public class LocalBinder extends Binder{
public void toast(){
Toast.makeText(getApplicationContext(), "hope this works", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ServiceTest.LocalBinder.class);
bindService(i, connection, Context.BIND_AUTO_CREATE);
Toast.makeText(getApplicationContext(), "bind completed", Toast.LENGTH_LONG).show();
}
public void binderMethod(View v){
binder.toast();
}
}
I guess that the reason is that onServiceConnected does not execute, which causes binder to stay null. (The but button binds the service to the activity while but2 executes binder.toast(); - the exception is thrown when but2 is pressed)
Basicly the question is : why doesnt onServiceConnected execute ?
I think, that intent should lead to service, not binder in service: Intent i = new Intent(getApplicationContext(), ServiceTest.class);
Related
I want to play my ringtone in my android app in background(for version O and above) even if application is closed and stop playing if i stop from my app.
I used service in my application but the music is stopped when i closed my app.
How can i achieve this ??
Here is my Service class:
public class MyService extends Service {
MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player=MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.setVolume(100,100);
player.start();
player.start();
return START_STICKY;
}
#Override
public void onDestroy() {
player.stop();
player.release();
super.onDestroy();
}
}
and here is my MainActivity class from where I'm starting and stopping the service:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Start(View view) {
startService(new Intent(this,MyService.class));
}
public void Stop(View v){
stopService(new Intent(this,MyService.class));
}
public void go(View view) {
startActivity(new Intent(MainActivity.this,NotActivity.class ));
}
}
From the code that you submitted, you have never invoked the service of the player. call the functions that you have created in oncreate method that should do the trick.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//button objects
private Button buttonStart;
private Button buttonStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting buttons from xml
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
//attaching onclicklistener to buttons
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == buttonStart) {
//starting service
startService(new Intent(this, MyService.class));
} else if (view == buttonStop) {
//stopping service
stopService(new Intent(this, MyService.class));
}
}
}
note: Create two buttons to start and stop the service
For more info check out: https://www.simplifiedcoding.net/android-service-example/
I have a java background serviceA and serviceB. I have instantiated serviceA in onStart method in Mainactivity class . I need to start serviceB if the serviceA fails to start. I have written a callback method which gets called in MainActivity but when I tried to call serviceB it is not getting created.
I have written a callback method in MainActivity which gets called in serviceA but when I tried to call serviceB it is not getting created.
public class MainActivity extends Activity implements ServiceCallbacks{
private static final String TAG = "Main Activity";
private Context myContext = null;
Intent myTestService;
private MyTestService serviceA;
private boolean bound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myContext = this;
setContentView(R.layout.activity_main);
Log.d(TAG,"onCreate called.");
}
#Override
protected void onResume() {
super.onResume();
if(serviceA == null) {
serviceA = new Intent(this, MyTestService.class);
Log.d(TAG,"onResume called.");
Log.d(TAG,"myTestService instance created.");
}
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG,"onPause called.");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG,"OnDestory called");
}
#Override
protected void onStart() {
super.onStart();
// bind to Service
Intent intent = new Intent(this, MyTestService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from service
if (bound) {
myService.setCallbacks(null); // unregister
unbindService(serviceConnection);
bound = false;
}
}
/** Callbacks for service binding, passed to bindService() */
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
// cast the IBinder and get MyService instance
LocalBinder binder = (LocalBinder) service;
myService = binder.getService();
bound = true;
myService.setCallbacks(MainActivity.this); // register
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};
#Override
public void callBackToActivity() {
unbindService(serviceConnection);
StartNewService();
}
private void StartNewService(){
Intent intent = new Intent(this, serviceB.class);
startService(intent);
}
}
I want to start serviceB if serviceA fails to start.
I am c# developer and new to java and need your help.
I have a Service (Bound) which I am trying to start from my MainActivity.java. The below is my Main Activity code:
public class MainActivity extends AppCompatActivity {
Handler m_handler;
Runnable m_handlerTask ;
private static ServiceConnection sConnection;
static boolean serviceBound = false;
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, DataDownloaderService.class);
bindService(intent, sConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.NoActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (!Global.isMyServiceRunning(DataDownloaderService.class, this)) {
sConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
DataDownloaderService.LocalBinder binder = (DataDownloaderService.LocalBinder) service;
Global.dService = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
serviceBound = false;
}
};
}
}
catch(Exception ex ){
String p="";
}
}
#Override
protected void onResume(){
super.onResume();
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
RefreshNowPlaying();
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
}
}
void RefreshNowPlaying(){
//Do something
}
}
The service code is as shown below:
public class DataDownloaderService extends Service {
private final IBinder dBinder = new LocalBinder();
public class LocalBinder extends Binder {
DataDownloaderService getService() {
// Return this instance of LocalService so clients can call public methods
return DataDownloaderService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return dBinder;
}
#Override
public void onCreate(){
}
#Override
public void onStart(Intent intent, int startid){
super.onStart(intent,startid);
Global.DataDownloaderServiceStatus = "STARTED";
}
#Override
public void onDestroy(){
Global.DataDownloaderServiceStatus = "STOPPED";
super.onDestroy();
}
}
I have also added the service to the AndroidManifest.xml under the Application element. However, I see that the service's onStart is never fired or the override onServiceConnected in the MainActivity is never called. I am new to Anrdoid development and Java. Can someone give me some pointers, please? I have noticed that the service's onCreate is getting hit, by putting breakpoints, but not onStart.
onStart() will be called only if the service was started via context.startService(), see here.
I have already scanned all of the related questons&answers here, but I still couldn't find the solution.
the service class file:
public class otser extends Service {
private WindowManager windowManager;
private ImageView chatHead;
#Override public IBinder onBind(Intent intent) {
return null;
}
#Override public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
FileObserver observer = new FileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots") {
#Override
public void onEvent(int event, String file) {
event &= FileObserver.ALL_EVENTS;
if(event == FileObserver.CREATE){
Toast.makeText(getApplicationContext(), "screenshot taken",
Toast.LENGTH_LONG).show();
}
}
};
observer.startWatching(); // start the observer
Toast.makeText(getApplicationContext(), "service: OK",
Toast.LENGTH_SHORT).show();
}}
According to other posts, I double checked the path, via creating a file programatically, it does exist, and correct.
The Activity class:
public class Home extends Activity {
Button showChatHead;
Button stopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
showChatHead = (Button) findViewById(R.id.gomb);
stopService= (Button) findViewById(R.id.gomb2);
showChatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ChatHeadService.class);
startService(i);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ChatHeadService.class);
stopService(i);
}
});
}}
The service class linked well, the last Toast message pops up, as a conclusion only the observer is being skipped.
Any ideas?
Thanks in advance!
newer release:
FileObserver fileObserver = new FileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots") {
#Override
public void onEvent(int event, String path) {
Toast.makeText(getApplicationContext(), "method entered", Toast.LENGTH_SHORT).show();
if (event == FileObserver.CREATE) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File created", Toast.LENGTH_SHORT).show();
}
});
}
}
};
fileObserver.startWatching();
The onEvent method is not entered, the "method entered" Toast didn't appear.
in documentation of the onEvent-Method is mentioned, that it will run at another thread and you should consider this. using a handler, the Toast message should appear, like this:
private Handler handler = new Handler();
#Override
public void onCreate() {
fileObserver = new FileObserver("path") {
#Override
public void onEvent(int event, String path) {
if (event == FileObserver.CREATE) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(FileWatcher.this, "File created", Toast.LENGTH_SHORT).show();
}
});
}
}
};
fileObserver.startWatching();
Edit 1
I need to call a method from BroadcastReceiver and method exist in the Activity class mention below.
I tried this code and got NULL_POINTER_EXCEPTION where I create the reference the MainActivity class.
Correct me what I'm doing wrong ?
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void myTesting(){
Toast.makeText(MainActivity.this, "Welcome to Activity", Toast.LENGTH_SHORT).show();
}
}
BroadcastReceiver.java
public class BootCompeteReceiver extends BroadcastReceiver {
public Context mContext;
private MainActivity mainActivity;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
try {
mainActivity = new MainActivity();
mainActivity.myTesting();
} catch (Exception e) {
Toast.makeText(context, ""+e, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
Do something like that:
public class MainActivity extends Activity {
private BroadcastReceiver receiver = new BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
MainActivity.this.myTesting();
} catch (Exception e) {
Toast.makeText(MainActivity.this, ""+e, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intFilt = new IntentFilter(Constants.YOUR_BROADCAST_RECEIVER_ACTION);
registerReceiver(receiver, intFilt);
}
public void myTesting(){
Toast.makeText(MainActivity.this, "Welcome to Activity", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
You can startActivity in onReceive, and call myTesting in onCreate of your Activity.
You can try this:
public class MainActivity extends Activity {
private static volatile int INSTANCE_COUNTER = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
INSTANCE_COUNTER++;
IntentFilter intentFilter = new IntentFilter("com.your.package.ACTION");
registerReceiver(mWhateverReceiver, intentFilter);
if (getIntent().getBooleanExtra("fromYourReceiver", false)) {
myTesting();
}
}
private void myTesting() {
// Do something here
}
private BroadcastReceiver mWhateverReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
myTesting();
}
};
public static boolean isInstanceExist() {
return INSTANCE_COUNTER > 0;
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
INSTANCE_COUNTER--;
unregisterReceiver(mWhateverReceiver);
}
}
Your receiver
public class BootCompeteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (MainActivity.isInstanceExist()) {
// There is already one instance of MainActivity, so broadcast this
// event to trigger the receiver inside MainActivity to do your task
Intent broadcastIntent = new Intent("com.your.package.ACTION");
context.sendBroadcast(broadcastIntent);
} else {
// There is no instances of MainActivity exist, so start a new one
// with the action that let the instance know what it should do
Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.putExtra("fromYourReceiver", true);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activityIntent);
}
}
}