Cannot invoke method - Method Channel in Flutter - flutter

I'm trying to write platform specific code in Flutter. First of all, created a method to obtain battery temperature inside MainActivity.kt
This is my full code in MainActivity.kt file:
package com.xyz.zyx
import android.os.BatteryManager;
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
class MainActivity: FlutterFragmentActivity() {
// ...
private var batteryManager: BatteryManager? = null
private var methodChannel: MethodChannel? = null
private var temperatureChannel: EventChannel? = null
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "battery").setMethodCallHandler {
call, result ->
if (call.method == "getBatteryTemperature") {
val batteryTemperature = getBatteryTemperature()
if (batteryTemperature != -1) {
result.success(batteryTemperature)
} else {
result.error("UNAVAILABLE", "Battery temperature not available.", null)
}
} else {
result.notImplemented()
}
}
}
private fun getBatteryTemperature(): Int {
val batteryStatus: Intent? =
IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
this.registerReceiver(null, ifilter)
val batteryTemperature: Int
val batteryManager =
getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryTemperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -99)
return batteryTemperature
}
}
}
This is how I call my platform specific code from Flutter side:
static const platform = MethodChannel('battery');
Future<void> _getBatteryTemp() async {
String batteryLevel;
try {
var result = await platform.invokeMethod('getBatteryTemperature');
batteryLevel = 'Battery temperature at $result % .';
} on PlatformException catch (e) {
batteryLevel = "Failed to get battery level: '${e.message}'.";
}
print(batteryLevel);
}
Lastly, this is the error on Flutter app running on an Android device. It throws an MissingPluginException even though there is a method called getBatteryTemperature, it says there isn't.
E/flutter (25427): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method getBatteryTemperature on channel battery)
E/flutter (25427): #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:294:7)
Is there something did I miss to implement in my code? Why does it not work?

Related

i am trying to use method channel to access camera and take photo , but how can i get the file from method channel respons

package com.example.unit_testing
import android.content.Intent
import android.graphics.Bitmap
import android.provider.MediaStore
import android.view.WindowManager.LayoutParams
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private val METHOD_CHANNEL_NAME = "com.jinto/method"
private var methodChannel: MethodChannel? = null
private val cameraRequest = 1888
var imageView: Bitmap? = null
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
window.addFlags(LayoutParams.FLAG_SECURE)
super.configureFlutterEngine(flutterEngine)
// Setup Channels
setupChannels(flutterEngine.dartExecutor.binaryMessenger)
}
override fun onDestroy() {
teardownChannels()
super.onDestroy()
}
private fun setupChannels(messenger: BinaryMessenger) {
methodChannel = MethodChannel(messenger, METHOD_CHANNEL_NAME)
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
methodChannel!!.setMethodCallHandler { call, result ->
if (call.method == "cameraOn") {
startActivityForResult(cameraIntent, cameraRequest)
result.success(imageView)
} else {
result.notImplemented()
}
}
}
private fun teardownChannels() {
methodChannel!!.setMethodCallHandler(null)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == cameraRequest && resultCode == RESULT_OK) {
val imageBitmap = data?.extras?.get("data") as Bitmap
println("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww${imageBitmap.width}")
imageView = imageBitmap
}
}
}
if we pass the bitmap(imageView) it won't work , initially it retune nothing , after the camera service started not getting any data
how can i convert the bitmap into file and return it, can you help me to solve this problem,
This is my code to get data from platform side,
Future<void> _checkAvailability() async {
try {
var apiImage = await methodChannel.invokeMethod("cameraOn");
print('$apiImage');
} on PlatformException catch (e) {
print('error');
print(e);
}
}

flutter - Invoking method from android activity

