I recently developed an android app that streams radio online using a URL. It has been working well in other android versions that is 6,7and 8 the ones i tested in emulators.
But last week i published the app to play store, and my reports show that it crashes in android 9 phones. It keeps on throwing java.lang.SecurityException.
I have tried what i could to resolve the error but i have failed.
The users keep reporting multiple app crashes on their phones
This is the stack trace from the play console
java.lang.RuntimeException:
at android.app.ActivityThread.handleServiceArgs (ActivityThread.java:3903)
at android.app.ActivityThread.access$1700 (ActivityThread.java:236)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1815)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:214)
at android.app.ActivityThread.main (ActivityThread.java:7032)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:965)
Caused by: java.lang.SecurityException:
at android.os.Parcel.createException (Parcel.java:1966)
at android.os.Parcel.readException (Parcel.java:1934)
at android.os.Parcel.readException (Parcel.java:1884)
at android.app.IActivityManager$Stub$Proxy.setServiceForeground (IActivityManager.java:5043)
at android.app.Service.startForeground (Service.java:695)
at com.premar.radiomunabuddu.RadioMediaPlayerService.play (RadioMediaPlayerService.java:120)
at com.premar.radiomunabuddu.RadioMediaPlayerService.onStartCommand (RadioMediaPlayerService.java:50)
at android.app.ActivityThread.handleServiceArgs (ActivityThread.java:3884)
Caused by: android.os.RemoteException:
at com.android.server.am.ActivityManagerService.enforcePermission (ActivityManagerService.java:12159)
at com.android.server.am.ActiveServices.setServiceForegroundInnerLocked (ActiveServices.java:1289)
at com.android.server.am.ActiveServices.setServiceForegroundLocked (ActiveServices.java:969)
at com.android.server.am.ActivityManagerService.setServiceForeground (ActivityManagerService.java:24839)
at android.app.IActivityManager$Stub.onTransact$setServiceForeground$ (IActivityManager.java:11378)
This is the HomeActivity.java
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FancyButton listenRadio;
ImageView facebook, twitter, instagram, linkedin;
RadioSettings settings;
Context context;
public static final int REQUEST_CODE =123;
private Button stopButton = null;
private Button playButton = null;
private Button phoneCall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ButterKnife.bind(this);
settings = new RadioSettings();
//views
phoneCall = (Button)this.findViewById(R.id.phoneBtn);
//Allow hardware audio buttons to control volume
setVolumeControlStream(AudioManager.STREAM_MUSIC);
clickListeners(); //Start click listeners
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void openFacebookProfile() {
try {
String facebookURL = getFacebookPageUrl();
Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
facebookIntent.setData(Uri.parse(facebookURL));
startActivity(facebookIntent);
} catch (Exception e){
e.printStackTrace();
}
}
private String getFacebookPageUrl() {
final String facebookUrl = settings.getFacebookAddress();
String fbURL = null;
PackageManager packageManager = getPackageManager();
try {
if (packageManager != null){
Intent fbIntent = packageManager.getLaunchIntentForPackage("com.facebook.katana");
if (fbIntent != null){
int versionCode = packageManager.getPackageInfo("com.facebook.katana",0).versionCode;
if (versionCode >= 3002850){
fbURL = "fb://page/1993598950880589";
}
} else {
fbURL = facebookUrl;
}
}
else {
fbURL = facebookUrl;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
fbURL = facebookUrl;
}
return fbURL;
}
private void openTwitterProfile(){
Intent intent = null;
try {
this.getPackageManager().getPackageInfo("com.twitter.android", 0);
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("twitter://user?user_id=USERID"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} catch (Exception e){
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/profilename"));
}
this.startActivity(intent);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.watch_webcam: {
launchWebcam();
break;
}
case R.id.playstore_share: {
/*
Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName())));
}
break;
*/
}
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_share) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareMessage= "\nPlease download our Radiomunnabuddu USA app from the Play Store\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID +"\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT , shareMessage);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Radio Munnabuddu USA");
startActivity(Intent.createChooser(shareIntent, "Share via..."));
}
else if (id == R.id.nav_email){
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto: "+settings.getEmailAddress()));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Radio Munnabuddu USA");
if (emailIntent.resolveActivity(getPackageManager()) != null){
startActivity(Intent.createChooser(emailIntent, "Send email via"));
}
}
else if(id == R.id.nav_report){
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto: denis#premar.tech"));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Crash or Bug report");
if (emailIntent.resolveActivity(getPackageManager()) != null){
startActivity(Intent.createChooser(emailIntent, "Send email via."));
}
}
else if(id == R.id.nav_about){
Intent aboutIntent = new Intent(HomeActivity.this, AboutActivity.class);
startActivity(aboutIntent);
}
else if(id == R.id.nav_fb){
openFacebookProfile();
}
else if(id == R.id.nav_twitter){
openTwitterProfile();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* Listens for contact button clicks
*/
private void clickListeners(){
//Play button
playButton = (Button)findViewById(R.id.PlayButton);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
RadioMediaPlayerService.class);
intent.putExtra(RadioMediaPlayerService.START_PLAY, true);
startService(intent);
}
});
//Stop button
stopButton = (Button)findViewById(R.id.StopButton);
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get new MediaPlayerService activity
Intent intent = new Intent(getApplicationContext(),
RadioMediaPlayerService.class);
stopService(intent);
}
});
//Email Button click list
final View EmailPress = (Button)this.findViewById(R.id.emailBtn);
EmailPress.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto: "+settings.getEmailAddress()));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Radio Munnabuddu");
if (emailIntent.resolveActivity(getPackageManager()) != null){
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(HomeActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
});
//Website Button
final View WWWPress = (Button)this.findViewById(R.id.websiteBtn);
WWWPress.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(settings.getWebsiteURL())); //URL
startActivity (browserIntent);
}
});
//SMS Button
final View TxtPress = (Button)this.findViewById(R.id.txtBtn);
TxtPress.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Uri uri = Uri.parse(settings.getSmsNumber());
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "Hello Presenter,");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
/*
if (ActivityCompat.checkSelfPermission(HomeActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED){
Toast.makeText(HomeActivity.this, "Please grant the permission to call", Toast.LENGTH_SHORT).show();
requestSMSPermission();
}
else {
startActivity (smsIntent);
}*/
}
});
}
/**
* Launches webcam from external URL
*/
public void launchWebcam(){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(settings.getRadioWebcamURL()));
startActivity (browserIntent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
onCall();
} else {
Log.d("TAG", "Call Permission Not Granted");
//Toast.makeText(this, "Call Permission Not Granted", Toast.LENGTH_SHORT).show();
}
return;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public void onCall() {
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.CALL_PHONE},
REQUEST_CODE);
} else {
phoneCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
/*
String phoneNum = settings.getPhoneNumber();
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
phoneIntent.setData(Uri.parse("tel:"+ phoneNum));
if (phoneIntent.resolveActivity(getPackageManager()) != null) {
startActivity(phoneIntent);
}
*/
startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:" + settings.getPhoneNumber())));
}
});
}
}
This is the RadioMediaPlayerService.java
public class RadioMediaPlayerService extends Service implements
AudioManager.OnAudioFocusChangeListener {
//Variables
private boolean isPlaying = false;
private MediaPlayer radioPlayer; //The media player instance
private static int classID = 579; // just a number
public static String START_PLAY = "START_PLAY";
AudioManager audioManager;
//Media session
MediaSession mSession;
//Settings
RadioSettings settings = new RadioSettings();
#Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Starts the streaming service
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getBooleanExtra(START_PLAY, false)) {
play();
}
//Request audio focus
if (!requestAudioFocus()) {
//Could not gain focus
stopSelf();
}
return Service.START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
/**
* Starts radio URL stream
*/
private void play() {
//Check connectivity status
if (isOnline()) {
//Check if player already streaming
if (!isPlaying) {
isPlaying = true;
//Return to the current activity
Intent intent = new Intent(this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// mSession.setSessionActivity(pi);
//Build and show notification for radio playing
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
R.drawable.buddu3);
Notification notification = new NotificationCompat.Builder(this, "ID")
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setTicker("Radio Munnabuddu USA")
.setContentTitle(settings.getRadioName())
.setContentText(settings.getMainNotificationMessage())
.setSmallIcon(R.drawable.ic_radio_black_24dp)
//.addAction(R.drawable.ic_play_arrow_white_64dp, "Play", pi)
// .addAction(R.drawable.ic_pause_black_24dp, "Pause", pi)
.setLargeIcon(largeIcon)
.setContentIntent(pi)
.build();
//Get stream URL
radioPlayer = new MediaPlayer();
try {
radioPlayer.setDataSource(settings.getRadioStreamURL()); //Place URL here
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
radioPlayer.prepareAsync();
radioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
radioPlayer.start(); //Start radio stream
}
});
startForeground(classID, notification);
//Display toast notification
Toast.makeText(getApplicationContext(), settings.getPlayNotificationMessage(),
Toast.LENGTH_LONG).show();
}
}
else {
//Display no connectivity warning
Toast.makeText(getApplicationContext(), "No internet connection",
Toast.LENGTH_LONG).show();
}
}
/**
* Stops the stream if activity destroyed
*/
#Override
public void onDestroy() {
stop();
removeAudioFocus();
}
/**
* Stops audio from the active service
*/
private void stop() {
if (isPlaying) {
isPlaying = false;
if (radioPlayer != null) {
radioPlayer.release();
radioPlayer = null;
}
stopForeground(true);
}
Toast.makeText(getApplicationContext(), "Radio stopped",
Toast.LENGTH_LONG).show();
}
/**
* Checks if there is a data or internet connection before starting the stream.
* Displays Toast warning if there is no connection
* #return online status boolean
*/
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
public void onAudioFocusChange(int focusChange) {
//Invoked when the audio focus of the system is updated.
switch (focusChange) {
/*
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
// if (radioPlayer == null) initMediaPlayer();
if (radioPlayer.isPlaying()){
radioPlayer.release();
stopForeground(true);
}
radioPlayer.setVolume(1.0f, 1.0f);
break;*/
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (radioPlayer.isPlaying()) radioPlayer.stop();
radioPlayer.release();
//radioPlayer = null;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Lost focus for a short time, but we have to stop
// playback. We don't release the media player because playback
// is likely to resume
if (radioPlayer.isPlaying()) radioPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (radioPlayer.isPlaying()) radioPlayer.setVolume(0.1f, 0.1f);
break;
}
}
/**
* AudioFocus
*/
private boolean requestAudioFocus() {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//Focus gained
return true;
}
//Could not gain focus
return false;
}
private boolean removeAudioFocus() {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
audioManager.abandonAudioFocus(this);
}
}
This is the Manifest.xml
<!--uses-permission android:name="android.permission.SEND_SMS" /-->
<uses-permission android:name="android.permission.INTERNET" />
<!--uses-permission android:name="android.permission.CALL_PHONE" /-->
<!--tools:node="remove"-->
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<service
android:name="com.premar.radiomunabuddu.RadioMediaPlayerService"
android:enabled="true" >
</service>
<receiver android:name="com.premar.radiomunabuddu.IntentReceiver">
<intent-filter>
<action android:name="android.media.AUDIO_BECOMING_NOISY" />
</intent-filter>
</receiver>
<activity
android:name="com.premar.radiomunabuddu.HomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.premar.radiomunabuddu.AboutActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.premar.radiomunabuddu.HomeActivity" />
</activity>
</application>
Android 9 introduced a new FOREGROUND_SERVICE permission. From the docs:
Note: Apps that target Android 9 (API level 28) or higher and use foreground services must request the FOREGROUND_SERVICE permission. This is a normal permission, so the system automatically grants it to the requesting app.
If an app that targets API level 28 or higher attempts to create a foreground service without requesting FOREGROUND_SERVICE, the system throws a SecurityException.
Just add that permission to your manifest and you should be good to go.
The setServiceForegroundInnerLocked method will check based on the targetSdkVersion level。lack FOREGROUND_SERVICE permission
code:
if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
mAm.enforcePermission(
android.Manifest.permission.FOREGROUND_SERVICE,
r.app.pid, r.appInfo.uid, "startForeground");
}
Related
If there is no Internet, display a certain xml in full screen when the application starts, that there is no Internet, and if there is, perform MainActivity.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MaterialSearchBar.OnSearchActionListener, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
#SuppressLint("StaticFieldLeak")
public static MaterialSearchBar searchBar;
private DrawerLayout drawer;
private NavigationView navigationView;
private AdView mAdView;
private static List<String> listPermissionsNeeded;
public boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: setting things up");
StaticUtils.requestQueue = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Admob banner
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
mAdView.setVisibility(View.VISIBLE);
}
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
mAdView.setVisibility(View.GONE);
}
});
//restoring recent searches list
StaticUtils.recentSearchesList = getArrayList(StaticUtils.KEY_LIST_PREFERENCCES);
if (StaticUtils.recentSearchesList==null){
StaticUtils.recentSearchesList = new ArrayList<>();
}
StaticUtils.savedImagesList = new ArrayList<>();
searchBar = findViewById(R.id.searchToolBar);
searchBar.setHint("Search Wallpapers");
searchBar.setOnSearchActionListener(this);
searchBar.hideSuggestionsList();
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
//sets home fragment open by default
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
playLogoAudio(); //to play the logo audio
searchEvents(); //advanced search events
}
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed: back button invoked.");
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void grantPermissionBottomSheet(){
View dialogView = getLayoutInflater().inflate(R.layout.layout_bottomsheet, null);
final BottomSheetDialog dialog = new BottomSheetDialog(this);
Button ok = dialogView.findViewById(R.id.bt_bottomsheet);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: bottomSheet button clicked.");
requestPermissions(MainActivity.this);
dialog.dismiss();
}
});
dialog.setContentView(dialogView);
dialog.show();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d(TAG, "onNavigationItemSelected: navigation item pressed.");
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
} else if (id == R.id.nav_saved) {
NetworkUtils network = new NetworkUtils(this);
if(network.checkConnection(drawer)){ //if network connected
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,2);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"Saved");
startActivity(i);
}
}else if (id == R.id.nav_downloads) {
//downloaded images
if (permissionsGranted(this)) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID, 4); //4 for downloads section
i.putExtra(StaticUtils.KEY_SEARCH_DATA, "Downloads");
startActivity(i);
}else{
grantPermissionBottomSheet();
}
} else if (id == R.id.nav_share) {
//share the app intent
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey! look what I found from play store.\nDownload cool & amazing wallpapers for your device from this app, "+getResources().getString(R.string.app_name)+", among various categories.\n\nCheck this out:\n"+StaticUtils.playStoreUrlDefault+getPackageName()+"\nDownload now:)");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share app through..."));
} else if (id == R.id.nav_rate) {
//rate the app intent
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
}
} else if (id == R.id.nav_about) {
//about page
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,3); //3 for about fragment
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"About");
startActivity(i);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void playLogoAudio(){
Log.d(TAG, "playLogoAudio: playing logo audio");
View headerView = navigationView.getHeaderView(0);
ImageView drawerLogo = headerView.findViewById(R.id.imageLogo);
drawerLogo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.hello);
mediaPlayer.start();
}
});
}
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
#Override
public void onSearchStateChanged(boolean enabled) {
if (enabled){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SearchFragment()).commit();
}else{
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
Log.d(TAG, "onSearchConfirmed: confirmed search: "+text);
Intent i = new Intent(this,SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,1);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,String.valueOf(text));
if(new NetworkUtils(getApplicationContext()).checkConnection(drawer)) { //start intent if network connected
StaticUtils.recentSearchesList.add(String.valueOf(text)); //adds the query to the recents list
if (StaticUtils.recentSearchesList.size()>20){
StaticUtils.recentSearchesList.remove(0);
}
SearchFragment.updateAdapter(this,StaticUtils.recentSearchesList);
searchBar.setText(""); //removes the search query
startActivity(i);
}
}
#Override
public void onButtonClicked(int buttonCode) {
Log.d(TAG, "onButtonClicked: search interface button clicked: "+buttonCode);
switch (buttonCode){
case MaterialSearchBar.BUTTON_NAVIGATION:
drawer.openDrawer(GravityCompat.START);
break;
case MaterialSearchBar.BUTTON_BACK:
searchBar.disableSearch();
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {}
public void saveArrayList(ArrayList<String> list, String key){
Log.d(TAG, "saveArrayList: saving recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
Log.d(TAG, "getArrayList: getting saved recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
#Override
protected void onPause() {
super.onPause();
//Saving arraylist when activity gets paused
saveArrayList(StaticUtils.recentSearchesList,StaticUtils.KEY_LIST_PREFERENCCES);
}
public void searchEvents(){
Log.d(TAG, "searchEvents: managing the search events");
searchBar.addTextChangeListener(new TextWatcher() {
ArrayList<String> tempList = new ArrayList<>();
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.d(TAG, "beforeTextChanged: clearing the list");
if (!tempList.isEmpty()){
tempList.clear();
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d(TAG, "onTextChanged: changing search query");
for (String string : StaticUtils.recentSearchesList) {
if (s.length() > 0) {
if (string.matches("(?i)(" + s + ").*")) {
tempList.add(string);
SearchFragment.updateAdapter(getApplicationContext(), tempList);
}
}else{
SearchFragment.updateAdapter(getApplicationContext(), StaticUtils.recentSearchesList);
}
}
}
#Override
public void afterTextChanged(Editable s) {}
});
}
#Override
protected void onResume() {
super.onResume();
navigationView.setCheckedItem(R.id.nav_home);
if (!permissionsGranted(this)){ //checking and requesting permissions
grantPermissionBottomSheet();
}
}
public static boolean permissionsGranted(Context context) {
Log.d(TAG, "checkPermissions: checking if permissions granted.");
int result;
listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(context,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
//if all/some permissions not granted
return listPermissionsNeeded.isEmpty();
}
public static void requestPermissions(Activity activity){
Log.d(TAG, "requestPermissions: requesting permissions.");
ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toArray(new
String[listPermissionsNeeded.size()]), StaticUtils.MULTIPLE_PERMISSIONS);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: action when permission granted or denied");
if (requestCode == StaticUtils.MULTIPLE_PERMISSIONS) {
if (grantResults.length <= 0) {
// no permissions granted.
showPermissionDialog();
}
}
}
public void showPermissionDialog(){
Log.d(TAG, "showPermissionDialog: requesting permissions");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
builder.setMessage("You'll not be able to use this app properly without these permissions.");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//re-requesting permissions
requestPermissions(MainActivity.this);
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
}
I would suggest some kind of different flow.
Most apps have something called a "Splash screen" (usually with a logo, sometimes kind of a progress bar).
what you can do is create a splash activity, - if there is internet call your MainActiviy, otherwise call another activity NetworkErrorActivity with the XML you want.
I am getting error:-
"java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.juhi_gupta.pizza_corner/com.example.juhi_gupta.pizza_corner.SplashScreen}: java.lang.InstantiationException: java.lang.Class has no zero argument constructor"
What's going wrong in my code? I am new to Asynctask.
public class SplashScreen extends Activity {
Context context;
SplashScreen(Context context)
{
this.context = context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 3000;
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
if (isNetworkAvailable()) {
new CheckInternetAsyncTask(getApplicationContext()).execute();
}
else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("No Internet Connection");
alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "Please check your internet connection and try again", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
#SuppressLint("StaticFieldLeak")
class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private Context context;
CheckInternetAsyncTask(Context context) {
this.context = context;
}
#Override
protected Boolean doInBackground(Void... params) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
if (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0)
return true;
} catch (IOException e) {
Log.e("TAG", "Error checking internet connection", e);
Toast.makeText(getApplicationContext(), "Error checking internet connection", Toast.LENGTH_LONG).show();
return false;
}
} else {
Log.d("TAG", "No network available!");
Toast.makeText(getApplicationContext(), "No network available!", Toast.LENGTH_LONG).show();
return false;
}
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("TAG", "result" + result);
}
}
}
And my Manifest.xml file:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.juhi_gupta.pizza_corner">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<!-- Splash screen -->
<activity
android:name="com.example.juhi_gupta.pizza_corner.SplashScreen"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Solution: There are 2 corrections:
1. Remove this:
SplashScreen(Context context)
{
this.context = context;
}
Write this instead, inside your onCreate() just after the line setContentView(...):
this.context = SplashScreen.this;
2. Instead of this:
new CheckInternetAsyncTask(getApplicationContext()).execute();
Write this:
new CheckInternetAsyncTask(this.context).execute();
Then:
Remove this below mentioned code from your onCreate(..) and try disconnecting your wifi and run the app, It will show.
int SPLASH_TIME_OUT = 3000;
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
Write The above code inside onPostExecute(...):
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("TAG", "result" + result);
...... (Over Here)
}
Hope it works.
I make an app to read barcode numbers and I used a surface view with a camera source in it. The app send the value to another activity which is shown as a dialog.
I make other activity as dialog but the problem the surface view is stopped. I tried many solutions until this works which is to put these lines in onCreate method .
setTheme(android.R.style.Theme_DeviceDefault_Dialog);
requestWindowFeature(Window.FEATURE_NO_TITLE);
with adding these two lines in onCreate method the surface view didn't stop and it works but the problem is the dialog shown in black screen also the parent when the dialog is shown it turns all to black. how to fix this problem.
I also modified manifest to process that and I add the following
<activity android:name=".InfoActivity"
android:excludeFromRecents="true"
android:label="#string/app_name"
android:launchMode="singleInstance"
android:theme="#style/Theme.AppCompat.Light.Dialog">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
these the whole code of the class
public class MainActivity extends AppCompatActivity {
SurfaceView surfaceView;
BarcodeDetector barcodeDetector;
CameraSource cameraSource;
TextView txtShow, itemName, itemPrice, itemQuantity;
TextView txtNameDialog, txtPriceDialog, txtQuantityDialog;
final int RequestCameraPermissionId = 1001;
String code;
RequestQueue requestQueue;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case RequestCameraPermissionId: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.cameraPreview);
txtShow = (TextView) findViewById(R.id.txtShow);
itemName = (TextView) findViewById(R.id.itemName);
itemPrice = (TextView) findViewById(R.id.itemPrice);
itemQuantity = (TextView) findViewById(R.id.itemQuantity);
startBarcode();
}
public void startBarcode() {
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(800, 600)
.setAutoFocusEnabled(true)
.build();
//Events
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
txtShow.post(new Runnable() {
#Override
public void run() {
//stop camera
cameraSource.stop();
//create vibrate
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
//set result for Text View
txtShow.setText(qrCodes.valueAt(0).displayValue);
final String code = txtShow.getText().toString();
// surfaceView.setTop(200);
final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.barcode);
mp.start();
Button getInfo = (Button) findViewById(R.id.getInfo);
Intent intent = new Intent(MainActivity.this,InfoActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have been trying to create a basic flashlight app using an image button (beginner). Where i have no syntax errors in the code but do have have some NULL pointer exception in the run time.
Here is my main activity class :-
public class FlashLight extends Activity{
Camera camera = null;
Parameters params = null;
boolean isFlashOn = false;
boolean hasFlash;
ImageButton btnSwitch = (ImageButton) findViewById(R.id.imageButton1);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash)
{
AlertDialog alert = new AlertDialog.Builder(FlashLight.this).create();
alert.setTitle("Error");
alert.setMessage("Application Not Supported");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
return;
}
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
// Switch button click event to toggle flash on/off
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
private void getCamera() {
if(camera == null)
{
try{
camera = Camera.open();
params = camera.getParameters();
}
catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
private void toggleButtonImage() {
try{
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.switchon);
}else{
btnSwitch.setImageResource(R.drawable.switchoff);
}
}
catch(RuntimeException e){
Log.e("Could not toggle Button image ", e.getMessage());
}
}
private void turnOnFlash() {
try{
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
catch(RuntimeException e){
Log.e("Could not turn on Flash ", e.getMessage());
}
}
private void turnOffFlash() {
try{
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
catch(RuntimeException e){
Log.e("Could not turn off flash ", e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.flash_light, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
while here is my manifest file :-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flashlight"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="FlashLight"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Please, help in the identification of the following error in the logcat menu:-
02-10 23:18:23.409: E/AndroidRuntime(13237): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.flashlight/com.example.flashlight.FlashLight}: java.lang.NullPointerException
ImageButton btnSwitch gives you NULL Pointer, you don't have
setContentView(R.layout.name_of_your_activity);
Change this and it will work:
Camera camera = null;
Camera.Parameters params = null;
boolean isFlashOn = false;
boolean hasFlash;
ImageButton btnSwitch; //add this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.name_of_your_xml_layout_for_activity);//add this
btnSwitch=(ImageButton)findViewById(R.id.imageButton1);//add this
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);...
I am following the patterns that are used in the Compass example in a new project and have most of the logic working. However, when I tap while my live card is displayed I hear the 'click' noise but my menu activity doesn't display. I think that I am missing a piece of the puzzle, but I have not been able to figure out what as of yet.
When I tap, besides the click, I also see this in logcat:
01-08 10:02:26.796: I/ActivityManager(196): START {flg=0x10008000 cmp=com.example.speeddisplay/.SpeedDisplayMenuActivity} from pid -1
So it looks like it should be starting my activity, but it doesn't show up. Here are some pieces of relevant code...although I am not sure where the issue is.
Service portion in AndroidManifest.xml:
<service
android:name="com.example.speeddisplay.service.SpeedService"
android:enabled="true"
android:icon="#drawable/ic_drive_50"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.google.android.glass.action.VOICE_TRIGGER" />
</intent-filter>
<meta-data
android:name="com.google.android.glass.VoiceTrigger"
android:resource="#xml/voiceinput_speeddisplay" />
</service>
onStartCommand method in SpeedService.java:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Constants.DEBUG) {
Log.d(TAG, "onStartCommand");
}
if (liveCard == null) {
liveCard = timelineManager.createLiveCard(LIVE_CARD_ID);
speedRenderer = new SpeedRenderer(this, speedManager);
liveCard.setDirectRenderingEnabled(true);
liveCard.getSurfaceHolder().addCallback(speedRenderer);
// Display the options menu when the live card is tapped.
Intent menuIntent = new Intent(this, SpeedDisplayMenuActivity.class);
menuIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
liveCard.setAction(PendingIntent.getActivity(this, 0, menuIntent, 0));
liveCard.publish(PublishMode.REVEAL);
if(Constants.DEBUG){
Log.d(TAG, "liveCard published");
}
}
return START_STICKY;
}
Here is my SpeedDisplayMenuActivity.java. None of these methods are getting called.
public class SpeedDisplayMenuActivity extends Activity {
private SpeedService.SpeedBinder speedService;
private boolean mResumed;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (Constants.DEBUG) {
Log.e("Service Stuff", "Service connected.");
}
if (service instanceof SpeedService.SpeedBinder) {
speedService = (SpeedService.SpeedBinder) service;
openOptionsMenu();
}
if (Constants.DEBUG) {
Log.e("Service Stuff", "service was an instance of " + service.getClass().getName());
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
// Do nothing.
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
if(Constants.DEBUG){
Log.e("Menu", "Created.");
}
super.onCreate(savedInstanceState);
bindService(new Intent(this, SpeedService.class), mConnection, 0);
}
#Override
protected void onResume() {
if(Constants.DEBUG){
Log.e("Menu", "Resumed.");
}
super.onResume();
mResumed = true;
openOptionsMenu();
}
#Override
protected void onPause() {
if(Constants.DEBUG){
Log.e("Menu", "Paused.");
}
super.onPause();
mResumed = false;
}
#Override
public void openOptionsMenu() {
if (Constants.DEBUG) {
Log.e("Options Menu", "Open");
}
if (mResumed && speedService != null) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Open with correct params");
}
super.openOptionsMenu();
} else {
if (Constants.DEBUG) {
Log.e("Options Menu", "Open with INCORRECT params");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Created");
}
getMenuInflater().inflate(R.menu.speed, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Item Selected");
}
switch (item.getItemId()) {
// case R.id.read_aloud:
// mCompassService.readHeadingAloud();
// return true;
case R.id.stop:
if (Constants.DEBUG) {
Log.e("Options Menu", "Stop");
}
stopService(new Intent(this, SpeedService.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onOptionsMenuClosed(Menu menu) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Closed");
}
super.onOptionsMenuClosed(menu);
unbindService(mConnection);
// We must call finish() from this method to ensure that the activity
// ends either when an
// item is selected from the menu or when the menu is dismissed by
// swiping down.
finish();
}
Does anybody see what I am missing?
That is right, declaring the SpeedDisplayMenuActivity is the problem in this case.
I have seen cases where many other types of exceptions / crash that normally happens in Android environment is gracefully handled in Glass.
That is definitely good for the user experience, but makes little tough on development. Hopefully some kind of settings come in future to enable exceptions as well in future!