public void CameraOnClick(){
using (AndroidJavaClass javaClass = new AndroidJavaClass ("com.d3d.viewer.NativePlugin")) {
using (AndroidJavaObject currentActivity = javaClass.CallStatic<AndroidJavaObject> ("instance")) {
Debug.Log ("Start Camera############");
//javaClass.CallStatic ("showCamera");
currentActivity.Call("showCamera");
}
}
}
public void getimageUrl1(string ImageUrl){
imageurl1 = ImageUrl;
Debug.Log ("ImageUrl11111111111111111111"+ImageUrl);
}
Android source
public class NativePlugin extends UnityPlayerActivity {
final Activity b = m_instance;
final Activity a = UnityPlayer.currentActivity;
private static NativePlugin m_instance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UnityPlayer.UnitySendMessage("PlusPopupManager","getimageUrl1","22222"); //don't activate
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
public static NativePlugin instance()
{
if(m_instance == null)
{
m_instance = new NativePlugin();
}
return m_instance;
}
public void showCamera () // Connect Camera
{
UnityPlayer.UnitySendMessage("PlusPopupManager","getimageUrl1","111111"); //activate
a.runOnUiThread(new Runnable()
{
public void run() {
Intent intent = new Intent(a, NativePlugin.class);
a.startActivity(intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
UnityPlayer.UnitySendMessage("PlusPopupManager","getimageUrl1","333333");//don't activate
}
}
manifast.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.d3d.viewer">
<application android:allowBackup="true" android:label="#string/app_name"
android:supportsRtl="true">
<activity android:name="com.d3d.viewer.NativePlugin" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:label="#string/app_name" android:screenOrientation="landscape" android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera.autofocus"/>
</manifest>
I make ARR android plugins.and import Unity3d.
'UnityPlayer.UnitySendMessage' is activated when I call 'showCamera'.
but don't activate when I call intent( NativePlugin) funtion.
why don't call 'UnityPlayer.UnitySendMessage' funtion on android activity.
Related
I have a list view that displays all the songs in my device in the application, then when I click on the song another activity opens where you can play the song, on emulator when I click on the song in the list it takes me to the other activity and I can play and hear the song, but on real device I'm not getting any error but when I select an item from the list, I get the name and artist of the song, but when i click on play it doesn't work, I don't hear sound nor can I jump to middle of song etc..
the list is like this:
When clicked:
I'm using media player to read the audio files, and the code for my main activity is:
public class MusicPlayerOffline extends AppCompatActivity implements View.OnClickListener {
TextView tvTime,tvDuration,tvTitle,tvArtist;
SeekBar seekBarTime,seekBarVolume;
Button btnPlay;
MediaPlayer musicPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player_offline);
Songs song = (Songs) getIntent().getSerializableExtra("song");
tvTime=findViewById(R.id.tvTime);
tvDuration=findViewById(R.id.tvDuration);
seekBarTime=findViewById(R.id.seekBarTime);
seekBarVolume=findViewById(R.id.seekBarVolume);
btnPlay=findViewById(R.id.btnPlay);
tvTitle=findViewById(R.id.tvTitle);
tvArtist=findViewById(R.id.tvArtist);
tvTitle.setText(song.getTitle());
tvArtist.setText(song.getArtist());
musicPlayer=new MediaPlayer();
try {
musicPlayer.setDataSource(song.getPath());
musicPlayer.prepare();
}catch (IOException e){
e.printStackTrace();
}
musicPlayer.setLooping(true);
musicPlayer.seekTo(0);
musicPlayer.setVolume(0.5f, 0.5f);
String duration = millisecondsToString(musicPlayer.getDuration());
tvDuration.setText(duration);
btnPlay.setOnClickListener(this );
seekBarVolume.setProgress(50);
seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float volume = progress /100f;
musicPlayer.setVolume(volume, volume);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBarTime.setMax(musicPlayer.getDuration());
seekBarTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
musicPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
new Thread(new Runnable() {
#Override
public void run() {
while (musicPlayer != null){
if (musicPlayer.isPlaying()){
try {
final double current = musicPlayer.getCurrentPosition();
final String elapsdTime = millisecondsToString((int) current);
runOnUiThread(new Runnable() {
#Override
public void run() {
tvTime.setText(elapsdTime);
seekBarTime.setProgress((int) current);
}
});
Thread.sleep(1000);
}catch (InterruptedException e){}
}
}
}
}).start();
}// end main
public String millisecondsToString(int time){
String elapsedTime = "";
int minutes = time / 1000 / 60;
int seconds = time / 1000 % 60;
elapsedTime = minutes+":";
if (seconds < 10){
elapsedTime += "0";
}
elapsedTime += seconds;
return elapsedTime;
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnPlay){
if (musicPlayer.isPlaying()){
// is playing
musicPlayer.pause();
btnPlay.setBackgroundResource(R.drawable.ic_play);
}else {
// on pause
musicPlayer.start();
btnPlay.setBackgroundResource(R.drawable.ic_pause);
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home){
finish();
if (musicPlayer.isPlaying()){
musicPlayer.stop();
}
}
return super.onOptionsItemSelected(item);
}
}
The code for my listviewmusic activity from where I retrieve title artist and audio is:
public class ListMusicActivity extends AppCompatActivity {
private static final int REQUEST_PERMISSION = 99;
ArrayList<Songs> songArrayList;
ListView tvSongs;
SongsAdapter songsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_music);
tvSongs = findViewById(R.id.tvSongs);
songArrayList = new ArrayList<>();
songsAdapter = new SongsAdapter(this, songArrayList);
tvSongs.setAdapter(songsAdapter);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
return;
}else {
// you have permission to read from external storage
getSongs();
}
tvSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Songs song = songArrayList.get(position);
Intent openMusicPlayer = new Intent(ListMusicActivity.this, MusicPlayerOffline.class);
openMusicPlayer.putExtra("song", song);
startActivity(openMusicPlayer);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSION){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
getSongs();
}
}
}
private void getSongs() {
// read songs from phone
ContentResolver contentProvider = getContentResolver();
Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor songCursor = contentProvider.query(songUri,null,null,null,null);
if (songCursor != null && songCursor.moveToNext()) {
int indexTitle = songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int indexArtist = songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int indexData = songCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
do {
String title = songCursor.getString(indexTitle);
String artist = songCursor.getString(indexArtist);
String path = songCursor.getString(indexData);
songArrayList.add(new Songs(title, artist, path));
}while (songCursor.moveToNext());
}
songsAdapter.notifyDataSetChanged();
}
}
My adapter:
public class SongsAdapter extends ArrayAdapter<Songs> {
public SongsAdapter(#NonNull Context context, #NonNull List<Songs> objects) {
super(context,0, objects);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_song, null);
TextView tvTitle = convertView.findViewById(R.id.tvTitle);
TextView tvArtist = convertView.findViewById(R.id.tvArtist);
Songs song = getItem(position);
tvTitle.setText(song.getTitle());
tvArtist.setText(song.getArtist());
return convertView;
}
}
I have no idea why it's not working, I don't get any error in the logcat, the music just doesn't start, it stays frozen at 0:00, and I cant jump to middle of it etc, although the name and artist name get obtained successfully just no audio
My manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.smallacademy.authenticatorapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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"
android:windowSoftInputMode="adjustPan">
<activity android:name=".ListMusicActivity"></activity>
<activity android:name=".MusicPlayerOffline" />
<activity android:name=".MusicplayerOnline" />
<activity android:name=".Musicplayer" />
<activity
android:name=".Admin_crud_Illness"
android:theme="#style/Theme.AppCompat.DayNight.DarkActionBar" />
<activity
android:name=".Admin_crud_food"
android:theme="#style/Theme.AppCompat.DayNight.DarkActionBar"
android:windowSoftInputMode="adjustPan" />
<activity android:name=".CaloriesCounterAdmin" />
<activity android:name=".Admin_addIllness" />
<activity android:name=".Admin_addfood" />
<activity android:name=".WaterInfo" />
<activity android:name=".WaterIntake" />
<activity android:name=".Share" />
<activity android:name=".Weather_Act" />
<activity android:name=".CalorieCounter" />
<activity android:name=".FetchFeedbacks" />
<activity android:name=".AdminHome" />
<activity android:name=".FeedBack" />
<activity android:name=".AdminDel" />
<activity android:name=".UpdateData" />
<activity android:name=".Fetchdata" />
<activity android:name=".Admin_add" />
<activity android:name=".BmiInfo" />
<activity android:name=".AdminAct" />
<activity android:name=".Loseweight_nutrition" />
<activity android:name=".Maintainweight_nutrition" />
<activity android:name=".Overweight_nutrition" />
<activity android:name=".Nutrition" />
<activity android:name=".CalmMood" />
<activity android:name=".AnnoyedMood" />
<activity android:name=".AngryMood" />
<activity android:name=".SadMood" />
<activity android:name=".HappyMood" />
<activity android:name=".MoodFeature" />
<activity android:name=".Calendar" />
<activity android:name=".Alarm" />
<activity
android:name=".StopWatch"
android:parentActivityName=".Home" />
<activity android:name=".Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Exercice"
android:windowSoftInputMode="adjustPan" />
<activity android:name=".BMI_Calculator" />
<activity android:name=".Home" />
<activity android:name=".EditProfile" />
<activity android:name=".Login" />
<activity android:name=".Register" />
<activity android:name=".MainActivity" />
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<receiver
android:name=".AlertReceiver"
android:enabled="true"
android:exported="true"
android:process=":remote" />
</application>
</manifest>
I am trying to send a simple message from my wear [Emulator] to my android phone, The message should have been sent according to my logs on the wear but it does not trigger my "showToast" method on my phone [it should be triggered when a message is received]. Anyone has an idea what I could be doing wrong?
This is my Wear Manifest
<manifest package="georgikoemdzhiev.weartesttwo"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature android:name="android.hardware.type.watch"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<uses-library
android:name="com.google.android.wearable"
android:required="false"/>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault.Light">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
This is my Mobile manifest
<manifest package="georgikoemdzhiev.weartesttwo"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
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>
<service android:name=".ReceiveMessageService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="/prefix" />
</intent-filter>
</service>
</application>
This is my Wear logic [I have a button that sends the showToast message]
public class MainActivity extends WearableActivity {
private static final long CONNECTION_TIME_OUT_MS = 2500;
private static final String TAG = MainActivity.class.getSimpleName();
private CircularButton mSendButton;
private List<Node> myNodes = new ArrayList<>();
private static final SimpleDateFormat AMBIENT_DATE_FORMAT =
new SimpleDateFormat("HH:mm", Locale.UK);
private BoxInsetLayout mContainerView;
private TextView mTextView;
private TextView mClockView;
private GoogleApiClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAmbientEnabled();
mSendButton = (CircularButton)findViewById(R.id.sendToast);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendToastMessage();
}
});
mClient = new GoogleApiClient.Builder(this)
.addApiIfAvailable(Wearable.API)
.build();
getNodes();
mContainerView = (BoxInsetLayout) findViewById(R.id.container);
mTextView = (TextView) findViewById(R.id.text);
mClockView = (TextView) findViewById(R.id.clock);
}
private void sendToastMessage() {
Log.d(TAG,"Sending message... Nodes List size:" + myNodes.size());
// send toast message logic...
new Thread(new Runnable() {
#Override
public void run() {
for(Node n:myNodes) {
Log.d(TAG,"Sending message to node:"+n.getDisplayName());
Wearable.MessageApi.sendMessage(mClient,n.getId(),"/showToast",null);
}
}
});
}
private List<Node> getNodes(){
new Thread(new Runnable() {
//
#Override
public void run() {
Log.d(TAG,"Getting nodes...");
mClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
NodeApi.GetConnectedNodesResult result = Wearable.NodeApi.getConnectedNodes(mClient).await();
List<Node> nodes = result.getNodes();
for(Node n:nodes){
Log.d(TAG,"Adding Node: "+n.getDisplayName());
myNodes.add(n);
}
Log.d(TAG,"Getting nodes DONE!");
}
}).start();
return null;
}
}
This is my ReceiveMessageService in Mobile
public class ReceiveMessageService extends WearableListenerService {
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.d("ReceiveMessageService","onMessageReceived");
//if(messageEvent.getPath().equals("/showToast")) {
showToast(messageEvent.getPath());
//}
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
This is my MainActivity in Mobile
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private static final String TAG = MainActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG,"onConnected");
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG,"onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG,"onConnectionFailed");
}
It looks like you are using wrong pathPrefix in your mobile side AndroidManifest. Try to replace
<data android:scheme="wear" android:host="*" android:pathPrefix="/prefix" />
with
<data android:scheme="wear" android:host="*" android:pathPrefix="/showToast" />
Edit
Also keep in mind that MessageApi is not guarantee to deliver a message even if it returns a successful result code as Google's document stated:
Note: A successful result code does not guarantee delivery of the message. If your app requires data reliability, use DataItem objects or the ChannelApi class to send data between devices.
I have a wearable app that has a couple of fragments created with FragmentGridPagerAdapter. One of the fragments has a couple of CircularButtons and I want to update the backcolor of the button when a message is received from handheld phone. I have no problems in receiving the message. However, button's color (or anything in UI) doesn't update. Do you know how can I fix this?
public class UIPageAdapter extends FragmentGridPagerAdapter {
private final Context mContext;
MainControlFragment[] mainControlFragments;
private List mRows;
uiChangeListener mUIChangeListener = new uiChangeListener();
public UIPageAdapter(Context ctx, FragmentManager fm) {
super(fm);
Log.i("pageAdapter", "constructor");
mContext = ctx;
mainControlFragments = new MainControlFragment[2];
mainControlFragments[0] = new MainControlFragment();
mainControlFragments[1] = new MainControlFragment();
LocalBroadcastManager.getInstance(ctx).registerReceiver(mUIChangeListener,new IntentFilter(Constants.BROADCAST_CONTROL_HOME));
}
#Override
public Fragment getFragment(int row, int col) {
Log.i("PageAdapter","Fragment #" + col +"is asked");
return mainControlFragments[col];
}
public void changeStatus(int button, boolean status) {
mainControlFragments[0].setStatus(button,status);
// notifyDataSetChanged();
}
public class uiChangeListener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String act = intent.getAction();
if (act == Constants.BROADCAST_CONTROL_HOME) {
int key = intent.getIntExtra(Constants.CONTROL_HOME_KEY,-1);
String command = intent.getStringExtra(Constants.CONTROL_HOME_COMMAND);
changeStatus(key,command.equals("on"));
}
}
}
#Override
public int getRowCount() {
return 1;
}
#Override
public int getColumnCount(int i) {
return 2;
}
}
Basically when a message received from the handheld device a WearableListener class broadcasts an update message to the UIPageAdapter
This is the listener class
public class ListenerService extends WearableListenerService
{
String tag = "ListenerService";
#Override
public void onMessageReceived(MessageEvent messageEvent) {
final String message = (new String(messageEvent.getData()));
Log.i(tag,message);
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(Constants.BROADCAST_CONTROL_HOME)
.putExtra(Constants.CONTROL_HOME_KEY, messageEvent.getPath())
.putExtra(Constants.CONTROL_HOME_COMMAND,Integer.parseInt(message.substring(1)))
.putExtra("caller",tag));
}
#Override
public void onCreate() {
super.onCreate();
Log.i(tag, "onCreate");
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="smartstuff.com.tr.myautomationtool" >
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<uses-library
android:name="com.google.android.wearable"
android:required="false" />
<service android:name=".ListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault.Light" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Finally the custom fragment
public class MainControlFragment extends Fragment{
ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("controlFragment","create");
this.container = container;
// Inflate the layout for this fragment
return inflater.inflate(R.layout.main_control, container, false);
}
public void setStatus(int button, boolean status) {
Log.i("controlFragment",button + " "+ status);
CircularButton[] btns = new CircularButton[4];
btns[0] = (CircularButton) container.findViewById(R.id.cbtnFront);
btns[1] = (CircularButton) container.findViewById(R.id.cbtnBack);
btns[2] = (CircularButton) container.findViewById(R.id.cbtnBed);
btns[3] = (CircularButton) container.findViewById(R.id.cbtnCoffee);
btns[button].setColor(status?Color.BLACK:Color.RED);
}
}
I also tried the notifyDataSetChanged(); method in UIPageAdapter however it it only calls onCreateView method in fragment. Any help is appreciated
I'm assuming you already resolved this but I had to add a call to invalidate() on the CircularButton after calling setColor():
_circularButton.setColor(ContextCompat.getColor(getActivity(), buttonColor));
_circularButton.invalidate();
Without the call to invalidate the UI only updated some of the time.
I'm trying to integrate Facebook login using >Facebook SDK LoginUsingLoginFragmentActivity
It is giving me error:
MainActivityCode:
public class LoginActivity extends Activity {
private Button mFacebookLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login);
mFacebookLogin = (Button) findViewById(R.id.btnFacebookLogin);
mFacebookLogin.setOnClickListener(mOnClickListener);
}
private OnClickListener mOnClickListener = new OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnFacebookLogin:
Intent intent = new Intent(LoginActivity.this, LoginIntoFacebookActivity.class);
startActivity(intent);
break;
default:
break;
}
}
};
}
LoginIntoFacebookActivity.java
public class LoginIntoFacebookActivity extends FragmentActivity {
private UserSettingsFragment userSettingsFragment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_fragment_activity);
FragmentManager fragmentManager = getSupportFragmentManager();
userSettingsFragment = (UserSettingsFragment) fragmentManager.findFragmentById(R.id.login_fragment);
userSettingsFragment.setSessionStatusCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
Log.d("LoginUsingLoginFragmentActivity", String.format("New session state: %s", state.toString()));
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
userSettingsFragment.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
Error Trace:
E/AndroidRuntime(2901): FATAL EXCEPTION: main
06-14 13:46:28.087:
E/AndroidRuntime(2901): java.lang.NoClassDefFoundError: com.example.LoginIntoFacebookActivity
E/AndroidRuntime(2901): at com.example.activity.LoginActivity$1.onClick(LoginActivity.java:31)
Line 31:
Intent intent = new Intent(MainLoginActivity.this, LoginIntoFacebookActivity.class);
Manifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.activity.MainLoginActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.LoginActivity"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
<activity android:name="com.example.activity.LoginIntoFacebookActivity" />
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/app_id" />
</application>
It may be that the AndroidManifest file has wrong information about which package LoginIntoFacebookActivity belongs to - there's a mismatch between the error trace you've posted and the manifest file.
I try to create Twitter client and now I deal with authorization via OAuth protocol. I have created "Sign In" button to come in WebView and load twitter authorization URL, that's work. However, when the authorization is accepted successfuly and Twitter service redirect me to my callback I receive error web page in WebView. That is to say I am not redirected to my activity, I still stay in WebView. But if try the same way via browser, it`s working. What the problem is that?
Main Activivty:
public class Twitter extends Activity implements OnClickListener {
Button bSignIn;
TextView status;
private OAuthConsumer consumer;
private OAuthProvider provider;
private String url;
final String TAG = getClass().getName();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
bSignIn = (Button) findViewById(R.id.bSignIn);
status = (TextView) findViewById(R.id.tvStatus);
bSignIn.setOnClickListener(this);
}
public void onClick(View v) {
new OAuthWebViewProcess().execute();
}
public class OAuthWebViewProcess extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Twitter.this, null,
"Connecting, please wait...");
}
protected Void doInBackground(Void... params) {
try {
consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,
Constants.ACCESS_URL, Constants.AUTHORIZE_URL);
url = provider.retrieveRequestToken(consumer,
Constants.OAUTH_CALLBACK_URL);
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
return null;
}
protected void onPostExecute(Void result) {
//Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
Intent i = new Intent(Twitter.this, TwitterWebView.class);
i.putExtra("url", Uri.parse(url).toString());
startActivityForResult(i, 1);
dialog.dismiss();
}
}
}
WebView for Twitter:
public class TwitterWebView extends Activity {
String url;
WebView TwitterWebView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twitterwebview);
Bundle extras = getIntent().getExtras();
url = extras.getString("url");
try {
TwitterWebView = (WebView) findViewById(R.id.wvTwitter);
TwitterWebView.setWebViewClient(new TwitterWebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
TwitterWebView.getSettings().setJavaScriptEnabled(true);
TwitterWebView.getSettings().setDomStorageEnabled(true);
TwitterWebView.getSettings().setSavePassword(false);
TwitterWebView.getSettings().setSaveFormData(false);
TwitterWebView.getSettings().setSupportZoom(false);
TwitterWebView.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="wixanz.app.twitter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".Twitter"
android:label="#string/app_name"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".TwitterWebView"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
</activity>
<activity
android:name=".TweetList"
android:label="TweetList"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="callback"
android:scheme="twitter" />
</intent-filter>
</activity>
</application>
</manifest>
I did the same about others networks like LinkedIn, Foursquare. But instead of use the callback URL, I override the method shouldOverrideUrlLoading (WebView view, String url) in your WebViewClient (which is used to show the login page) to catch the access token and the token secret (if needed) by myself.