I tried to app to app communication on Flutter - Android.
First, Android app(A) bound Flutter service which Android Service(B).
Then A call to B and B start activity.
Second, activity invoke method on Flutter using MethodChannel.
But I faced the Exception.
How to invoke flutter method on Android activity that start with Android service.
Exception
E/flutter (12950): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getDatabasesPath on channel com.tekartik.sqflite)
E/flutter (12950): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
MyService.kt
class MyService : Service() {
private lateinit var mMessenger: Messenger
internal class IncomingHandler(context: Context,
private val applicationContext: Context = context.applicationContext
) : Handler() {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
when (msg.what) {
WHAT_REQ_VP -> {
applicationContext.startActivity(Intent(applicationContext,
TempActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
}
}
override fun onBind(intent: Intent): IBinder {
mMessenger = Messenger(IncomingHandler(this))
return mMessenger.binder
}
}
TempActivity.kt
class TempActivity : FlutterActivity() {
private lateinit var channel: MethodChannel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_temp)
val backgroundFlutterView = FlutterNativeView(baseContext, true)
channel = MethodChannel(backgroundFlutterView, "com.example.test")
GeneratedPluginRegistrant.registerWith(this)
channel.setMethodCallHandler { call, result -> run {
when (call.method) {
"result" -> {
print(call.argument<String>("result"))
}
else -> {}
}
} }
findViewById<Button>(R.id.btn_confirm).setOnClickListener {
val arguments = HashMap<String, String>()
arguments["message"] = "From Android"
channel.invokeMethod("test", arguments)
}
}
}
temp.dart
import 'package:flutter/services.dart';
class Temp {
static final _singleton = Temp._internal();
static const MethodChannel _channel = const MethodChannel('com.example.test');
factory Temp() {
return _singleton;
}
Temp._internal() {
_channel.setMethodCallHandler(_handleMethod);
}
_handleMethod(MethodCall call) {
switch (call.method) {
case 'test':
print('_handleMethod: ${call.method}');
_channel.invokeMethod('result', 'Result from flutter client');
}
}
}

Mapbox shows wrong current location in android

I am using Mapbox sdk for android.
I want to get current location,and i am also getting,but the problem is:
I am getting wrong current location,which is near Nigeria.
can anyone help me to get perfect location??
here is my gradle file's details:
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.app.mapboxdemo"
minSdkVersion 15
targetSdkVersion 27
multiDexEnabled true
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.intuit.ssp:ssp-android:1.0.5'
implementation 'com.intuit.sdp:sdp-android:1.0.5'
implementation('com.mapbox.mapboxsdk:mapbox-android-sdk:6.1.3#aar') {
transitive = true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-locationlayer:0.5.3'
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-cluster-utils:0.3.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.13.0'
implementation('com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.13.0') {
transitive = true
}
}
and here are the permisssions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-feature android:name="android.hardware.location.gps"/>
and here is my code for getting user location:
package com.app.mapboxdemo;// classes needed to initialize map
import com.mapbox.api.geocoding.v5.MapboxGeocoding;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
// classes needed to add location layer
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import android.location.Location;
import com.mapbox.mapboxsdk.geometry.LatLng;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.CameraMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
// classes needed to add a marker
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
// classes needed to launch navigation UI
import android.view.View;
import android.widget.Button;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
// classes needed to add location layer
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import android.location.Location;
import com.mapbox.mapboxsdk.geometry.LatLng;
import android.support.annotation.NonNull;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
// classes needed to add a marker
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
// classes needed to launch navigation UI
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import java.util.List;
public class NavigationActivity extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
// variables for adding location layer
private static MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
// variables for adding a marker
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
EditText edtLatitude, edtLongitude;
private Button button, buttonGetLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_draw_navigation);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
/*mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
}
});*/
button = findViewById(R.id.startButton);
edtLatitude = findViewById(R.id.edtLatitude);
edtLongitude = findViewById(R.id.edtLongitude);
buttonGetLocation = findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "buttonGetLocation onClick: " );
checkLatLong(mapboxMap);
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(origin)
.destination(destination)
.shouldSimulateRoute(simulateRoute)
.build();
Log.e(TAG, "onClick: Start Button");
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(NavigationActivity.this, options);
}
});
}
});
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings({"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings({"MissingPermission"})
private void initializeLocationEngine() {
LocationEngineProvider locationEngineProvider = new LocationEngineProvider(this);
locationEngineProvider.obtainLocationEngineBy(LocationEngine.Type.ANDROID);
locationEngine = locationEngineProvider.obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
locationEngine.requestLocationUpdates();
Location lastLocation = locationEngine.getLastLocation();
// Log.e(TAG, "initializeLocationEngine: Latitude is"+lastLocation.getLatitude()+" Longitude is "+lastLocation.getLongitude() );
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
finish();
}
}
#Override
#SuppressWarnings({"MissingPermission"})
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
locationEngine.removeLocationEngineListener(this);
}
}
#Override
#SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public void checkLatLong(MapboxMap mapboxMap) {
if ((edtLatitude.getText() == null && edtLatitude.getText().length() == 0) && (edtLongitude.getText() == null && edtLongitude.getText().length() == 0)) {
Toast.makeText(getApplicationContext(), "Enter Proper Longitude and Latitude.", Toast.LENGTH_LONG).show();
} else {
if (destinationMarker != null) {
map.removeMarker(destinationMarker);
}
destinationCoord = new LatLng(Double.parseDouble(edtLatitude.getText().toString()), Double.parseDouble(edtLongitude.getText().toString()));
destinationMarker = map.addMarker(new MarkerOptions()
.position(destinationCoord)
);
Log.e(TAG, "checkLatLong: ");
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
setCameraPosition(originLocation);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
}
}
}
please help me to get user location.
Help is appreciated,i referred a lot of questions but didnt get any solution.
than also,suggest any help in reffering questions too.
I Solved it by making few changes in methods initializeLocationEngine() and enableLocationPlugin()
Here are the modified methods for answer:
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
getLifecycle().addObserver(locationPlugin);
Log.e(TAG, "enableLocationPlugin:Permission Granted" );
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
Log.e(TAG, "enableLocationPlugin:Permission Not Granted" );
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.addLocationEngineListener(this);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}

