I have declared my Service inside my Voice Activity's Voice.java that
public class Voice extends AppCompatActivity implements RecognitionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
startService(new Intent(Voice.this,task.class));
}
class task extends Service{
#Override
public void onCreate() {
//background code here
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and my manifest showing
this error
Instantiatable attribute missing
Related
I have codes in two classes
First class is ExampleBroadcastReceiver:
public class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
if (noConnectivity) {
Toast.makeText(context, "Disconnected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
}
Second class is MainActivity:
public class MainActivity extends AppCompatActivity {
ExampleBroadcastReceiver exampleBroadcastReceiver = new ExampleBroadcastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(exampleBroadcastReceiver, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(exampleBroadcastReceiver);
}
}
How can I make the two classes into one by passing the code from the ExampleBroadcastReceiver class to MainActivity? Is it possible? Please don't ask why. Thanks.
Use java interface to handle an event in MainActivity that occurs in ExampleBroadcastReceiver. This way you don't have to merge classes to share an event based data.
public class ExampleBroadcastReceiver extends BroadcastReceiver {
public interface ConnectivityMonitorCallback {
void onConnectivityChanged(boolean connectivity);
}
public ConnectivityMonitorCallback callback;
public ExampleBroadcastReceiver(#NonNull ConnectivityMonitorCallback eventCallback) {
callback = eventCallback;
}
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
callback.onConnectivityChanged(noConnectivity);
}
}
}
Finally in the MainActivity you handle the event.
public class MainActivity extends AppCompatActivity {
ExampleBroadcastReceiver exampleBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Define event handling code here which occurs in ExampleBroadcastReceiver
exampleBroadcastReceiver = new ExampleBroadcastReceiver(new ExampleBroadcastReceiver.ConnectivityMonitorCallback {
#Override
void onConnectivityChanged(boolean connectivity) {
// Handle the event that occured in ExampleBroadcastReceiver
}
});
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(exampleBroadcastReceiver, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(exampleBroadcastReceiver);
}
}
I have a video player app where I need to access the lifecycle of an abstract activity from another class in Android. In my abstract activity, I've tried using LifecycleRegistry, but this is getting me the lifecycle owner not the actually lifecycle of the abstract class. How can I access the lifecycle of an abstract activity from another class?
Here is my abstract activity:
abstract public class MainActivity extends AppCompatActivity {
private LifecycleRegistry lifecycleRegistry;
VideoPlayer videoPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
setContentView(R.layout.activity_main);
videoPlayer = new VideoPlayer();
playVideo();
}
public void playVideo(){
videoPlayer.init();
//calls function in VideoPlayer class
}
#Override
protected void onResume() {
super.onResume();
lifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED);
}
#Override
protected void onDestroy() {
super.onDestroy();
lifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED);
}
}
Here is the class where I need to get the lifecycle of my abstract MainActivity:
public class VideoPlayer {
public void init() {
playVideo();
}
public void playVideo() {
//async call happens here, I need getLifeCycle() from MainActivity
}
}
Don't know a know about the context of you feature, but you You can do smth
public class VideoPlayer {
private Lifecycle mLifecycle;
public VideoPlayer(Lifecycle lifecycle) {
mLifecycle = lifecycle;
}
public void init() {
playVideo();
}
public void playVideo() {
//you have mLifecycle now
}
}
In Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
videoPlayer = new VideoPlayer(getLifecycle());
}
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.
How the code Intent intent=new Intent(context,Activity.class) which is in the superclass can be reused by its subclasses given that the subclasses have different context and different activities to start after on click listener is called. Is it possible?
This is the superclass:
public class CommonPost extends AppCompatActivity {
public void on_create(final Context context, final Class aclass) {
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CommonPost commonPost = new CommonPost();
MyTask task = commonPost.new MyTask(context, aclass);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
task.execute();
}
});
}
class MyTask extends AsyncTask<Void,Void,Void> {
Context context;
Class aclass;
public MyTask(Context context,Class aclass){
this.context=context;
this.aclass=aclass;
}
#Override
protected void onPreExecute() {
// do something
}
#Override
protected Void doInBackground(Void... voids) {
// do something
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Intent intent = new Intent(context, aclass);
startActivity(intent);
}
}
One of the subclass:
public class PlacementPost extends CommonPost {
Context context=PlacementPost.this;
Class aclass=Placements.class;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
on_create(context,aclass);
}
}
I am getting the following error when I try the above code:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:4266)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4548)
at android.app.Activity.startActivity(Activity.java:4516)
at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:240)
at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:177)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
I am not sure where I am wrong or what I am missing. I just tried out whatever logically I felt correct. Please do correct me out where I am wrong!
for the starters you should never initialize your Activity using new, it has it's own life cycle and context should be of the class where you are actually starting intent, change you code to
on_create
public void on_create(final Context context, final Class aclass) {
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MyTask task = new MyTask(stor_root, mProgress, editTextplace, post, ninfo, imageUri,
mstorage, mDatabase, context, aclass);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
task.execute();
}
});
}
MyTask - Stop passing context from child
class MyTask extends AsyncTask<Void,Void,Void> {
Class aclass;
public MyTask(Class aclass){
this.aclass=aclass;
}
#Override
protected void onPreExecute() {
// do something
}
#Override
protected Void doInBackground(Void... voids) {
// do something
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Intent intent = new Intent(CommonPost.this, aclass);
startActivity(intent);
}
}
SubClass
public class PlacementPost extends CommonPost {
Context context=PlacementPost.this;
Class aclass=Placements.class;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
on_create(aclass);
}
}
You need to make the variable a class scope not an inner class scope.
This is an inner class scope variables:
public class CommonPost extends AppCompatActivity {
...
class MyTask extends AsyncTask<Void,Void,Void> {
Context context;
Class aclass;
...
}
}
You can't access the Context context and Class aclass; from the child class.
You need to make it a class scope:
public class CommonPost extends AppCompatActivity {
// set to protected to only allow child class access.
protected Context context;
protected Class aclass;
...
class MyTask extends AsyncTask<Void,Void,Void> {
}
}
Then, in your child class, change the variables to:
public class PlacementPost extends CommonPost {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the value to the base class.
context = PlacementPost.this;
aclass = Placements.class;
on_create(context,aclass);
}
}
I am using android tts in my class to just say a message like so:
Problem: I get leaked service connection
public class WorkTimerNotification extends ActionBarActivity implements TextToSpeech.OnInitListener {
TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_timer_notification);
//line1
tts = new TextToSpeech(this,this);
#Override
public void onInit(int status) {
//line2
tts.setLanguage(Locale.US);
//line3
tts.speak("Text to say aloud", TextToSpeech.QUEUE_ADD, null);
tts.shutdown();
}
#Override
protected void onDestroy() {
super.onDestroy();
tts.shutdown();
}
Line 1 I get leaked serviceConnection with this logcat:
WorkTimerNotification has leaked ServiceConnection android.speech.tts.TextToSpeech$Connection#41aee290 that was originally bound here
android.app.ServiceConnectionLeaked
I press on this and it still goes back to the hash for some reason. I do not know why...
int speak(CharSequence, int, Bundle, String)
I have also tried: But it does not work either.
#Override
protected void onDestroy() {
//Close the Text to Speech Library
if(tts!= null) {
tts.stop();
ttsRest.shutdown();
Log.d(TAG, "TTS Destroyed");
}
super.onDestroy();
}
You can not call speak until after onInit is called, move your speak code to onInit
public class WorkTimerNotification extends ActionBarActivity implements TextToSpeech.OnInitListener {
TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_timer_notification);
//line1
}
#Override
public void onInit(int status) {
//line2
tts.setLanguage(Locale.US);
//line3
tts.speak("Text to say aloud", TextToSpeech.QUEUE_ADD, null);
}
#Override
protected void onStart()
{
super.onStart();
tts = new TextToSpeech(this,this);
}
#Override
protected void onStop()
{
super.onStop();
tts.shutdown();
}