I'm trying to send sensor data from my wear device to the handheld. The problem is that the onMessageReceived function of my WearableListenerService is never called, even though it gets created.
The package names of the wear and mobile apps are the same, also here's the entry for the service in the manifest file:
<service
android:name=".WatchDataReceiver"
android:enabled="true"
android:exported="true" >
</service>
On my handheld in the MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, WatchDataReceiver.class));
setContentView(R.layout.activity_fullscreen);
...
}
On my handheld, the service:
public class WatchDataReceiver extends WearableListenerService {
#Override
public void onCreate() {
super.onCreate();
Log.i(WatchDataReceiver.class.getSimpleName(), "WEAR create");
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.i(WatchDataReceiver.class.getSimpleName(), "WEAR Data changed " );
}
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.i(WatchDataReceiver.class.getSimpleName(), "WEAR Message " + messageEvent.getPath());
}
}
On the watch/wear:
public class MainActivity extends Activity implements SensorEventListener {
private static final String LOG_TAG = "Watch: ";
private SensorManager sensorManager;
private Sensor accelerometer;
private GoogleApiClient mGoogleApiClient;
private String msg = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
if (accelerometer != null) {
Log.v(LOG_TAG, "Accelerometer registered!");
}
else {
Log.v(LOG_TAG, "Accelerometer _not_ registered!");
}
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER && event.values.length > 0) {
double value_x = event.values[0];
double value_y = event.values[1];
double value_z = event.values[2];
msg = Double.toString(value_x) + ";" + Double.toString(value_y) + ";" + Double.toString(value_z);
sendMessageToHandheld(msg);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//TODO
}
private void sendMessageToHandheld(String msg) {
if (mGoogleApiClient == null)
return;
final String message = msg;
Log.d(LOG_TAG,"sending a message to handheld: "+message);
// use the api client to send the heartbeat value to our handheld
final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
final List<Node> nodes = result.getNodes();
if (nodes != null) {
for (int i=0; i<nodes.size(); i++) {
final Node node = nodes.get(i);
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), message, null);
}
}
}
});
}
}
According to LogCat the correct handheld is found because in sendMessageToHandheld right after the actual sendMessage it do a Log.d with the name of the node.
What am I missing?
You have to add this IntentFilter to your service:
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
It tells the system to take care of the Service lifecycle (ie starting it if needed).
Related
I'm trying to implement a temperature sensor on a virtual Pixel 4a, Ambient Temp sensor is included according to list of sensors.
When I run the program, the textView continues to print "Hello world!" instead of what setText in the onSensorChanged method provides.
Here is my code, any help will be amazing:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager sensorManager;
private TextView textView;
private Sensor tempSensor;
private Boolean tempSensorAvailable;
private int activityCode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACTIVITY_RECOGNITION)
!= PackageManager.PERMISSION_GRANTED) {
requestActivityPermission();
}
textView = findViewById(R.id.textView);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) != null) {
tempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
tempSensorAvailable = true;
} else {
textView.setText("Temperature Sensor is not available.");
tempSensorAvailable = false;
}
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
textView.setText(sensorEvent.values[0] + " Celsius");
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
#Override
protected void onResume() {
super.onResume();
if (tempSensorAvailable) {
sensorManager.registerListener(this, tempSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
protected void onPause() {
super.onPause();
if (tempSensorAvailable) {
sensorManager.unregisterListener(this);
}
}
public void requestActivityPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.
ACTIVITY_RECOGNITION)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("Permission is needed to run this app.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACTIVITY_RECOGNITION},
activityCode);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACTIVITY_RECOGNITION},
activityCode);
}
}
You mus call SensroManager.registerListener():
https://developer.android.com/reference/android/hardware/SensorManager#registerListener(android.hardware.SensorEventListener,%20android.hardware.Sensor,%20int)
I am using sinch Video calling API for my android application. But when the app is in the background, whenever the user is offline i.e user cleared app from the recent tab, he was unable to get the call. I used Firebase for pushing notification whenever the user is offline, but it is not getting triggered all the time, it is getting triggered sometimes only. can anyone suggest me how to push notification of incoming call when the user cleared the app from recent and will sinch actually run in the background?
public class SinchService extends Service {
private static final String APP_KEY = "key";
private static final String APP_SECRET = "secret";
private static final String ENVIRONMENT = "clientapi.sinch.com";
public static final String CALL_ID = "CALL_ID";
static final String TAG = SinchService.class.getSimpleName();
private SinchServiceInterface mSinchServiceInterface = new SinchServiceInterface();
private SinchClient mSinchClient;
private String mUserId;
static Context context;
private StartFailedListener mListener;
#Override
public void onCreate() {
super.onCreate();
}
/* #Override
public void onDestroy() {
if (mSinchClient != null && mSinchClient.isStarted()) {
mSinchClient.terminate();
}
super.onDestroy();
}*/
private void start(String userName,String fcm_token) {
if (mSinchClient == null) {
mUserId = userName;
/*LooperThread looperThread = new LooperThread();
looperThread.start();*/
/* new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});*/
mSinchClient = Sinch.getSinchClientBuilder().context(getApplicationContext()).userId(mUserId)
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.build();
//Log.d("OnMsg","coming after getSinchServiceInterface()");
mSinchClient.setSupportMessaging(true);
mSinchClient.setSupportCalling(true);
mSinchClient.setSupportManagedPush(true);
mSinchClient.setSupportPushNotifications(true);
mSinchClient.startListeningOnActiveConnection();
/* mSinchClient.startListeningOnActiveConnection();
mSinchClient.setSupportActiveConnectionInBackground(true);*/
// mSinchClient.setSupportActiveConnectionInBackground(true);
// mSinchClient.startListeningOnActiveConnection();
/* mSinchClient.setSupportManagedPush(true);
mSinchClient.setSupportPushNotifications(true);*/
// Log.d("fcm:","fcm token in bytes "+ fcm_token.getBytes());
mSinchClient.checkManifest();
mSinchClient.addSinchClientListener(new MySinchClientListener());
mSinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
mSinchClient.start();
// mSinchClient.registerPushNotificationData(fcm_token.getBytes());
}
}
class LooperThread extends Thread {
public Handler mHandler;
#Override
public void run() {
// Initialize the current thread as a Looper
// (this thread can have a MessageQueue now)
Looper.prepare();
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// process incoming messages here
/* mSinchClient.setSupportMessaging(true);
mSinchClient.setSupportCalling(true);
mSinchClient.setSupportManagedPush(true);
mSinchClient.setSupportPushNotifications(true);
mSinchClient.startListeningOnActiveConnection();
*//* mSinchClient.startListeningOnActiveConnection();
mSinchClient.setSupportActiveConnectionInBackground(true);*//*
// mSinchClient.setSupportActiveConnectionInBackground(true);
// mSinchClient.startListeningOnActiveConnection();
*//* mSinchClient.setSupportManagedPush(true);
mSinchClient.setSupportPushNotifications(true);*//*
// Log.d("fcm:","fcm token in bytes "+ fcm_token.getBytes());
mSinchClient.checkManifest();
mSinchClient.addSinchClientListener(new MySinchClientListener());
mSinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
mSinchClient.start();*/
}
};
// Run the message queue in this thread
Looper.loop();
}
}
private void stop() {
if (mSinchClient != null) {
mSinchClient.terminate();
mSinchClient = null;
}
}
private boolean isStarted() {
return (mSinchClient != null && mSinchClient.isStarted());
}
#Override
public IBinder onBind(Intent intent) {
return mSinchServiceInterface;
}
public class SinchServiceInterface extends Binder {
public Call callUserVideo(String userId) {
return mSinchClient.getCallClient().callUserVideo(userId);
}
public String getUserName() {
return mUserId;
}
public boolean isStarted() {
return SinchService.this.isStarted();
}
public void startClient(String userName,String token) {
start(userName,token);
}
public void stopClient() {
stop();
}
public void setStartListener(StartFailedListener listener) {
mListener = listener;
}
public Call getCall(String callId) {
return mSinchClient.getCallClient().getCall(callId);
}
public VideoController getVideoController() {
if (!isStarted()) {
return null;
}
return mSinchClient.getVideoController();
}
public AudioController getAudioController() {
if (!isStarted()) {
return null;
}
return mSinchClient.getAudioController();
}
}
public interface StartFailedListener {
void onStartFailed(SinchError error);
void onStarted();
}
private class MySinchClientListener implements SinchClientListener {
#Override
public void onClientFailed(SinchClient client, SinchError error) {
if (mListener != null) {
mListener.onStartFailed(error);
}
/* mSinchClient.terminate();
mSinchClient = null;*/
}
#Override
public void onClientStarted(SinchClient client) {
Log.d(TAG, "SinchClient started");
if (mListener != null) {
mListener.onStarted();
mSinchClient.startListeningOnActiveConnection();
}
}
#Override
public void onClientStopped(SinchClient client) {
Log.d(TAG, "SinchClient stopped");
}
#Override
public void onLogMessage(int level, String area, String message) {
switch (level) {
case Log.DEBUG:
Log.d(area, message);
break;
case Log.ERROR:
Log.e(area, message);
break;
case Log.INFO:
Log.i(area, message);
break;
case Log.VERBOSE:
Log.v(area, message);
break;
case Log.WARN:
Log.w(area, message);
break;
}
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client,
ClientRegistration clientRegistration) {
}
}
public class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
Log.d("OnMsg", "Incoming call");
Intent intent = new Intent(SinchService.this, IncomingCallScreenActivity.class);
intent.putExtra(CALL_ID, call.getCallId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SinchService.this.startActivity(intent);
}
}
}
public class PlaceCallActivity extends BaseActivity implements SinchService.StartFailedListener/*,PushTokenRegistrationCallback*/{
private Button mCallButton;
private EditText mCallName;
Button stopButton;
String token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//initializing UI elements
mCallName = findViewById(R.id.callName);
mCallButton = findViewById(R.id.callButton);
mCallButton.setEnabled(false);
mCallButton.setOnClickListener(buttonClickListener);
stopButton = findViewById(R.id.stopButton);
stopButton.setEnabled(false);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("test", "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
token = task.getResult().getToken();
// Log and toast
//String msg = getString(R.string.msg_token_fmt, token);
Log.d("test", token);
Toast.makeText(PlaceCallActivity.this, token, Toast.LENGTH_SHORT).show();
}
});
stopButton.setOnClickListener(buttonClickListener);
/* try {
#SuppressLint("WrongThread") String regId = FirebaseInstanceId.getInstance().getToken("Your-Sender-ID", "FCM");
} catch (IOException e) {
e.printStackTrace();
}*/
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
getSinchServiceInterface().startClient(new PreferenceUtils(PlaceCallActivity.this).getName(),token);
}
}, 4000);
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
TextView userName = (TextView) findViewById(R.id.loggedInName);
getSinchServiceInterface().setStartListener(this);
userName.setText(new PreferenceUtils(PlaceCallActivity.this).getName());
mCallButton.setEnabled(true);
stopButton.setEnabled(true);
}
/* #Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}*/
/*//to kill the current session of SinchService
private void stopButtonClicked() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finish();
}*/
//to place the call to the entered name
private void callButtonClicked() {
String userName = mCallName.getText().toString();
if (userName.isEmpty()) {
Toast.makeText(this, "Please enter a user to call", Toast.LENGTH_LONG).show();
return;
}
Call call = getSinchServiceInterface().callUserVideo(userName);
String callId = call.getCallId();
Log.d("test","call id is"+callId);
Intent callScreen = new Intent(this, CallScreenActivity.class);
callScreen.putExtra(SinchService.CALL_ID, callId);
callScreen.putExtra("TOKEN", token);
startActivity(callScreen);
}
private OnClickListener buttonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.callButton:
callButtonClicked();
break;
case R.id.stopButton:
// stopButtonClicked();
break;
}
}
};
#Override
public void onStartFailed(SinchError error) {
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onStarted() {
}
}
We want to take a snapshot from Google Map in Fragment and not save into External Storage it send through retrofit API, and also I have done but facing one problem image only get in black color not show map on imageview.
SupportMapFragment mapFragment;
private GoogleMap mMap;
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
private TextView resutText;
private ImageView marker;
ImageView iconnn;
private LatLng mCenterLatLong;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT < 22)
setStatusBarTranslucent(false);
else
setStatusBarTranslucent(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
resutText = (TextView) findViewById(R.id.dragg_result);
marker=(ImageView)findViewById (R.id.marker1);
iconnn=(ImageView)findViewById (R.id.iconnn);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
configureCameraIdle();
}
private void configureCameraIdle() {
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(MapsActivity.this);
CameraUpdate center= CameraUpdateFactory.newLatLng(latLng);
CameraUpdate zoom= CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
try {
List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
if (!locality.isEmpty() && !country.isEmpty())
resutText.setText(locality + " " + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraIdleListener(onCameraIdleListener);
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
float zoomLevel = mMap.getCameraPosition().zoom;
//use zoomLevel value..
}
});
new CountDownTimer (5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
captureScreen();
}
}.start ();
}
public void captureScreen()
{
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback()
{
#Override
public void onSnapshotReady(Bitmap snapshot)
{
// TODO Auto-generated method stub
String filePath = System.currentTimeMillis() + ".jpeg";
iconnn.setImageBitmap (snapshot);
}
};
mMap.snapshot(callback);
}
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}`` SupportMapFragment mapFragment;
private GoogleMap mMap;
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
private TextView resutText;
private ImageView marker;
ImageView iconnn;
private LatLng mCenterLatLong;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT < 22)
setStatusBarTranslucent(false);
else
setStatusBarTranslucent(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
resutText = (TextView) findViewById(R.id.dragg_result);
marker=(ImageView)findViewById (R.id.marker1);
iconnn=(ImageView)findViewById (R.id.iconnn);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
configureCameraIdle();
}
private void configureCameraIdle() {
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(MapsActivity.this);
CameraUpdate center= CameraUpdateFactory.newLatLng(latLng);
CameraUpdate zoom= CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
try {
List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
if (!locality.isEmpty() && !country.isEmpty())
resutText.setText(locality + " " + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraIdleListener(onCameraIdleListener);
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
float zoomLevel = mMap.getCameraPosition().zoom;
//use zoomLevel value..
}
});
new CountDownTimer (5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
captureScreen();
}
}.start ();
}
public void captureScreen()
{
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback()
{
#Override
public void onSnapshotReady(Bitmap snapshot)
{
// TODO Auto-generated method stub
String filePath = System.currentTimeMillis() + ".jpeg";
iconnn.setImageBitmap (snapshot);
}
};
mMap.snapshot(callback);
}
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
}
}
}
I am trying to share image and text via whatsapp using implicit intent but I'm not able to share. I have searched the net but could not find any proper explanation. I have attached the code below.
... the code works without errors.but it dose not share content with whatsapp. i have searched all the places in google and on stackoverflow .but could not encounter with any proper explanation
public class MainActivity extends Activity implements View.OnClickListener {
TextView title_text,text_description;
ImageButton main_image;
Button button;
private static String url = "random url ";
private static final String TAG_ID = "title";
private static final String TAG_IMAGE = "image_url";
private static final String TAG_DESC = "product_desc";
String id;
String name;
String image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_description=(TextView)findViewById(R.id.text_description);
title_text=(TextView)findViewById(R.id.text_title);
main_image=(ImageButton)findViewById(R.id.image_main);
button= (Button) findViewById(R.id.button);
button.setOnClickListener(this);
new GetContacts().execute();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"whatsappsharing",Toast.LENGTH_SHORT).show();
Intent whatsappintent=new Intent();
whatsappintent.setAction(Intent.ACTION_SEND);
Uri uri= Uri.parse(TAG_IMAGE);
whatsappintent.setType("text/plain");
whatsappintent.putExtra(Intent.EXTRA_TEXT, "hello nathar");
whatsappintent.setType("image/jpeg");
whatsappintent.putExtra(Intent.EXTRA_STREAM,uri);
whatsappintent.setPackage("com.whatsapp");
startActivity(whatsappintent);
}
private class GetContacts extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
id = jsonObj.getString(TAG_ID);
Log.d(TAG_ID,"title");
name = jsonObj.getString(TAG_DESC);
Log.d(TAG_DESC,"name");
image=jsonObj.getString(TAG_IMAGE);
Log.d(TAG_IMAGE,"image");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (image!=null && !image.equalsIgnoreCase(""))
Picasso.with(MainActivity.this).load(image).fit().into(main_image);
title_text.setText(id);
text_description.setText(name);
}
}
}
Try this piece of code:
Uri imageUri = Uri.parse(TAG_IMAGE);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
// Target whatsapp:
shareIntent.setPackage("com.whatsapp");
// Add text and then Image URI
shareIntent.putExtra(Intent.EXTRA_TEXT, <Message_text>);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(shareIntent);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
where Message_text will be sent as a image caption
I am adding my two separate android activities in one application, one of my activity having volley library but it gives me an exception that appcontroller(volley library) its an application not an activity please help me out
Ya, you have mention in your manifest file appcontroller class as Application. This solves the exception.
Main Acitivity:
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
// Fragments and ViewPager Initialization
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec,String message,int picture,Context x)
{
tabSpec.setContent(new MyTabFactory(activity));
View tabIndicator = LayoutInflater.from(x).inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(message);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setBackgroundDrawable(x.getResources().getDrawable(picture));
icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
tabSpec.setIndicator(tabIndicator);
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLUE);
//mTabHost.getTabWidget().setDividerDrawable(R.Color.transperant);
}
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.CYAN);// selected
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((ImageView) view);
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// TODO Put here your Fragments
NewSampleFragment f1 = NewSampleFragment.newInstance(getApplicationContext(),R.layout.newfragment_a);
MySampleFragment f2 = MySampleFragment.newInstance("Sample Fragment 2");
MySampleFragment f3 = MySampleFragment.newInstance("Sample Fragment 3");
MySampleFragment f4 = MySampleFragment.newInstance("Sample Fragment 4");
MySampleFragment f5 = MySampleFragment.newInstance("Sample Fragment 5");
fList.add(f1);
fList.add(f2);
fList.add(f3);
fList.add(f4);
fList.add(f5);
return fList;
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab1"),"Grocery",R.drawable.movies,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab2"),"Crockery",R.drawable.artist,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab3"),"Foods",R.drawable.song,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab4"),"Drinks",R.drawable.shopping,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab5"),"Toys",R.drawable.play,getApplicationContext());
mTabHost.setOnTabChangedListener(this);
}
}
OfferActivity (This should be open when button pressed)
public class OfferActivity extends Activity
{
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private String URL_FEED = "http://nusdtech.com/public_html/checking2.php";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
JsonArrayRequest movieReq = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
FeedItem movie = new FeedItem();
movie.setId(obj.getInt("id"));
movie.setName(obj.getString("name"));
// Image might be null sometimes
String image = obj.isNull("image") ? null : obj
.getString("image");
movie.setImge(image);
movie.setStatus(obj.getString("status"));
movie.setProfilePic(obj.getString("profilePic"));
//movie.setTimeStamp(obj.getString("price"));
movie.setPrice(obj.getString("price"));
movie.setDate(obj.getString("dates"));
feedItems.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
listAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
AppController:
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Activity that contain fragment buttons
public class NewSampleFragment extends Fragment {
private static View mView;
private Context con;
public static final NewSampleFragment newInstance(Context con,int layout) {
NewSampleFragment f = new NewSampleFragment();
con=con;
Bundle b = new Bundle();
b.putInt("mylayout",layout);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = getArguments().getInt("mylayout");
mView = inflater.inflate(R.layout.newfragment_a, container, false);
Button button = (Button) mView.findViewById(R.id.bactivity);
Button offer=(Button) mView.findViewById(R.id.aactivity);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(getActivity(), ListViewDemo.class);
//Optional parameters
getActivity().startActivity(myIntent);
Log.e("Error","Kashif");
}
});
offer.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startApplication("uzair.sabir.app.OfferActivity");
}
});
return mView;
}
public void startApplication(String application_name){
try{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveinfo_list = getActivity().getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info:resolveinfo_list){
if(info.activityInfo.packageName.equalsIgnoreCase(application_name)){
launchComponent("uzair.sabir.app", "OfferActivity");
break;
}
}
}
catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "There was a problem loading the application: "+application_name,Toast.LENGTH_SHORT).show();
Log.e("Error",e.getMessage());
}
}
private void launchComponent(String packageName, String name){
Intent launch_intent = new Intent("android.intent.action.MAIN");
launch_intent.addCategory("android.intent.category.LAUNCHER");
launch_intent.setComponent(new ComponentName(packageName, name));
launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(launch_intent);
}
}