How to read all apps notification in my app when my app is closed?

package com.example.notificationlistener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn)
{
Log.i("From service","onNotificationPosted");
String pack = sbn.getPackageName();
// if("com.twitter.android".equalsIgnoreCase(pack))
// if("com.google.android.gm".equalsIgnoreCase(pack))
{
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn)
{
Log.i("Msg","Notification Removed");
}
}
this is my service class
package com.example.notificationlistener;
import java.util.Locale;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements TextToSpeech.OnInitListener{
TableLayout tableLayout;
TextToSpeech textToSpeech;
String text = "noText";
String title = "noTitle";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableLayout = (TableLayout)findViewById(R.id.tab);
textToSpeech = new TextToSpeech(this, null);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
Log.w("From MainActivity", "broadcast receiver is called");
String pack = intent.getStringExtra("package");
String ticker = intent.getStringExtra("ticker");
title = intent.getStringExtra("title");
text = intent.getStringExtra("text");
Log.d("mainActivity_pack", pack);
Log.d("mainActivity_title", title);
Log.d("mainActivity_text", text);
Log.d("mainActivity_ticker", ticker);
// Log.d("mainActivity", sender);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "New Message", System.currentTimeMillis()+5000);
notification.setLatestEventInfo(context, title, text, null);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notificationManager.notify(2, notification);
speak();
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT,1.0f));
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#0B0719"));
textview.setText(Html.fromHtml(pack +"<br><b>" + title + " : </b>" + text));
tr.addView(textview);
tableLayout.addView(tr);
}
};
protected void onDestroy()
{
super.onDestroy();
if (textToSpeech != null)
{
textToSpeech.stop();
textToSpeech.shutdown();
}
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else
{
speak();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speak()
{
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}`enter code here`
}
this is my activity. i am trying to read notification and resend them through my app so done this and i am able to get the notifications but when my app is closed its not working so please suggest me some changes or suggestions...thanks
Put your broadcast receiver into a service. Activities don't run when the app is closed. Services do. Start your services from your activity. Then they will continue to run even after closing the app.

JMapframe displays only a single shapefile

I used the Netbeans and GeoTools to program a graphical interface to display multiple shapefiles in the same JmapFrame. I used the following code but I do not know, when execute, it display only one shapefile.Svp, someone can help me, I await your answers.
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import java.io.File;
import org.geotools.data.FeatureSource;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.map.DefaultMapContext;
import org.geotools.map.MapContext;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.simple.SimpleFeature;
/**
*
* #author Brahim
*/
class ImportVecteur2
{
private JMapFrame fenMap;
private MapContext mapContext;
ImportVecteur2(JMapFrame fenMap)
{
//this.mapContext = mapContext;
this.fenMap = fenMap;
}
#SuppressWarnings("static-access")
public void chercheAfficheVecteur() //throws Exception
{
try
{
File file = JFileDataStoreChooser.showOpenFile("shp", null);
if (file == null)
{
return;
}
FileDataStore store = FileDataStoreFinder.getDataStore(file);
FeatureSource featureSource = store.getFeatureSource();
//get vertices of file
// Create a map context and add our shapefile to it
mapContext = new DefaultMapContext();
mapContext.addLayer(featureSource, null);
// Now display the map
fenMap.enableLayerTable(true);
fenMap.setMapContext(mapContext);
fenMap.setVisible(true);
}
Each time you call chercheAfficheVecteur you create a new MapContext so the previous one is thrown away and with it your previous shapefile. If you change the method to be
public void chercheAfficheVecteur() {
try {
File file = JFileDataStoreChooser.showOpenFile("shp", null);
if (file == null) {
return;
}
FileDataStore store = FileDataStoreFinder.getDataStore(file);
FeatureSource featureSource = store.getFeatureSource();
//get vertices of file
// Create a map context and add our shapefile to it
if(mapContext == null){
mapContext = new DefaultMapContext();
fenMap.setMapContext(mapContext);
}
//make it look prettier
Style style = SLD.createSimpleStyle(featureSource.getSchema());
mapContext.addLayer(featureSource, style);
}
and
ImportVecteur2(JMapFrame fenMap)
{
//this.mapContext = mapContext;
this.fenMap = fenMap;
fenMap.enableLayerTable(true);
fenMap.setVisible(true);
}
It should work better.
After further testing (i.e. I actually compiled some code) - MapContext is deprecated (and has been for some time) please use MapContent.
package org.geotools.tutorial.quickstart;
import java.awt.Color;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import org.geotools.data.FeatureSource;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.data.JFileDataStoreChooser;
public class Test {
private static final Color[] color = { Color.red, Color.blue, Color.green,
Color.MAGENTA };
private static MapContent mapContext;
private static JMapFrame fenMap;
public static void main(String args[]) throws IOException {
Test me = new Test();
me.run();
}
public void run() throws IOException {
fenMap = new JMapFrame();
mapContext = new MapContent();
fenMap.setMapContent(mapContext);
fenMap.enableToolBar(true);
fenMap.setMinimumSize(new Dimension(300, 300));
fenMap.setVisible(true);
int i = 0;
while (chercheAfficheVecteur(i)) {
i++;
i = i % color.length;
}
}
public boolean chercheAfficheVecteur(int next) throws IOException {
File file = JFileDataStoreChooser.showOpenFile("shp", null);
if (file == null) {
return false;
}
FileDataStore store = FileDataStoreFinder.getDataStore(file);
FeatureSource featureSource = store.getFeatureSource();
// get vertices of file
// Create a map context and add our shapefile to it
if (mapContext == null) {
}
// make it look prettier
Style style = SLD.createSimpleStyle(featureSource.getSchema(), color[next]);
Layer layer = new FeatureLayer(featureSource, style);
mapContext.addLayer(layer);
return true;
}
}