I'm trying to integrate twitter to my app, but I can't seem to get it to work.
This is my code:
public class OAuthForTwitter extends Activity {
private CommonsHttpOAuthConsumer httpOauthConsumer;
private OAuthProvider httpOauthprovider;
public final static String consumerKey = "{removed}";
public final static String consumerSecret = "{removed}";
private final String CALLBACKURL = "sosInternational:///HierBenIkNu";
private Twitter twitter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
doOAuth();
}
/**
* Opens the browser using signpost jar with application specific
* consumerkey and consumerSecret.
*/
private void doOAuth() {
try {
httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
httpOauthprovider = new DefaultOAuthProvider(
"http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, CALLBACKURL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(CALLBACKURL)) {
String verifier = uri
.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try {
// this will populate token and token_secret in consumer
httpOauthprovider.retrieveAccessToken(httpOauthConsumer,
verifier);
// TODO: you might want to store token and token_secret in you
// app settings!!!!!!!!
AccessToken a = new AccessToken(httpOauthConsumer.getToken(),
httpOauthConsumer.getTokenSecret());
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
twitter.setOAuthAccessToken(a);
// create a tweet
Date d = new Date(System.currentTimeMillis());
String tweet = "#OAuth working! " + d.toLocaleString();
// send the tweet
twitter.updateStatus(tweet);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
When I'm done authenticating on the Twitter site, it should redirect me back to the app.
But instead, I get this Page not found:
I have this in my AndroidManifest:
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
<category android:name="android.intent.category.DEFAULT"></category>
<category android:name="android.intent.category.BROWSABLE"></category>
<data android:scheme="sosInternational" android:host="HierBenIkNu"></data>
</intent-filter>
How can I go back to my app with the keys i get back?
Ok, it was quite a dumb mistake.
My <intent-filter> wasn't inside an application..
This is how it is now:
<activity
android:name=".OAuthForTwitter"
android:label="#string/app_name"
android:configChanges="orientation|keyboardHidden"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
<category android:name="android.intent.category.DEFAULT"></category>
<category android:name="android.intent.category.BROWSABLE"></category>
<data android:scheme="sosInternational" android:host="OAuthForTwitter"></data>
</intent-filter>
</activity>
This kind off works, it just loads the whole app from start.
Isn't there a way to just 'go back' to the last activity without restarting the whole app?
I have solved this. Not exactly the way you have developed, but a slight different way. Here are the steps describing what i did.
Use webview instead of opening it in web browser: One of the key advantage doing it is , you can track the url redirects.
call setWebViewClient method of your webview and override shouldOverrideUrlLoading method of your class, i have used inner class.
You will have url parameter in your method. Check whether it starts with your own call back url or not, (Note: This url contains User Token and user secret that is necessary for authorization).
After you finish your task, you can hide the activity or remove the webView or any thing you desire.
EDIT : This is the oAuth way usually used in web application, so we don't need xAuth way. (In case other community members don't know)
Hope it will help you.
Your callback URL should be "sosInternational://HierBenIkNu" (instead of "sosInternational:///HierBenIkNu") in the Java code.
private final String CALLBACKURL = "sosInternational://HierBenIkNu";
Related
Firebase notification is not working properly with a specific project.
If I sent notification from the console to all devices it did not work.
If I tried to send a notification via REST. its returns with the below response.
{
"multicast_id": ....,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}
Update : 2
I have created another project on the firebase console, delete resources and keys from the old project, then I have set up a new android application in the new project.
The result was the same, not receiving any notification The rest result was also the same.
But.
When I add another android application in the same project, then I was able to send notifications from a console-specific to that app, also from the rest API using token.
when I tried the original application token, I have the error. I am not able to find the issue ?. the registration part and initialization part was the same in the application.
Manifest Looks like.
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/purple_700" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id" />
<service
android:name=".CustomFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
App.java
public class App extends Application
{
#Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(this);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(getString(R.string.default_notification_channel_id),"X1",NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
Token Generate.
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
Log.d(TAG, "onComplete() called with: task = [" + task + "]");
if(task.isSuccessful())
{
Log.d(TAG, "onComplete() called with: task = [" + task.getResult() + "]");
}
}
});
I have tried the same code with different projects and it's working fine.
I don't know what's wrong!.
I have an AccessibilityService which was working fine but for some reason during development it stopped working. I can't seem to find that reason. Please have a look at my code and tell why it isn't working.
public class MyServicee extends AccessibilityService {
public static final String TAG = "volumeMaster";
#TargetApi(Build.VERSION_CODES.KITKAT)
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
List<CharSequence> eventText;
Log.v(TAG, "***** onAccessibilityEvent");
final int eventType = event.getEventType();
switch (eventType) {
case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
break;
}
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_CLICKED) {
}
}
private String processUSSDText(List<CharSequence> eventText) {
for (CharSequence s : eventText) {
String text = String.valueOf(s);
if (true) {
return text;
}
}
return null;
}
#Override
public void onInterrupt() {
Log.v(TAG, "***** onInterrupt");
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onServiceConnected() {
Log.v(TAG, "***** onServiceConnected");
AccessibilityServiceInfo info = getServiceInfo();
info.eventTypes =
AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED
| AccessibilityEvent.TYPE_VIEW_CLICKED
| AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
info.packageNames = new String[]{"com.whatsapp"};
info.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
setServiceInfo(info);
super.onServiceConnected();
}
}
Here's the relevant part of Manifest:
<service android:name=".MyServicee"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:enabled="true">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice"
android:resource="#xml/myservice" />
</service>
Here's myserviceconfig.xml:
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeViewClicked|typeNotificationStateChanged|typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackAllMask"
android:canRetrieveWindowContent="true"
android:accessibilityFlags="flagIncludeNotImportantViews|flagRequestFilterKeyEvents"
android:notificationTimeout="1"
android:packageNames="com.whatsapp"
android:settingsActivity="#string/app_name" />
The code attempts to detect when the user has started a call recording service.
There are a few problems with your configuration:
First in your onServiceConnected function, you overwrite the system constructed accessibility info.
AccessibilityServiceInfo info = getServiceInfo();
info.eventTypes =
AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED
| AccessibilityEvent.TYPE_VIEW_CLICKED
| AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
info.packageNames = new String[]{"com.whatsapp"};
info.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
setServiceInfo(info);
super.onServiceConnected();
This entire block of code is unnecessary and is all accomplished by the similar lines in your serviceConfig XML file. Just omit it, if you can't omit it, there is a problem with your configuration, though everything outside of this seems to be fine.
Now, speaking of letting your service_config xml file speak for itself, let's talk about a couple of lines in here:
android:notificationTimeout="1"
A notification timeout of 1 MS is essentially worthless.
android:packageNames="com.whatsapp"
Do you really want to limit accessibility events to just one application?
android:settingsActivity="#string/app_name"
This is an absolutely invalid value for the settingsActivity property. The settings activity should be the name of an activity class within your application. EX: com.yourpackage.SettingsActivity. This property can be safely omitted.
Aside from this information it is fairly easy to get accessibility services in a completely stale state. Have a daemon service, running in the background, keeping your service form starting but NOT actually doing productive things. The only way to fix this is to restart your device. Sometimes you even have to uninstall your package and then restart your device and then reinstall your package.
I'm developing an android application which needs to consume rest apis deployed, for now, on an heroku instance...since i got crashes anytime i try to integrate retrofit as http client I've done the following:
Added retrofit2 as dependendcy (didn't choose the latest version in order to avoid potential maturity problems)
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.google.code.gson:gson:2.6.2'
I coded an example android app, just to check if something has been done wrong in my original app, using http://httpbin.org/ip
public interface HttpBinService
{
public static class Response
{
private String origin;
public Response(String origin) {
this.origin = origin;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
}
#GET("ip")
public Call<Response> getIp ();
}
And the main activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Retrofit setup
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://httpbin.org")
.addConverterFactory(GsonConverterFactory.create())
.build();
// Service setup
HttpBinService service = retrofit.create(HttpBinService.class);
try {
Call<HttpBinService.Response> call = service.getIp();
Response<HttpBinService.Response> res = call.execute();
if (res.isSuccessful()){
Log.i("PROVARETROFIT", "OK");
((TextView)findViewById(R.id.testo)).setText(res.body().getOrigin());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I did not forget to ask for internet permissions in my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.spich.provaretrofit">
<uses-permission android:name="android.permission.INTERNET"/>
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
But all i got is that application closes unexpectedly. If t execute it in debug, it executes correctly all steps until call execution. LogCat appears to not say anything useful
04-15 09:48:08.281 6491-6491/? I/art: Late-enabling -Xcheck:jni
04-15 09:48:08.367 6491-6491/? W/System: ClassLoader referenced unknown path: /data/app/it.spich.provaretrofit-1/lib/arm64
04-15 09:48:08.387 6491-6491/it.spich.provaretrofit I/HwCust: Constructor found for class android.app.HwCustHwWallpaperManagerImpl
04-15 09:48:08.577 6491-6491/? I/Process: Sending signal. PID: 6491 SIG: 9
Has someone idea of what is happening there?
Not sure why logcat doesn't show anything useful. But when executing it, it is giving an android.os.NetworkOnMainThreadException, which can explain the problem. So as they say in the comments: try using the enque method with a callback, this also allows you to get rid of the try/catch statement. Try to replace the code after // Service setup in your MainActivity with:
HttpBinService service = retrofit.create(HttpBinService.class);
Call<HttpBinService.Response> call = service.getIp();
call.enqueue(new Callback<HttpBinService.Response>() {
#Override
public void onResponse(Call<HttpBinService.Response> call, Response<HttpBinService.Response> response) {
if (response.isSuccessful()){
Log.i("PROVARETROFIT", "OK");
//((TextView)findViewById(R.id.testo)).setText(res.body().getOrigin());
System.out.println(response.body().getOrigin());
} else {
System.out.println("Unsuccesfull");
}
}
#Override
public void onFailure(Call<HttpBinService.Response> call, Throwable t) {
System.out.println("Call failed");
}
});
in android +API19: I made a SMS app and i just need to receive a sms in it but when my application is set as default, the phone's itself sms app gets disabled and can not send message. The only thing that i need is to receive a message.
But because of that the message app of phone gets disabled and a message can not be sent, guide please, what could i do?
i just need to receive sms!
<receiver
android:name=".ReceiverSms"
android:permission="android.permission.BROADCAST_SMS"
android:enabled="true"
>
<intent-filter android:priority="999999">
<action android:name="android.provider.Telephony.SMS_DELIVER" />
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
code:
public class ReceiverSms extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
HelperWork.toastShower(context, "Runned");
boolean pswDare = true;
Bundle extras = intent.getExtras();
if (extras == null) {
return;
}
Object[] smsExtras = (Object[]) extras.get(SmsConstant.PDUS);
ContentResolver contentResolver = context.getContentResolver();
Uri smsUri = Uri.parse(SmsConstant.SMS_URI);
String body = null;
String address = null;
for (Object smsExtra: smsExtras) {
byte[] smsBytes = (byte[]) smsExtra;
SmsMessage smsMessage = SmsMessage.createFromPdu(smsBytes);
HelperWork.toastShower(context, body);
body = smsMessage.getMessageBody();
address = smsMessage.getOriginatingAddress();
// do other somthing
}
ContentValues values = new ContentValues();
values.put(SmsConstant.COLUMN_ADDRESS, address);
values.put(SmsConstant.COLUMN_BODY, body);
Uri uri = contentResolver.insert(smsUri, values);
}
}
By looking at the android developer's blog
Other apps that only want to read new messages can instead receive the SMS_RECEIVED_ACTION broadcast intent when a new SMS arrives. However, only the app that receives the SMS_DELIVER_ACTION broadcast (the user-specified default SMS app) is able to write to the SMS Provider defined by the android.provider.Telephony class and subclasses.
So if you only want to receive SMS, then only use SMS_RECEIVED_ACTION and remove SMS_DELIVER_ACTION. You don't have to make your app default in order to only receive SMS.
I am attempting to access metadata for an activity from the manifest file.
The manifest looks like this :
<activity
android:name="co.uk.benbun.nvrrclubapp.MainActivity"
android:label="#string/app_name" >
<meta-data android:value="newstag" android:name="NEWS"></meta-data>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The code to access it, looks like this :
try {
ApplicationInfo ai = getPackageManager().getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
String myApiKey = bundle.getString("NEWS");
} catch (NameNotFoundException e) {
Log.e("metadata", "Failed to load meta-data, NameNotFound: " + e.getMessage());
feedTag = "NEWS";
} catch (NullPointerException e) {
Log.e("metadata", "Failed to load meta-data, NullPointer: " + e.getMessage());
feedTag = "NEWS";
}
When I execute the code I always get the nullPointerException.
What am I doing wrong?
The documentation for PackageManager.GET_META_DATA says:
ComponentInfo flag: return the metaData data Bundles that are
associated with a component. This applies for any API returning a
ComponentInfo subclass.
You are calling getApplicationInfo() which returns an ApplicationInfo object. ApplicationInfo does not inherit from ComponentInfo, so this object will not have any meta-data. You need to get the ActivityInfo for your MainActivity in order to get the meta-data (ActivityInfo is a subclass of ComponentInfo).